ios - 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
});
解决方案
您可以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))
});
您可以使用该结构以原子方式将其增加任何数值。这是有关更多详细信息的文档。
推荐阅读
- python - TypeError: 只有大小为 1 的数组可以转换为 Python 标量,
- python - 如何使用 choropleth map 函数和 python plotly 库来按大陆可视化?
- javascript - 当用户路由到另一个使用 getServerSideProps 的页面时,Next.js 如何获取数据?
- proxy - 特使中的 JSON 排序和记录响应/请求正文
- spring - 需要 dataSource 或 dataSourceClassName 或 jdbcUrl
- python - 如何在 Health-News-dataset.zip 文件下的 train 文件夹中加载文件
- apache-flink - Apache Flink 接收数据到 StatsD
- excel - 在使用 libxl 库时,以下部分中使用的这些命令是什么?
- django - 在 Django 模板中访问字典
- java - 使用 intelliJ 时 maven pom.xml 中的未知错误