Skip to content

Instantly share code, notes, and snippets.

@threetwotwo
Last active April 3, 2020 05:50
Show Gist options
  • Save threetwotwo/b063f138e8b8e1cf8370337f9109b12e to your computer and use it in GitHub Desktop.
Save threetwotwo/b063f138e8b8e1cf8370337f9109b12e to your computer and use it in GitHub Desktop.
Cloud function - update post like count
export const updatePostLikeCount = functions.firestore
.document('posts/{postId}/likes/{uid}')
.onWrite((change, context) => {
const postId = context.params.postId;
let increment: number;
const publicPostRef = firestore.collection('posts').doc(postId);
//onCreate
if (change.after.exists && !change.before.exists) {
increment = 1;
//onDelete
} else if (!change.after.exists && change.before.exists) {
increment = -1;
} else {
return null;
}
return publicPostRef.set({
'like_count': admin.firestore.FieldValue.increment(increment)
}, { merge: true });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment