Can we use Atomicity in Firebase Real time database?

Viewed 60

I am using firebase realtime database with node.js. Like, I have two functions as below and I want both of them to be executed whenever an even occurs. if any of them fails, both of them must not perform any operation on my database. Is there anything to do so!

see below: -


//function1: - (which will update reward status)

async function updateRewardData() {
    await db.ref("rewardRef").set('claimable');
}

//function2: (which will update target points and nextreward)

async function updateUserData(){
    return await db.ref("userRef").update(
        {userState: "premium", nextTarget: 'X'}
    );
}

function eventOccur (){
  if(eventOccur == true){
    updateRewardData();
    updateUserData();
  }
}

if event occured I want both function to be executed and update on my firebase realtime database but if any of them fails then any of them must not update anything on DB. But as above I am not able to do that.

1 Answers

You can perform a single, multi-path update to combine the two writes:

async function updateRewardAndUserData() {
    await db.ref().update({
        "rewardRef": 'claimable',
        "userRef/userState": "premium", 
        "userRef/nextTarget": 'X'
    });
}

Note the userRef/property notation here, which means we update these specific properties of userRef and leave other properties under that path unmodified.

If you want to replace all of userRef, that'd be:

async function updateRewardAndUserData() {
    await db.ref().update({
        "rewardRef": 'claimable',
        "userRef": {
            "userState": "premium", 
            "nextTarget": 'X'
        }
    });
}
Related