Manspof
Manspof

Reputation: 357

prevent race condition in firebase cloud functions

I build firebase cloud function with global variable that increment the answer into object. the issue is that I'm looking a way to prevent condition, when same users try to increment the variable in same time.

 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'})




});

Upvotes: 4

Views: 1546

Answers (1)

Praveen Kumar A X
Praveen Kumar A X

Reputation: 431

-- Instead of using a global variable, make use of transaction

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;
});

Upvotes: 4

Related Questions