(js) writing async function using a api wrapper - javascript

I'm currently using https://github.com/pixtron/bybit-api/tree/master
and what im trying to do looks like this:
const {RestClient} = require('#pxtrn/bybit-api');
const API_KEY = 'xxx';
const PRIVATE_KEY = 'yyy';
const client = new RestClient(API_KEY, PRIVATE_KEY);
client.getPosition({symbol: 'BTCUSD'})
.then(msg => {
let btcPositionCheck = msg.result.size;
if (btcPositionCheck == 0) {
console.log("empty")
} else {
let btcPositionSize = btcPositionCheck;
let btcPositionSide = msg.result.side;
}
})
.catch(err => {
console.error(err);
});
client.getPosition({symbol: 'ETHUSD'})
.then(msg => {
let ethPositionCheck = msg.result.size;
if (ethPositionCheck == 0) {
console.log("empty")
} else {
let ethPositionSize = ethPositionCheck;
let ethPositionSide = msg.result.side;
}
})
.catch(err => {
console.error(err);
});
console.log(btcPositionSize + ' ' + ethPositionSize)
returning me the following error:
ReferenceError: btcPositionSize is not defined
simply because im out of scope, I'm aware. however, I'm unsure how to approach rewriting the following to better allow me to construct what I need. (I need to call getPosition for the 3 different assets as well and take the variables from each call to use later in my code.) if that makes any sense. help would be greatly appreciated
edit:
async function getPosition({symbol: BTCUSD}) {
try {
let btcPositionCheck = msg.result.size;
} catch(error) {
return null;
}
}
im trying to rewrite it but im unsure how

Once you get into asynchronous context, you need to stay in asynchronous context to get values. In your case, there are promises to be resolved, you can await them and then print.
Also you need to make sure that your variables are in valid scope
const {RestClient} = require('#pxtrn/bybit-api');
const API_KEY = 'xxx';
const PRIVATE_KEY = 'yyy';
const client = new RestClient(API_KEY, PRIVATE_KEY);
async function doItAll() {
let btcPositionCheck;
let ethPositionCheck;
await client.getPosition({symbol: 'BTCUSD'})
.then(msg => {
btcPositionCheck = msg.result.size;
if (btcPositionCheck == 0) {
console.log("empty")
} else {
let btcPositionSize = btcPositionCheck;
let btcPositionSide = msg.result.side;
}
})
.catch(err => {
console.error(err);
});
await client.getPosition({symbol: 'ETHUSD'})
.then(msg => {
ethPositionCheck = msg.result.size;
if (ethPositionCheck == 0) {
console.log("empty")
} else {
let ethPositionSize = ethPositionCheck;
let ethPositionSide = msg.result.side;
}
})
.catch(err => {
console.error(err);
});
console.log(btcPositionSize + ' ' + ethPositionSize)
}
Note that nicer way is to await promises into value, which means it can look like that (to use await, it needs to be in an async function)
const msg = await client.getPosition({symbol: 'BTCUSD'})
btcPositionCheck = msg.result.size;
if (btcPositionCheck == 0) {
console.log("empty")
} else {
let btcPositionSize = btcPositionCheck;
let btcPositionSide = msg.result.side;
}

Related

Firebase Cloud Functions Async

I am making a function for firebase cloud functions, I want a function to be called every time a new document is created in "posts". I want this function to perform the tasks that I put inside the "onCeatePost" function.
The problem I have is that I'm not sure if this is the correct way to structure such a function.
In several firebase examples I have seen that it is always called return _; or return null; at the end of a task, but I don't know how to structure the function so that all the tasks are carried out, could someone help me to restructure my function or tell me what is wrong please.
There are several if statements in the function, if the created publication does not comply with them, I would like it to skip them but continue with the other tasks that I put inside the function.
I don't know if it's too much to ask, but I'm new to this language and I haven't been able to find the answer I'm looking for. Thank you!
exports.onPostCreate = functions.firestore.document("/posts/{postId}").onCreate(async (snap) => {
const post = snap.data();
if (post) {
try {
const topic = post.topic;
const contentForFeed = post.contentForFeed;
const uid = post.uid;
const previous = post.prev;
await db.collection("users").doc(uid).update({"stats.posts": admin.firestore.FieldValue.increment(1)});
if (topic) {
await db.collection("topics").doc(topic.id).collection("user-authors").doc(uid).set({"date": snap.createTime});
}
if (contentForFeed == true) {
const userPath = db.collection("users").doc(uid);
await userPath.update({"stats.lastUpdate": snap.createTime});
}
if (previous) {
const previousId = previous.id;
const previousUid = previous.uid;
const refPrev = db.collection("posts").doc(previousId);
await db.runTransaction(async (t) => {
const doc = await t.get(refPrev);
const priority = doc.data().stats.date;
const newDate = new admin.firestore.Timestamp(priority.seconds + 120, priority.nanoseconds);
await db.collection("posts").doc(previousId).update({"newDate": newDate});
});
if (previousUid != uid) {
const path = db.collection("users").doc(uid).collection("user-posts");
const dataToSet = {"timestamp": snap.createTime, "uid": uid, "postId": onReplyToPostId};
await path(dataToSet);
}
}
} catch (err) {
functions.logger.log(err);
}
} else {
return null;
}
});
You'll find below the adapted code (untested) with 4 corrections.
Here are explanations for the two most important ones:
(Correction 2) In a transaction you need to use the transaction's update() method and not the "standard one"
(Correction 4) When all the asynchronous work is complete you need to return a value or a Promise. See this documntation page for more details.
exports.onPostCreate = functions.firestore
.document('/posts/{postId}')
.onCreate(async (snap) => {
const post = snap.data();
if (post) {
try {
const topic = post.topic;
const contentForFeed = post.contentForFeed;
const uid = post.uid;
const previous = post.prev;
await db
.collection('users')
.doc(uid)
.update({
'stats.posts': admin.firestore.FieldValue.increment(1),
});
if (topic) {
await db
.collection('topics')
.doc(topic.id)
.collection('user-authors')
.doc(uid)
.set({ date: snap.createTime });
}
if (contentForFeed == true) {
const userPath = db.collection('users').doc(uid);
await userPath.update({ 'stats.lastUpdate': snap.createTime });
}
let previousUid; // <= Correction 1
if (previous) {
const previousId = previous.id;
previousUid = previous.uid; // <= Correction 1
const refPrev = db.collection('posts').doc(previousId);
await db.runTransaction(async (t) => {
const doc = await t.get(refPrev);
const priority = doc.data().stats.date;
const newDate = new admin.firestore.Timestamp(
priority.seconds + 120,
priority.nanoseconds
);
t.update(refPrev, { newDate: newDate }); // <= Correction 2
});
if (previousUid != uid) {
const path = db
.collection('users')
.doc(uid)
.collection('user-posts');
const dataToSet = {
timestamp: snap.createTime,
uid: uid,
postId: onReplyToPostId,
};
await path.add(dataToSet); // <= Correction 3
}
}
return null; // <= Correction 4
} catch (err) {
functions.logger.log(err);
}
} else {
return null;
}
});

API getting multiple Calls

My program in a nutshell. If the trigger word is detected in the message, my application creates invoices.
The issue: Multiple calls to the trigger function. All of the requests to the API are simultaneous. This causes my data to have problems.
I have added the async and await to wait for the trigger function to complete. But it seems my calls are still being called all together.
// Links to a Facebook Live.
export const fblive = async (liveid) => {
if (liveid != null) {
try {
const reg = new RegExp("\\d{5,}");
const found = liveid.match(reg);
if (found > 0) {
console.log(found, " || ", found[0]);
let activate = false;
var userid = "";
//var accesstoken = ''
var accesstoken =''
var videoID = found;
var live_url =
"https://streaming-graph.facebook.com/" +
videoID +
"/live_comments?access_token=" +
accesstoken +
"&comment_rate=one_hundred_per_second&fields=from{name,id},message";
var source = new EventSource(live_url);
source.onmessage = function (event) {
var result = JSON.parse(event["data"]);
let trigger_word = result["message"].search("#");
// looking at comments
readcomment(result["message"]);
if (result["from"] != null) {
console.log("FROM ! !:", result["from"]);
}
};
} else {
console.log("ZERO FOUND");
}
} catch (error) {
console.log("FB LIVE COMMENT IS NOT RUNNING");
}
} else {
console.log("Live ID not valid");
}
};
// Looking at every comment in a facebook live
export const readcomment = async (the_comment) => {
try {
console.log(" CALLING LIVE READ COMMENT ", the_comment);
let re = await new Promise((resolve) =>
setTimeout(
setTimeout(async function () {
console.log(the_comment);
if (the_comment.includes("#")) {
populatelist();
console.log(the_comment);
let new_string = the_comment.trim().split(" ");
console.log(new_string, " STRING SPLIT");
let customer_found = await findcust(new_string);
let item_found = await finditem(new_string);
console.log(customer_found, item_found, "WE FOUND ");
if (customer_found != false && item_found != false) {
console.log("THERE'S A TRIGGER SALE HERE");
let remove = await find_remov(new_string);
console.log(remove, "WE ARE LOOKING AT RMOVE ");
await comment_trigger(customer_found,item_found,remove)
console.log(the_comment)
console.log("promise for " , the_comment, " has been fullfilled")
}
}
}, 2000)
)
);
} catch (error) {
console.log(error.response)
}
};
// This is when a comment was found to be the triggers words (customer id and a item name)
export const comment_trigger = async (customer, item, rmv) => {
// FIND THE ITEM IN INVOICE.
const client = find(customer, customer_list1);
const real_item = find(item, item_list1);
try {
console.log(client, real_item);
if (client != false && real_item != false) {
let inv = await invoicesbycustomer(client.id);
console.log(inv);
if (inv == undefined || inv.length ==0) {
console.log(customer, item);
console.log(real_item.id);
let new_Invoice = new Invoice("", client);
let new_item = new Product(real_item.id, real_item.name, 1);
await new_Invoice.addItem(new_item);
console.log(new_Invoice);
await createInvoice(new_Invoice);
console.log("NO INVOICE WAS FOUND FOR THIS CLIENT");
} else {
console.log(inv);
// making sure there's a real invoice.
console.log("DATA TYPE IS ", typeof inv);
if (typeof inv !== "undefined") {
console.log(inv, "THIS IS INVOICE WITH CLIENT");
console.log(inv[0].node.items.length);
let oldItems = inv[0].node.items;
let NewInvoice = new Invoice(
inv[0].node.id,
inv[0].node.customer.id
);
let Itemsize = oldItems.length;
let found = false;
if (Itemsize > 0) {
//IF ITEMS EXIST ADD QTY.
// ELSE ADD THIS NEW ITEM.
for (let x in oldItems) {
if (real_item.id == oldItems[x].product.id) {
found = true;
}
}
if (found && rmv == "removeqty") {
await removeqtyitem(customer, item);
} else if (found && rmv == "removeAll") {
await removeitem(customer, item);
} else if (found) {
let aqi = await addqtyitem(customer, item);
} else {
// add item
await additems(customer, item);
}
} else {
await additems(customer, item);
}
}
}
} else {
let errmssg = "";
if (!client) {
errmssg = errmssg.concat(" ", " Client is not valid ");
console.log("client not found", errmssg);
}
if (!real_item) {
errmssg = errmssg.concat("", " Item not found");
}
console.log(errmssg);
console.error(errmssg);
}
} catch (error) {
console.error(error.response.data)
}
};
Here's an example of the api being called. this is using graphql
//DELETING INVOICE API CALL
export const deleteInvoice = async(id) => {
const invoiceId = id;
console.log(invoiceId, "THIS I S INVOICE DELET EDELETE DELETE DELTE ")
try {
const token = "zCtQa00zlorbFFum6I7Rlzc0QwMDoS";
const shema = `
mutation ($input: InvoiceDeleteInput !) {
invoiceDelete(input: $input) {
didSucceed
inputErrors {
path
code
message
}
}
}`;
//About to submit my shema to waveapps
const API_URL="https://gql.waveapps.com/graphql/public"
const bussID = "QnVzaW5lc3M6ZTIyZmVhODEtNjg5OC00N2ZiLTgzOGItYWMyYzllNDZiM2Jk";
let watch = await axios(API_URL, {
method: "POST",
headers: {
Authorization: token ? `Bearer ${token}` : "",
"Content-Type": "application/json",
},
data:{
query: shema,
variables: {
input:{
invoiceId: invoiceId,
}
},
},
})
console.log(watch.data)
} catch (error) {
console.log(error.response)
}
//console.log("return delete invoice complete")
};
I have used async/await and promises.
When multiple calls are made. The await and promises are still being called at the same time. Not sure what else to look at? any suggestions please. I have spent a week on this.

Return empty array in Fastify handler with async/await function

I'm trying to make a web3 wallet with Moralis with Fasitify in back and VueJS in front.
(I would like to say that I already do this in web client (vuejs) and everything works well!)
In my back, I fetch all the asset from user. It works, I get them all well and I can send them back to the front
But I need to process/sort the data to recover only part of it and send it to the front to avoid doing too much treatment at the front and reduce your workload.
I do that :
*handlers/token.js*
const getTokenBalances = async () => {
let userTokens;
const options = {
chain: "bsc",
address: "0x935A438C29bd810c9aBa2F3Df5144d2dF4F3c0A0",
};
userTokens = await Moralis.Web3API.account.getTokenBalances(options);
return userTokens;
};
and if I return userTokens, I had it in Postman. But now, I do something like :
const getTokenBalances = async (tokens) => {
let userTokens;
let userBalances = [];
const options = {
chain: "bsc",
address: "0x935A438C29bd810c9aBa2F3Df5144d2dF4F3c0A0",
};
userTokens = await Moralis.Web3API.account.getTokenBalances(options);
userTokens.forEach((token) => {
if (
!token.name.match(/^.*\.io/) &&
!token.name.match(/^.*\.IO/) &&
!token.name.match(/^.*\.net/) &&
!token.name.match(/^.*\.Net/) &&
!token.name.match(/^.*\.com/) &&
!token.name.match(/^.*\.org/)
) {
getTokenPair(token).then((value) => {
if (value > 2) {
checkTokenPrice(token).then((price) => {
if (price > 0.001) {
userBalances.push(token);
}
});
}
});
}
});
userBalances.sort((a, b) => {
return b.total_value_usd - a.total_value_usd;
});
return userBalances;
};
userBalances its always empty in my response in Postman (And I don't understand why ?)
The getTokenPair function :
const getTokenPair = async (token) => {
const BNBTokenAddress = "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"; //BNB
const options = {
token0_address: token.token_address,
token1_address: BNBTokenAddress,
exchange: "pancakeswapv2",
chain: "bsc",
};
try {
const pairAddress = await Moralis.Web3API.defi.getPairAddress(options);
let amount = 0;
//console.log("token pairAddress : " + pairAddress.pairAddress);
if (pairAddress.token1.symbol === "BUSD") {
try {
let reserve = await getPairReserves(pairAddress.pairAddress);
amount += reserve / 10 ** 18;
} catch (err) {
console.log("error getReservesBUSD : " + err);
}
}
if (pairAddress.token1.symbol === "WBNB") {
try {
let reserve = await getPairReserves(pairAddress.pairAddress);
amount += reserve / 10 ** 18;
} catch (err) {
console.log("error getReservesWBNB : " + err);
}
}
//console.log("amount : " + amount)
return amount;
} catch (err) {
console.log("error getPair : " + err);
}
};
and the checkTokenPrice function :
const checkTokenPrice = async (token) => {
let price;
const options = {
address: token.token_address,
chain: "bsc",
exchange: "PancakeSwapv2",
};
try {
const priceToken = await Moralis.Web3API.token.getTokenPrice(options);
price = priceToken.usdPrice.toFixed(7);
token.price = priceToken.usdPrice.toFixed(7);
token.balance = insertDecimal(token.balance, token.decimals);
token.total_value_usd = (token.balance * token.price).toFixed(2);
return price;
} catch (err) {
console.log("error tokenPrice : " + err);
}
};
They are await method in all the function I use so maybe there is a connection.
Thanks for you help !
**** EDIT *****
I solve my problem like this :
const getTokenBalances = async () => {
let userTokens;
let userBalances = [];
const options = {
chain: "bsc",
address: "0x935A438C29bd810c9aBa2F3Df5144d2dF4F3c0A0",
};
userTokens = await Moralis.Web3API.account.getTokenBalances(options);
for (token of userTokens) {
if (
!token.name.match(/^.*\.io/) &&
!token.name.match(/^.*\.IO/) &&
!token.name.match(/^.*\.net/) &&
!token.name.match(/^.*\.Net/) &&
!token.name.match(/^.*\.com/) &&
!token.name.match(/^.*\.org/)
) {
let value = await getTokenPair(token);
if(value > 2) {
let price = await checkTokenPrice(token);
if (price > 0.001) {
userBalances.push(token);
}
}
}
}
return userBalances;
};
Thanks for the help ! ;)

Is this Transaction valid?

I am wondering if this transaction is even valid and actually ensuring quantity is being the most up to date.
async function deductQuantity(orders: [Order]) : Promise<boolean> {
try {
let document = await admin.firestore().collection("MenuItems")
orders.forEach(async (order)=> {
let itemDoc = (await document.where(`item.catalogType`, "==", order.catalogType).where(`item.id`, "==", order.item.id))
let get = await itemDoc.get()
get.forEach(async a=> {
const pp = document.doc(a.id)
await admin.firestore().runTransaction(async (t)=> {
const mostRecentDoc = await t.get(pp)
const data = await mostRecentDoc.data()
if (data == undefined){
return
}
const newQuantity = data.item.quantity - order.quantity
await t.update(pp, {[`item.quantity`] : newQuantity})
})
})
})
return true
} catch (error) {
console.log("dum: " + error)
return false
}
}
the part where I do let get = await itemDoc.get(), and get.ForEach, is kind of unnecessary because I know, that it will only return one document that matches the query field, but I need to forEach it in order to get the child component\s. Anyways, is it a valid transaction?

How to return fieldValue or data to a variable in with firestore

I hav two types of variables that I am trying to use in my code and I am struggling to make them not come back as undefined.
const destinationData = collectionData.doc('india');
let travelData = destinationData.get()
.then(doc => {
if (!doc.exists) {
return res.status(404).send(msgNotFound);
} else {
return doc.data();
}
})
console.log(travelData.name);
const passportData = collectionData.doc('australia');
let passportCountry = passportData.get('countryCode');
console.log(passportCountry);

Categories

Resources