"something went wrong" error on fucntion getfloat - javascript

This code works perfectly beside the last part , and I do not see where might be the error. I tested it, and the main problem is in Trade.prototype.getFloat maybe is the callback idk, (the Trade.prototype.getFloat I got it from a 3y post here on stack from other user).
3y problem: This code works perfectly besides this line: "inventory[asset.assetid].floatvalue = getFloat". As you can see it is situated in async mode, and this line initializes a request to get some value, but it cant get it couse value is undefined. I tested it, and the main problem in request, which is asynchronous too. So the answer is how to stop the async mode and wait the return of the request.
'use strict'
const config = require('../config')
const request = require('request')
const async = require('async')
const Trade = require('./index')
const MAX_RETRIES = 3
const API_URL = 'https://api.steamapis.com/steam/inventory'
Trade.prototype.getInventory = function getInventory(steamID64, appID, contextID, callback, retries) {
request(`${API_URL}/${steamID64}/${appID}/${contextID}?api_key=${config.SteamApisKey}`, (error, response, body) => {
if (!error && response.statusCode === 200) {
const items = JSON.parse(body)
const assets = items.assets
const descriptions = items.descriptions
const inventory = {}
if (descriptions && assets) {
async.forEach(descriptions, (description, cbDesc) => async.forEach(assets, (asset, cbAsset) => {
if (
description.classid !== asset.classid ||
!description.tradable ||
!description.marketable ||
description.market_hash_name.indexOf('Souvenir') > -1
) {
return cbAsset()
}
if (typeof inventory[asset.assetid] !== 'undefined') {
return cbAsset()
}
const type = Trade.prototype.getItemType(description.market_hash_name, description.type)
const wear = Trade.prototype.getItemWear(description.market_hash_name)
const inspect = Trade.prototype.getInspect(steamID64, asset.assetid, description.actions)
const getFloat = Trade.prototype.getFloat(inspect, asset.assetid, function(_float){
var data = String(_float);
inventory[asset.assetid].floatvalue = data;
inventory[asset.assetid] = asset
inventory[asset.assetid].item_type = type
inventory[asset.assetid].item_wear = wear
inventory[asset.assetid].inspect = inspect
inventory[asset.assetid].data = {
background: description.background_color,
image: description.icon_url,
tradable: description.tradable,
marketable: description.marketable,
market_hash_name: description.market_hash_name,
type: description.type,
color: description.name_color,
};
return cbAsset();
})
}));
}
return callback(null, inventory)
}
let retry = retries
if (typeof retries === 'undefined') {
retry = 0
}
retry += 1
if (retry <= MAX_RETRIES) {
return Trade.prototype.getInventory(steamID64, appID, contextID, callback, retry)
}
let statusCode = null
if (typeof response !== 'undefined' && typeof response.statusCode !== 'undefined') {
statusCode = response.statusCode
}
return callback({ error, statusCode })
})
}
Trade.prototype.getInventories = function getInventories(params, callback) {
const inventories = {}
async.each(params, (user, cb) => {
Trade.prototype.getInventory(user.steamID64, user.appID, user.contextID, (err, data) => {
inventories[user.id] = {}
inventories[user.id] = {
error: err,
items: (!err) ? Object.keys(data).map(key => data[key]) : null,
}
cb()
})
}, () => {
callback(inventories)
})
}
Trade.prototype.getItemType = function getItemType(marketHashName, type) {
if (marketHashName.indexOf('Key') !== -1) {
return { value: 0, name: 'key' }
}
if (marketHashName.indexOf('★') !== -1) {
return { value: 1, name: 'knife' }
}
if (
type.indexOf('Classified') !== -1 ||
type.indexOf('Contraband') !== -1 ||
type.indexOf('Covert') !== -1
) {
return { value: 2, name: 'rare_skin' }
}
if (
type.indexOf('Consumer Grade') !== -1 ||
type.indexOf('Base Grade') !== -1 ||
type.indexOf('Graffiti') !== -1 ||
type.indexOf('Sticker') !== -1 ||
type.indexOf('Industrial Grade') !== -1
) {
return { value: 4, name: 'misc' }
}
return { value: 3, name: 'weapon' }
}
Trade.prototype.getItemWear = function getItemWear(marketHashName) {
if (marketHashName.indexOf('Factory New') !== -1) {
return 'FN'
}
if (marketHashName.indexOf('Minimal Wear') !== -1) {
return 'MW'
}
if (marketHashName.indexOf('Field-Tested') !== -1) {
return 'FT'
}
if (marketHashName.indexOf('Well-Worn') !== -1) {
return 'WW'
}
if (marketHashName.indexOf('Battle-Scarred') !== -1) {
return 'BS'
}
return false
}
Trade.prototype.getInspect = function getInspect (steamID64, assetid, actions) {
let inspectLink = null;
if (actions) {
for (const a in actions) {
if (actions[a].name.indexOf('Inspect') !== -1) {
inspectLink = actions[a].link
inspectLink = inspectLink.replace('%owner_steamid%', steamID64)
inspectLink = inspectLink.replace('%assetid%', assetid)
}
}
}
return inspectLink
}
Trade.prototype.getFloat = function getFloat (adding, callback) {
request ("https://api.csgofloat.com:1738/?url=" + adding, (error, response, body) => {
if (!error && response.statusCode == 200) {
var floatBody = JSON.parse(body);
var float = floatBody["iteminfo"]["floatvalue"];
var id = id;
if (float != "") {
callback(float);
} else {
return "wrong";
}
} else {
console.log('something goes wrong');
return "wrong";
}
});
}

Related

how i can get a value through key

i want to know how i can get a value/numbers through key/username ?
look like that console.log(acc.${username})
my js
...
app.get("/account", (req, res) => {
loggedIn = req.cookies.loggedIn;
username = req.cookies.username;
if (loggedIn == "true") {
db.list().then(keys => {
if (keys.includes(username)) {
res.render("settings.html", { username: username })
var data = fs.readFileSync('2FA.json');
var acc = JSON.parse(data)
//////////////////////////////////////////////
console.log(acc.${username}) // i want to see a numbers in user name look like in here
/////////////////////////////////////////////
} else {
res.redirect("/logout");
}
});
} else {
res.render("notloggedin.html");
}
});
my json
[
{
"youssefnageeb": 927342
},
{
"youssefnageeb1":310686
},
{
"youssefnageeb2": 105380
},
{
"youssefnageeb3": 431816
},
{
"youssefnageeb4": 484728
}
]
I am guessing "data" is in the format mentioned above.
So, you can do
const index = data.findIndex(function isAccountRow(row) { return typeof row[username] === 'number'; })
if(index === -1) {
return res.redirect("/logout");
}
const row = data[index];
console.log(row[username]); // will be the number

Why binding a function to null context?

I am working with the following functions atm, but what confused me is why in function request, we need to bind sendRequest to null by doing sendRequest.apply(null, _arguments))?
In sendRequest definition, there is no this in it, does it not make its context binding meaningless?
function sendRequest(args = {}) {
args.data = _param(args.data);
args.method = args.method || 'GET';
args.error = isFunction(args.error) ? args.error : function () {};
args.success = isFunction(args.success) ? args.success : function () {};
args.parseResponse = args.hasOwnProperty('parseResponse') ? args.parseResponse : true;
const myXhr = new PostMessageProxyRequest();
if (args.method === 'GET') {
let queryString = '?';
if (args.url.indexOf('?') !== -1) {
queryString += '&';
}
args.url += queryString + args.data;
}
myXhr.open(args.method, baseUrl + args.url);
if (args.headers) {
for (const key in args.headers) {
if (args.headers.hasOwnProperty(key)) {
myXhr.setRequestHeader(key, args.headers[key]);
}
}
}
myXhr.setRequestHeader('Content-Type', CONTENT_TYPE.FORM);
function callError(status, response) {
if (args.parseResponse) {
try {
response = JSON.parse(response);
} catch (e) {} // eslint-disable-line no-empty
}
args.error.call(null, { status, response });
}
myXhr.onload = function () {
let content = myXhr.responseText;
if (myXhr.status >= 200 && myXhr.status <= 300) {
try {
if (content && content.length > 0 && args.parseResponse) {
content = JSON.parse(content);
}
try {
args.success.call(null, {
status: myXhr.status,
response: content
});
} catch (e) {
callError(-1, `${e.name} on success handler, msg: ${e.message}`);
}
} catch (e) {
callError(-1, `error parsing response: ${e.message}. Response: ${content}`);
}
} else {
callError(myXhr.status, content);
}
};
myXhr.onerror = function () {
callError(myXhr.status, myXhr.responseText);
};
myXhr.send(args.method === 'POST' || args.method === 'PUT' ? args.data : null);
}
function request(args = {}) {
const _arguments = arguments;
args.error = args.error || (() => {});
init()
.then(() => sendRequest.apply(null, _arguments))
.catch((options = {}) => args.error.call(null, options));
}

Linear flow of multiple intent is not working

I am working on a project of Amazon Alexa of booking a table in a restaurant and I have four intents:
makeReservation
futureOrCurrentLocation
getRestaurantName
selectRestaurants
I am facing one issue that the linear flow of intent is not working. I have stored the previous intent in the session and checked the previous intent from the session and on that basic I am calling the next intent.
But when I say Alexa with the previous intent String in the response of the current intent, it jumps to the new intent we have called, but it throws an exception.
Actually it should work like if I say some intent String in the response of other intent then it should repeat the current intent once again.
And one more issue I am facing is that I need to append the String in the user utterance like e.g.:
Alexa: "Where would you like to go?"
User: "Go to {Restaurant Name}"
I didn't want to append this "Go to" in the restaurant name.
// Lambda Function code for Alexa.
const Alexa = require("ask-sdk");
// Book a table
const makeReservation_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'makeReservation' ;
},
handle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
const responseBuilder = handlerInput.responseBuilder;
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
sessionAttributes.tableTalkType = 1;
handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
return responseBuilder
.addDelegateDirective({
name: 'futureOrCurrentLocation',
confirmationStatus: 'NONE',
slots: {}
})
.withShouldEndSession(false)
.getResponse();
},
};
const futureOrCurrentLocation_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'futureOrCurrentLocation' ;
},
async handle(handlerInput) {
const { requestEnvelope, serviceClientFactory, responseBuilder } = handlerInput;
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
let previousIntentName = getPreviousIntent(sessionAttributes);
if (previousIntentName == 'makeReservation') {
const request = handlerInput.requestEnvelope.request;
// const responseBuilder = handlerInput.responseBuilder;
const slotValues = getSlotValues(request.intent.slots);
const location = slotValues.locationType.heardAs;
const tableTalkType = sessionAttributes.tableTalkType;
let say = '';
// delegate to Alexa to collect all the required slots
const currentIntent = request.intent;
if (request.dialogState && request.dialogState !== 'COMPLETED') {
return handlerInput.responseBuilder
.addDelegateDirective(currentIntent)
.getResponse();
}
if (location == 'future location') {
say = `Future location not available at this moment. Please ask to current location.`;
return responseBuilder
.speak(say)
.reprompt(say)
.getResponse();
} else if(location == 'current location' && tableTalkType == 1){
return responseBuilder
.addDelegateDirective({
name: 'getRestaurantName',
confirmationStatus: 'NONE',
slots: {}
})
.getResponse();
} else if (location == 'current location' && tableTalkType == 2) {
return userCreatedTableListing_Handler.handle(handlerInput);
} else {
say = `invalid input.Please try again`;
return responseBuilder
.speak(say)
.reprompt(say)
.getResponse();
}
} else {
return errorIntent_Handler.handle(handlerInput);
}
},
};
const getRestaurantName_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'getRestaurantName' ;
},
handle(handlerInput) {
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
let previousIntentName = getPreviousIntent(sessionAttributes);
if (previousIntentName == 'futureOrCurrentLocation') {
const request = handlerInput.requestEnvelope.request;
let slotValues = getSlotValues(request.intent.slots);
// delegate to Alexa to collect all the required slots
const currentIntent = request.intent;
if (request.dialogState && request.dialogState !== 'COMPLETED') {
return handlerInput.responseBuilder
.addDelegateDirective(currentIntent)
.getResponse();
}
// SLOT: restaurantname
if (request.dialogState && request.dialogState == 'COMPLETED' && slotValues.restaurantname.heardAs) {
return new Promise((resolve) => {
getRestaurants(slotValues, handlerInput).then(say => {
resolve(handlerInput.responseBuilder.speak(say).reprompt(say).withShouldEndSession(false).getResponse());
}).catch(error => {
console.log(error);
});
});
}
} else {
return errorIntent_Handler.handle(handlerInput);
}
}
};
const selectRestaurants_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'selectRestaurants' ;
},
handle(handlerInput) {
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
let previousIntentName = getPreviousIntent(sessionAttributes);
if (previousIntentName == 'getRestaurantName') {
const request = handlerInput.requestEnvelope.request;
const responseBuilder = handlerInput.responseBuilder;
let slotValues = getSlotValues(request.intent.slots);
let say = '';
let restaurantListArray = sessionAttributes.sessionrestaurantList ? sessionAttributes.sessionrestaurantList : [];
sessionAttributes.previousIntent = '';
handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
let restaurantIndex = slotValues.selectRestaurant.heardAs;
let restaurantData = {
name: '',
address: '',
restaurantlatitude: '',
restaurantlongitude: '',
restaurantID:'',
restaurantImageUrl: '',
date: '',
time:'',
people: '',
};
if (restaurantListArray.length >= restaurantIndex) {
let jsonData = JSON.parse(restaurantListArray[restaurantIndex - 1]);
if ((restaurantIndex) && (jsonData[restaurantIndex].name !== '' && typeof jsonData[restaurantIndex].name !== undefined && jsonData[restaurantIndex].name !== null)) {
let restaurantAddress1 = jsonData[restaurantIndex].location.address1 ? jsonData[restaurantIndex].location.address1: '';
let restaurantAddress2 = jsonData[restaurantIndex].location.address2 ? jsonData[restaurantIndex].location.address2: '';
let restaurantAddress3 = jsonData[restaurantIndex].location.address3 ? jsonData[restaurantIndex].location.address3: '';
restaurantData['name'] = jsonData[restaurantIndex].name;
restaurantData['address'] = restaurantAddress1.concat(restaurantAddress2, restaurantAddress3);
restaurantData['restaurantID'] = jsonData[restaurantIndex].id;
restaurantData['restaurantImageUrl'] = jsonData[restaurantIndex].image_url;
restaurantData['restaurantlatitude'] = jsonData[restaurantIndex].coordinates.latitude;
restaurantData['restaurantlongitude'] = jsonData[restaurantIndex].coordinates.longitude;
sessionAttributes.restaurantData = restaurantData;
handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
say = `selected Restaurant name is ${jsonData[restaurantIndex].name} in ${restaurantAddress1} ${restaurantAddress2} ${restaurantAddress3}.`;
return responseBuilder
.addDelegateDirective({
name: 'bookingDate',
confirmationStatus: 'NONE',
slots: {}
})
.speak(say)
// .reprompt('try again, Please provide date')
.withShouldEndSession(false)
.getResponse();
} else {
say = 'Restaurant not available. please say again';
return responseBuilder
.speak(say)
.reprompt('Restaurant not available. please say again')
.withShouldEndSession(false)
.getResponse();
}
} else {
say = 'Please select valid input.';
return responseBuilder
.speak(say)
.reprompt('Please select valid input')
.withShouldEndSession(false)
.getResponse();
}
} else {
return errorIntent_Handler.handle(handlerInput);
}
},
};
const errorIntent_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'errorIntent' ;
},
handle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
const responseBuilder = handlerInput.responseBuilder;
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
let say = 'Sorry. There is some problem with the response. Please say again';
return responseBuilder
.speak(say)
.reprompt(say)
.getResponse();
},
};

Is there a way to wait for the calculations before moving to next iteration in Javascript

In the following function before the calculation for productId and reqQuantity finished corresponding to the else if condition. The commands after it are ran.
addBasketItem.quantityCheck = () => (req, res, next) => {
if (req.method === 'POST' || req.method === 'PUT') {
// console.log(extractParam(req))
var result = utils.parseJsonCustom(req.rawBody)
var productId = 0
var reqQuantity = 0
if( req.method === 'POST') {
var productIds = []
var basketIds = []
var quantities = []
for (var i = 0; i < result.length; i++) {
if (result[i].key === 'ProductId') {
productIds.push(result[i].value)
} else if (result[i].key === 'BasketId') {
basketIds.push(result[i].value)
} else if (result[i].key === 'quantity') {
quantities.push(result[i].value)
}
}
productId = productIds[0]
console.log("productIdInstantiated:", productId)
reqQuantity = quantities[0]
} else if (req.method === 'PUT') {
var pID = req.url
models.BasketItem.findAll({ where: { id: pID.replace('/', '') } }).then((item) => {
productId = item[0].dataValues.ProductId <---- Here
console.log("productIdInside:", productId)
reqQuantity = result[0].value <---- Here
})
}
console.log("productIdQueried:", productId)
models.Product.findAll({ where: { id: productId } }).then((product) => {
const availableQuantity = product[0].dataValues.quantity
if (availableQuantity < reqQuantity) {
res.status(401).send('{\'error\' : \'Quantity Unavailable\'}')
} else {
next()
}
}).catch(error => {
next(error)
})
} else {
next()
}
}
You can use async/await for this:
addBasketItem.quantityCheck = async (req, res, next) => {
if (req.method === 'POST' || req.method === 'PUT') {
// console.log(extractParam(req))
var result = await utils.parseJsonCustom(req.rawBody)
var productId = 0
var reqQuantity = 0
....
You can change the order and store the promise in a variable.
After that you can just call .then() on the variable.
addBasketItem.quantityCheck = () => (req, res, next) => {
var promise;
//Some stuff going on here..
promise = models.BasketItem.findAll({ where: { id: pID.replace('/', '') } });
//After "else if (req.method === 'PUT')" (Or somewhere else..)
promise.then(item => {
productId = item[0].dataValues.ProductId;
console.log("productIdInside:", productId);
reqQuantity = result[0].value;
models.Product.findAll({ where: { id: productId } }).then((product) => {
const availableQuantity = product[0].dataValues.quantity
if (availableQuantity < reqQuantity) {
res.status(401).send('{\'error\' : \'Quantity Unavailable\'}')
} else {
next()
}
}).catch(error => {
next(error)
});
});
}

Run function if other end Vue, JS

I'm don't know how to run code if other end
Function showAvailableTable refresh item and add data to vuex $store
I need to run code from ////START to //// END if showAvailableTable() done correctly(axios add data to $store)
how should I do it correctly?
showAvailableTable () {
var obj = this.firstStepData
var nullCount = 0
var self = this
for (var key in obj) {
if (obj.hasOwnProperty(key) && obj[key] == null) {
nullCount++
}
}
if (nullCount === 0) {
var reservationId = this.firstStepData.restaurant.id
var restaurantSize = this.firstStepData.tableSize.value
var reservationDate = this.firstStepData.reservationDate
var reservationTime = this.firstStepData.reservationTime
axios
.get(self.$store.state.apiUrl + 'reservation/tables/?size=' + restaurantSize + '&restaurant_id=' + reservationId + '&date=' + reservationDate + '&hour=' + reservationTime)
.then(response => {
this.$store.commit('updateRestaurantTableList', response.data)
})
.catch(error => {
console.log(error)
})
this.$store.commit('updateShowTable', true)
}
},
Next function, this function booking table, I'm run this.showAvailableTable() to refresh data in $store
firstStepBook (event, id) {
this.showAvailableTable()
///////////////////START
var isResData = false
this.dataLoading = true
for (var obj in this.restaurantTableList) {
if (this.restaurantTableList[obj].id === id) {
if (this.restaurantTableList[obj].res_tab.length > 0) {
isResData = true
}
break
}
}
if (isResData && !event.currentTarget.classList.contains('isSelected')) {
alert('someone is booking this table, choose another one')
} else {
if (event.currentTarget.classList.contains('isSelected')) {
this.deleteTmpReservation(this.reservationTmp.id)
this.dataLoading = false
} else {
if (this.reservationTmp.id !== undefined) {
this.deleteTmpReservation(this.reservationTmp.id)
this.dataLoading = false
}
var self = this
axios.post(self.$store.state.apiUrl + 'reservation/', {
restaurant_table: id,
clients_number: self.firstStepData.tableSize.value,
reservation_time: self.firstStepData.reservationTime,
reservation_date: self.firstStepData.reservationDate
})
.then(function (response) {
self.showAvailableTable()
self.$store.commit('updateReservationTmp', response.data)
self.dataLoading = false
})
.catch(function (error) {
console.log(error)
})
//this.$store.commit('updateStep', 2)
}
}///////////////////END
},
thank you in advance
This might suit you if the mutation is only called within showAvailableTable()
Ref Vuex subscribe
mounted() {
this.$store.subscribe((mutation, state) => {
if (mutation.type === 'updateRestaurantTableList') {
///////////////////START
...
///////////////////END
}
})
},
methods: {
firstStepBook (event, id) {
// call to updateRestaurantTableList triggers above subscription
this.showAvailableTable()
}
}

Categories

Resources