Last active
April 3, 2020 05:50
-
-
Save threetwotwo/b063f138e8b8e1cf8370337f9109b12e to your computer and use it in GitHub Desktop.
Cloud function - update post like count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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