I try to create a Firebase cloud function that react on new "Event" in the realtime database and add a "notification" object in a notification list for the corresponding users. i succeed to get new event information,to push a notification a corresponding users but not in a list format (but in hashmap format).
So I tried to get the numbers of children in order to push new notification with the good index. I don't know how to manage promises in that case.
The idea is to get sport_name and level from the new event, to get corresponding users in Sport and add notification for each users.
There is my cloud function :
exports.detectEvent = functions.database .ref("Event/{eventID}") .onCreate((snapshot, context) => { const event = snapshot.val(); const sport = event.sport.name; const level = event.niveau; const name = event.name; var promises=[]; var path = "Sports/" + sport + "/" + level; var notif = { type : "Event", contentID : context.params.eventID, message : sport + " : Un nouvel événement vous correspond ! ", seen : false, date : "01" }; console.log('path ', path); return admin.database().ref(path).once("value", function(result) { var datas = result.val(); for (var property in datas) { if (datas.hasOwnProperty(property)) { promises.push(admin.database().ref("Users/"+datas[property]+"/notifications").on("value", function(snapshot) { console.log("There are "+snapshot.numChildren()+" notifs"); admin.database().ref("Users/"+datas[property]+"/notifications").child(snapshot.numChildren()).set(notif) }));
} } return Promise.all(promises); })
});
There is the table :