I am using Firebase Cloud Functions, which get triggered by the creation of a document in Firestore. On creation of the object, I need to undertake two different operations in parallel:
- update the value of a field in a specific document (not the one which was created and triggered the cloud function)
- run a transaction on another document.
So my questions are:
- How do I ensure that both of my operations have been successfully completed before ending the cloud function itself?
- How do I implement separate retry mechanism for each of the two operations (as I do not want a common retry mechanism for the whole function as it can redo the transaction operation even if it was the other operation that had failed)?
Here is my current code:
exports.onCityCreated = functions.firestore
.document('Cities/{cityId}')
.onCreate((snap, context) => {
const db = admin.firestore();
const newCity = snap.data();
const mayorId = newEvent.mayorID;
const mayorRef = db.doc('Users/'+ mayorId);
const timestamp = admin.firestore.FieldValue.serverTimestamp();
db.doc('Utils/lastPost').update({timestamp: timestamp}); //First Operation - Timestamp Update
return db.runTransaction(t => { //Second Operation - Transaction
return t.get(mayorRef).then(snapshot => {
var new_budget = snapshot.data().b - 100;
return t.update(mayorRef, {b: new_budget});
})
.then(result => {
return console.log('Transaction success!');
})
.catch(err => {
console.log('Transaction failure:', err);
});
});
});