Cloud Functions for Firebase:增量计数器

Cloud Functions for Firebase: Increment Counter

使用事务的实时数据库触发器增加计数器是否可以接受?

exports.incPostCount = functions.database.ref('/threadsMeta/{threadId}/posts')
.onWrite(event => {
    admin.database().ref('/analytics/postCount')
    .transaction(count => {
        if (count === null) {
            return count = 1
        } else {
            return count + 1
        }
    })
});

当然!事实上,这正是它的做法 in this code sample,尽管有一些小差异:

exports.countlikechange = functions.database.ref("/posts/{postid}/likes/{likeid}").onWrite((event) => {
  var collectionRef = event.data.ref.parent;
  var countRef = collectionRef.parent.child('likes_count');

  return countRef.transaction(function(current) {
    if (event.data.exists() && !event.data.previous.exists()) {
      return (current || 0) + 1;
    }
    else if (!event.data.exists() && event.data.previous.exists()) {
      return (current || 0) - 1;
    }
  });
});

值得注意的是,此示例根据是创建还是删除子节点来处理递增和递减情况。