我想使用事务使用云函数更新数据库中的views_count。
@posts
@postId_123
-"url": "https://..."
-"id": "..."
-views_count: 17 // increase from 17 to 18
我知道如何在Swift的客户端上更新iOS版的Transaction,但我不是本地Javascript开发人员,我正试图使用Cloud Function来尝试同样的事情。我找不到任何使用云功能更新交易的示例代码
客户端:
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
});
您可以使用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))
});
您可以使用该结构以原子方式将其递增任何数值。以下是有关详细信息的文档。