Firebase云端函数:增量计数器 [英] Cloud Functions for Firebase: Increment Counter

查看:320
本文介绍了Firebase云端函数:增量计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it acceptable to increment a counter with a realtime database trigger using transaction?

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
        }
    })
});


推荐答案

事实上,这正是在这个代码中示例,但有一些小的区别:

Definitely! In fact, that's exactly how it's done in this code sample, although with a few small differences:

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;
    }
  });
});

值得注意的是,这个示例根据是否正在创建子节点来处理递增和递减大小写或删除。

Notably, this sample handles both an increment and a decrement case depending on whether the child node is being created or deleted.

这篇关于Firebase云端函数:增量计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆