Search code examples
javascriptfirebasefirebase-realtime-databasees6-promise

Firebase Admin : How to promisify a push operation


I have a function as follows.

const notify = function (uid, ..., senderId) {
    var obj = {
        "time": +new Date(),
        ... ...
        "uid": senderId,
    }
    dbRef("../notifications/").push(obj);
}

I call this from within other functions to write notifications, this is called among other functions that return promises, which are put into an array to wait for all promises to be fulfilled.

So I'd like this to return a promise instead of using a complete callback, you know, like how db.set() does.

WHY I"M NOT USING db.set().

structure.

users/{uid}/notifications/autoId/notificationObject.

db.ref('users/{uid}/notifications').push(notificationObject) will adhere to the above, while set() will do the following.

`users/{uid}/notifications/notificationObject`

Which will practically just replace the entire user notifications objects.


Solution

  • There are multiple ways to write a push() function like the one in your question:

    dbRef("../notifications/").push(obj);
    

    One of those options uses set() like this:

    dbRef("../notifications/").push().set(obj);
    

    What this does is actually the following:

    //Generate the unique push key and get the reference
    var key = dbRef("../notifications/").push();
    //Save the data to the newly generated reference
    key.set(obj);
    

    All three code blocks in this answer do exactly the same thing. More information about these ways of saving can be found in the Firebase docs.