Skip to content

Instantly share code, notes, and snippets.

@DennisAlund
Created October 25, 2017 13:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DennisAlund/a47e0d2a854cb5d35d522a3e2d69f7a4 to your computer and use it in GitHub Desktop.
Save DennisAlund/a47e0d2a854cb5d35d522a3e2d69f7a4 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();
admin.database().ref("movieRevies").child(event.params.movieId).transaction(movie => {
if (!movie) {
return movie;
}
console.log(`[${event.data.id}] Got a ${review.stars} star review from ${review.name} (now ${movie.numReviews} total reviews)`);
movie.numReviews += 1;
movie.totalReviewScore += review.stars;
movie.averageScore = (movie.totalReviewScore/movie.numReviews).toPrecision(3);
return movie;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment