Sanjay Dattatri
Sanjay Dattatri

Reputation: 129

firebase Cloud function transaction working sporadically

I have the cloud function like so:

exports.updateNewsCount = functions.database.ref('/channels/{channelId}/news/{newsId}/') 
.onWrite (event => {
    const channelId = event.params.channelId;
    const newsId = event.params.newsId;
    let CntRef = admin.database().ref('/channelDetails/' + channelId + '/newsCnt');
    if (event.data.exists() && !event.data.previous.exists()){
        return CntRef.transaction(function(current){
            if (current){
                console.log ('current is not null');
                return (current || 0) + 1;
            }
            else {
                console.log('current is null');
                return current;
            }
        },function(error, b, d){
            if (error) 
                console.log(error);
            else 
                console.log ('error is null');
            if (b)
                console.log('boolean is true');
            else
                console.log('boolean is false');

            if (d)
                console.log('snapshot is ' + d);
            else
                console.log ('snapshot is null');
        }).then(()=>{});
    } else if (!event.data.exists() && event.data.previous.exists()){
        return CntRef.transaction(function(current){
            if (current)
                return (current || 1) - 1;
            else
                return current;
        }, function(error, b, d){if (error) console.log(error); if (d) console.log(d);}).then(()=>{});
    }
});

It fires consistently as I can see the log entries. However, the newsCnt field is not updated as expected. Sometimes it gets updated and sometimes not!!! What am I doing wrong here?

Upvotes: 3

Views: 3225

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

You should expect that a transaction be called potentially multiple times, the first time with null. That's the way transactions work. Please read the documentation here.

In particular note the following callout in that section:

Note: Because your update function is called multiple times, it must be able to handle null data. Even if there is existing data in your remote database, it may not be locally cached when the transaction function is run, resulting in null for the initial value.

Upvotes: 2

Related Questions