0

I am using firebase functions and Admin SDK to implement a functions on a event trigger. I am trying to push a notification to user when a new update is available. So, when the update version changes from the current, I want to make some changes in the user object and set update_available key as true

Now, the location of event(update_version) that is being tracked and the data to be changed are in to completely different objects. The Object model is as follows:

|root
  |- app_info
        |- version

  |- users
        |- <uid>
            |- checker
                  |- update_available: true

Not so far I have achieved this :

 function setUpdateValueTrue() {
    db.ref().orderByChild("checker/update_available").equalTo("false").once('value', (snapshot) => {
        snapshot.forEach((childSnapshot) => {
          console.log("got in here");
          console.log(childSnapshot.val())
      });
   })
 }

I guess this maybe completely wrong. At the moment i feel stuck. Any help is really appreciated. My major concern is how to I bypass the uid or query through it.

2
  • How do you link the app_info and the user? Commented Dec 14, 2018 at 9:08
  • No, not linking them. I am observing the value of the version. As soon as it changes, i want all the values of update_available under checker to be true for all the users. By default the value is going to be false Commented Dec 14, 2018 at 9:12

1 Answer 1

1

The following should work (not tested however).

Note the use of Promise.all(), since you need to update a variable number of users nodes in parallel.

exports.versionUpdate = functions.database.ref('/app_info').onUpdate((change, context) => {
    const beforeData = change.before.val(); // data before the update
    const afterData = change.after.val(); // data after the update

    if (beforeData.version !== afterData.version) {

       const promises = [];
       const usersRef = admin.database().ref('/users');

       return usersRef.once('value', function(snapshot) {
          snapshot.forEach(childSnapshot => {
             const uid = childSnapshot.key;
             promises.push(usersRef.child(uid + '/checker/update_available').set(true));
          });
          return Promise.all(promises);
       });

   } else {
      return null;
   }

});
Sign up to request clarification or add additional context in comments.

2 Comments

Great. To be honest, I had the exact same logic in my mind, but the foreach loop didn't work for me previously. This totally works. I posted this question since I thought there might be a way to query through the data just like we have in iOS SDK. But this does the job. Thanks Renaud.
how could this be written in typescript?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.