Skip to content

Instantly share code, notes, and snippets.

@DennisAlund
Last active October 25, 2017 13:25
Show Gist options
  • Select an option

  • Save DennisAlund/c880b01369013791139e04e9d4f7b482 to your computer and use it in GitHub Desktop.

Select an option

Save DennisAlund/c880b01369013791139e04e9d4f7b482 to your computer and use it in GitHub Desktop.
export const countReviews = functions.firestore.document("movies/{movieId}/reviews/{reviewId}").onCreate(async (event) => {
console.log(`Got a ${event.data.data().stars} star review`);
const review = event.data.data();
const movieRef = admin.firestore().collection("movies").doc(event.params.movieId);
admin.firestore().runTransaction(async transaction => {
const movie = (await transaction.get(movieRef)).data();
movie.numReviews += 1;
movie.totalReviewScore += review.stars;
movie.averageScore = (movie.totalReviewScore/movie.numReviews).toPrecision(3);
console.log(`[${event.data.id}] Got a ${review.stars} star review from ${review.name} (now ${movie.numReviews} total reviews)`);
return transaction.update(movieRef, movie);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment