I am having issues where firebase is not updating the stock values in my database correctly on some occasions. I am using FieldValue.increment() and it works most of the time, but doesn't update maybe 1% of the time for some reason, even though there was no error message from firebase. I was looking at the firebase documentation and it seems that I need to make my writes to the database idempotent in the case of retries or fails. I was thinking about using transactions to check the database if a change has occurred before updating, but my code is currently writing to multiple collections using batch writes.
I was wondering if it is possible to return a batch write commit from a transaction in Firebase? I know you can do the writes inside of the transaction, but would there by any issues if you created a batch and then, based on your read operation for the transaction, you either commit or don't commit the batch of writes? It seems to be working ok when I run the program, but I'm worried there may be potential edge cases I'm not seeing. Here is an example of what I am talking about...
const batch = db.batch();
const ref1 = db.collection('references').doc('referenceId1');
const ref2 = db.collection('references').doc('referenceId2');
batch.update(ref1, {completed: true});
batch.set(ref2, ...)
return db.runTransaction((transaction)=> {
return transaction.get(ref1).then((doc) => {
const document = doc.data();
if(!ref1.completed){
return batch.commit()
}
})
})
.then(function() {
console.log("Transaction successfully committed!");
}).catch(function(error) {
console.log("Transaction failed: ", error);
});