firebase Cloud function transaction working sporadically

一笑奈何 提交于 2019-12-23 16:12:03

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/44481979/firebase-cloud-function-transaction-working-sporadically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!