2
votes

I use Cloud Functions for Firebase for some server-side-tasks. Using the database-trigger onWrite() I experience some unexpected behaviour.

exports.doStuff = functions.database.ref('/topic/{topicId}/new').onWrite((event) => {

    // If data, then continue...
    if (event.data.val()){
        // doStuff
        //
    } else {
        console.log("started, but no content!");
    }

When new data is added to the specified folder the function is started at least once without any new content ("started, but no content!" is logged to the console). Sometimes even two, three or four times. Then it's run again, automatically (a couple of seconds later) and this time everything works as expected.

EDIT:


The code that writes to the specified node is as follows:

functionA(topicId){
    return this.db.object('/topic/'+topicId+'/new').update({
        timestamp: firebase.database.ServerValue.TIMESTAMP
    });
}

The timestamp is only set once. So before that operation is called, the node new does not exist. So there is no edit or delete. However, this means, by calling the above function first the node new is created, some miliseconds later timestamp and then the value for timestamp. Does Firebase call the onWrite() function for each of these events?


Does this make sense to anybody? Any idea how to make sure, that the function is only executed, when there is really new data available?

1
Can you post the code that writes to /topic/{topicId}/new? - Bob Snyder
Create, Edit and Delete are all considered as onWrite events. Perhaps the trigger is firing after a delete event? - sketchthat
Question edited. I added the code that writes to the firebase node. - Jane Dawson
This isn't much help but I'll share that I copied your Cloud Function code, ran it with an equivalent DB update (Android/Java) and can't reproduce your results. I see the function invoked once. I can only suggest that you do some experiments to try and isolate the behavior: define the trigger for a different location to make sure some other code is not writing to /topic/{topicId}/new, update with a simple integer instead of TIMESTAMP, do a set() instead of update(). - Bob Snyder
running into a similar issue myself. The event.data.val() returns empty - Bazinga777

1 Answers

0
votes

onWrite() has a new format, since version 1.0 of Firebase SDK

Your original code was based on tutorials or help from an earlier, beta, version of Firebase.

exports.doStuff = functions.database.ref('/topic/{topicId}/new')
.onWrite((event) => {

    if (event.data.val()){
        // do stuff
    }
}

However since version 1.0, the first parameter in the onWrite function is a "change" object which has two properties: before and after. You want the after. You can get it as follows:

exports.doStuff = functions.database.ref('/topic/{topicId}/new')
.onWrite((change) => {

    if (change.after.val()){
        // do stuff
    }
}

Source: https://firebase.google.com/docs/reference/functions/functions.Change