【问题标题】:Firebase -How to update a RealTimeDatabase Transaction using a Cloud FunctionFirebase - 如何使用云函数更新 RealTimeDatabase 事务
【发布时间】:2021-02-18 01:03:44
【问题描述】:

我想通过事务使用 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
});

【问题讨论】:

    标签: ios swift firebase-realtime-database google-cloud-functions


    【解决方案1】:

    您可以为此使用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))
    
    });
    

    您可以使用该结构以原子方式将其增加任何数值。这是documentation了解更多详情。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    相关资源
    最近更新 更多