首页 > 解决方案 > Firebase - 如何使用云函数更新 RealTimeDatabase 事务

问题描述

我想通过事务使用 Cloud Functions 更新我的数据库中的views_count 。

@posts
  @postId_123
     -"url": "https://..."
     -"id": "..."
     -views_count: 17 // increase from 17 to 18

我知道如何在 Swift 中更新客户端上的 iOS 事务,但我不是原生 Javascript 开发人员,我正在尝试使用云函数尝试同样的事情。我找不到任何关于使用云函数更新事务的示例代码

客户端:

lazy var functions = Functions.functions()

func updateViewCount() {

    let data: [String: Any] = ["postId": postId_123, "uid": Auth.auth().currentUser!.uid:]

    functions.httpsCallable("updateViewCount").call(data) { (result, error) in

        if let error = error { return }

        if let result = result {
            print(result)
        }
    }
}

let viewCountObserver = Database.database().reference().child("posts")
func addListenerForViewCount() {

    viewCountObserver.child(postId_123).child("views_count").observe( .value) { (snapshot) in

        let views_count = snapshot.value as? Int ?? 0
        print("the updated views count is: ", views_count)
    }
}

云功能:

const functions = require('firebase-functions');
const admin = require('firebase-admin')
admin.initializeApp();

exports.updateViewCount = functions.https.onCall((data, context) => {

    const postId = data.postId;
    const userId = data.uid;
    console.log("postId: " + postId + ", userId: " + userId);

    const postsRef = admin.database().ref('/posts/${postId}/views_count');

    // not sure what to do to update the views_count key using a Transaction from this point on
});

标签: iosswiftfirebase-realtime-databasegoogle-cloud-functions

解决方案


您可以ServerValue.Increment为此使用:

exports.updateViewCount = functions.https.onCall((data, context) => {

    const postId = data.postId;
    const userId = data.uid;
    console.log("postId: " + postId + ", userId: " + userId);

    const postsRef = admin.database().ref('posts').child(postId);

    postsRef.child('views_count').set(firebase.database.ServerValue.increment(1))

});

您可以使用该结构以原子方式将其增加任何数值。这是有关更多详细信息的文档


推荐阅读