我使用全局变量构建firebase云功能,将答案增加到对象中。 问题在于,当相同的用户试图同时增加变量时,我正在寻找一种预防条件的方法。
const functions = require('firebase-functions');
// global variable
let answers = {'a':0, 'b':0,'c':0}
exports.tryGetCount = functions.https.onRequest((req, res) => {
// console.log(req.body)
let userAnswer = req.body.answer;
let userInformation = req.body.userInfo;
if(answers.hasOwnProperty(userAnswer)){
answers[userAnswer]++; // increment the answer
return res.send({answers:answers})
}
return res.status(400).json({error:'invalid answer propertu'})
});
答案 0 :(得分:2)
- 不使用全局变量,而是使用事务
https://firebase.google.com/docs/database/web/read-and-write#save_data_as_transactions
var ref = new Firebase('xxx');
var countRef = ref.child("ans").child("-KGb1Ls-gEErWbAMMnZC").child('count');
countRef.transaction(function(currentCount) {
return currentCount + 1;
});