【发布时间】: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