Home > OS >  How to implement atomicity in firebase realtime database. For my problem
How to implement atomicity in firebase realtime database. For my problem

Time:07-12

For the given code, I try to implement atomicity. In this, if the first push gets executed then execute the second push if it fails then roll back the first push and start again from the top. If the first push is executed successfully then execute the second if it is executed successfully then execute the third and if the third failed then roll back both the first and second push. and start execution again from the top. if it passes then save the data to the real-time database.

               "if(message){
                    ref.push({
                        mobNo : senderMobNo,
                        message : message,
                        time : d
                    });
                    ref2.push({
                        mobNo : senderMobNo,
                        message : message,
                        time : d
                    });
                    ref3.push({
                        mobNo : senderMobNo,
                        message : message,
                        time : d
                    });
                }"

CodePudding user response:

If the recursion doesn't work for you, and you want all data to be committed, then you should consider performing simultaneous additions to multiple locations in the JSON tree with a single call to update().

In this way, you can write the new messages simultaneously to the desired locations. These operations are atomic, either all updates succeed or all updates fail. In this case, there is no need to roll something back.

CodePudding user response:

It sounds like you want to perform a multi-path update, which is a way to combine multiple updates in a single API call:

if(message){
    const updates = {};
    let id = ref.push().key; // generate a push key
    updates[key] = {
        mobNo : senderMobNo,
        message : message,
        time : d
    });
    id = ref.push().key; // generate another push key
    updates[id] = {
        mobNo : senderMobNo,
        message : message,
        time : d
    });
    id = ref.push().key; // generate a third push key
    updates[id] = {
        mobNo : senderMobNo,
        message : message,
        time : d
    });
    ref.update(updates); // send them all to the database in one go
}
  • Related