File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed
firestore/solution-aggregation/functions Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change
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]
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments