Firebase 云函数:增量计数器 [英] Cloud Functions for Firebase: Increment Counter
本文介绍了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屋!
查看全文