-
Notifications
You must be signed in to change notification settings - Fork 130
/
Copy pathindex.js
34 lines (27 loc) · 1.18 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
const functions = require('firebase-functions');
const { getFirestore } = require('firebase-admin/firestore');
const db = getFirestore();
// [START aggregate_function]
exports.aggregateRatings = functions.firestore
.document('restaurants/{restId}/ratings/{ratingId}')
.onWrite(async (change, context) => {
// Get value of the newly added rating
const ratingVal = change.after.data().rating;
// Get a reference to the restaurant
const restRef = db.collection('restaurants').doc(context.params.restId);
// Update aggregations in a transaction
await db.runTransaction(async (transaction) => {
const restDoc = await transaction.get(restRef);
// Compute new number of ratings
const newNumRatings = restDoc.data().numRatings + 1;
// Compute new average rating
const oldRatingTotal = restDoc.data().avgRating * restDoc.data().numRatings;
const newAvgRating = (oldRatingTotal + ratingVal) / newNumRatings;
// Update restaurant info
transaction.update(restRef, {
avgRating: newAvgRating,
numRatings: newNumRatings
});
});
});
// [END aggregate_function]