Skip to content

Commit f5ccbd7

Browse files
committed
Adding aggregation function to repo
1 parent a2a7b67 commit f5ccbd7

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
const functions = require('firebase-functions');
2+
const admin = require('firebase-admin');
3+
4+
const db = admin.firestore();
5+
6+
// [START aggregate_function]
7+
exports.aggregateRatings = functions.firestore
8+
.document('restaurants/{restId}/ratings/{ratingId}')
9+
.onWrite((change, context) => {
10+
// Get value of the newly added rating
11+
var ratingVal = change.after.data().rating;
12+
13+
// Get a reference to the restaurant
14+
var restRef = db.collection('restaurants').document(context.params.restId);
15+
16+
// Update aggregations in a transaction
17+
return db.runTransaction(transaction => {
18+
return transaction.get(restRef).then(restDoc => {
19+
// Compute new number of ratings
20+
var newNumRatings = restDoc.data('numRatings') + 1;
21+
22+
// Compute new average rating
23+
var oldRatingTotal = restDoc.data('avgRating') * restDoc.data('numRatings');
24+
var newAvgRating = (oldRatingTotal + ratingVal) / newNumRatings;
25+
26+
// Update restaurant info
27+
return transaction.update(restRef, {
28+
avgRating: newAvgRating,
29+
numRatings: newNumRatings
30+
});
31+
});
32+
});
33+
});
34+
// [END aggregate_function]
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"name": "solution-aggregation",
3+
"description": "Cloud Functions for Firebase",
4+
"scripts": {
5+
"serve": "firebase serve --only functions",
6+
"shell": "firebase experimental:functions:shell",
7+
"start": "npm run shell",
8+
"deploy": "firebase deploy --only functions",
9+
"logs": "firebase functions:log"
10+
},
11+
"dependencies": {
12+
"firebase-admin": "~5.8.1",
13+
"firebase-functions": "^1.0.1"
14+
},
15+
"private": true
16+
}

0 commit comments

Comments
 (0)