I am new to Cloud Functions.
I have a table ‘drivers’ with having few details.
Now I want to write a Firebase Cloud Function which will
- trigger whenever the value in ‘drivers/{driverId}/history/{rideId}/rating’ is set.
- Update totalRating (drivers/{driverId}/totalRating) value to oldTotalRatingValue + NewTotalRatingValue.
Any help or a reference would be appreciated.
Thanks in Advance.
=============My Approach======================
exports.increaseRating = functions.database.ref('/drivers/{driverId}/history/{historyId}/rating') .onUpdate((snapshot, context) => { var newRating = snapshot.after.val(); var oldRating = 0; var db = admin.database(); var ref = db.ref(`/drivers/${context.params.driverId}/totalRating`); ref.once("value", function(snapshot) { oldRating = snapshot.val(); }); console.log(oldRating); var finalRating = oldRating + newRating; return admin.database().ref(`/drivers/${context.params.driverId}`).update({ "totalRating": finalRating, }) })
but my var oldRating doesn’t updates to database value.
Advertisement
Answer
You need to use a Transaction
if you want to update the totalRanking
, in order to avoid that another instance of the Cloud Function writes to the totalRanking
location before your new value is successfully written by the current Cloud Function.
The following should work (untested):
exports.increaseRating = functions.database.ref('/drivers/{driverId}/history/{historyId}/rating') .onUpdate((snapshot, context) => { const newRating = snapshot.after.val(); const totalRatingRef = admin.database().ref(`/drivers/${context.params.driverId}/totalRating`); return totalRatingRef.transaction(currentTotalRating => { // If /drivers/{driverId}/history/{historyId}/rating has never been set, newRating will be `null`. return currentTotalRating + newRating; }); });
Note that we are returning the Promise returned by the Transaction. More details on this key point in the doc.