【发布时间】:2019-10-15 10:02:24
【问题描述】:
我有以下结构:
{
"point_logs": {
"user1": {
"LrDm-0OBBg84rTSXGyF": {
"action": "action_type_1",
"point": 1
},
"LrDm0b0oF-48EF3ZsqF": {
"action": "action_type_2",
"point": 1
}
},
"user2": {
"LrDm0dfZsEE40HvnwEc": {
"action": "action_type_5",
"point": 1
},
"LrDm0gKsdEw3O3ync_7": {
"action": "redeem_1",
"point": -2
}
}
}
}
我目前正在添加一个firebase云函数来兑换积分,因为云函数是async,为了确保有足够的积分可以兑换,我需要将兑换函数设为原子。
我尝试使用事务:
exports.redeemPoints = functions.https.onRequest((req, res) => {
db.ref('/point_logs/' + user_id).transaction((data) => {
admin.database().ref('/points_assign_logs/' + user_id).once('value', (snapshot) => {
// code to iterate and sum all points from this user's logs
if (remain_points >= redeem_point) {
admin.database().ref('/point_logs/' + user_id).push(redeem_log);
}
return data
});
});
});
但是对于这个函数的多次异步调用,剩余点可能是负数,即使有一个检查if (remain_points >= redeem_point)。
我怎样才能正确地使用用户事务来原子化这个日志更新?
【问题讨论】:
-
你的交易在这里看起来没什么用,你想总结什么?
-
呀,我也觉得没用,总和是从所有日志中累积积分。也许我应该提交总积分,然后更新交易。
标签: node.js firebase firebase-realtime-database google-cloud-functions