My product tracks the user’s stock portfolio. I have created a Firebase function that is called every 24 hours. This function goes over the user’s stock data and makes a call to a 3rd party API to get the latest stock prices etc. My code used to work fine until recently when the API vendor imposed a max 5 calls per minute rate limit. Now, with the current code, I start getting failures after the first 5 calls. How do I re-architect my code to add this wait after every 5 calls I make? Below is what the code looks like
exports.dailyNetworth = onSchedule("every 24 hours", async (event:any) => {
...
for(let uid of validUsers.keys()){
const finColRef = db.collection("users/" + uid + "/finance")
const fQuerySnapshot = await finColRef.orderBy("Date",'desc').limit(1).get()
fQuerySnapshot.forEach(async(doc:any) => {
let data:any
data = doc.data()
const finance = new Finance()
finance.assets = data.assets
for(let ast of Object.keys(finance.assets['Stocks'])){
const asset:Stock = finance.assets['Stocks'][ast]
let lastUpdateDate = asset.lastUpdateDate.seconds
const stkPrice:any = await findStockPrice(asset.Name, asset["Share Count"])
if(stkPrice !== null){
finance.assets[astClass][ast].value = stkPrice
finance.assets[astClass][ast].lastUpdateDate = Timestamp.now()
}
}
});
}
});
The third-party API call method is like the below:
async function findStockPrice(symbol:string, quantity:number){
let value = null
try {
const url = 'https://someurl.com?' + symbol
const header = {
...
}
const response = await fetch(url, {headers: header})
const json = await response.json()
const rate = json["rate"]
value = quantity*rate
} catch (error:any) {
logger.error(error);
}
return value
}