Reputation: 839
I am attempting to write a firebase cloud function to loop through all children of a particular node, check a different part of the database for it's corresponding data, and adding up all number values.
Basically, I want the cloud function to create a price total of all the items within a list, but using a different part of the database to retrieve the price for that item.
exports.onAddToCart = functions.database.ref('/users/user_cart/{uid}/items').onWrite((change, context) =>{
let totalCost = 0;
return admin.database().ref('/users/user_cart/' + context.params.uid + '/items').once('value').then((snapshot) => {
snapshot.forEach((child) => {
return admin.database().ref('/serv/' + child.val()).once('value').then((snapshot2) => {
totalCost += snapshot2.val().price;
});
return false;
});
return admin.database().ref('/users/user_cart/' + context.params.uid + '/price').set(totalCost);
});
});
This code does not work
The problem is snapshot.forEach
needs to return a boolean and not a promise. How can I accomplish this? Or is this not viable?
Upvotes: 0
Views: 1922
Reputation: 839
I ended up creating an array of promises that were each mapped to the location of the price
exports.onAddToCart = functions.database.ref('/users/user_cart/{uid}/items').onWrite((change, context) =>{
let totalCost = 0;
const itemList: string[] = [];
return admin.database().ref('/users/user_cart/' + context.params.uid + '/items').once('value').then((snapshot) =>{
snapshot.forEach((child) => {
itemList.push(child.val());
return false;
})
return itemList;
}).then((items) => {
const promiseList: Promise<any>[] = [];
for (let i = 0; i < items.length; i++){
promiseList.push(admin.database().ref('/services/' + items[i]).once('value').then((value) =>{
totalCost += value.val().price;
}));
}
return Promise.all(promiseList);
}).then(() =>{
return admin.database().ref('/users/user_cart/' + context.params.uid + '/total').set(totalCost);
});
});
Upvotes: 1