Skip to content

Instantly share code, notes, and snippets.

@threetwotwo
Last active February 5, 2021 10:20
Show Gist options
  • Save threetwotwo/fac11f09f0270365feaa19c109e0d214 to your computer and use it in GitHub Desktop.
Save threetwotwo/fac11f09f0270365feaa19c109e0d214 to your computer and use it in GitHub Desktop.
Cloud function - fan out post write
export const fanOutPostWrite = functions.firestore
.document('users/{uid}/posts/{postId}')
.onWrite(async (change, context) => {
const postId = context.params.postId;
const uploader = context.params.uid;
const followerRefs = await firestore
.collection('users').doc(uploader)
.collection('followers').get();
let batchArray: FirebaseFirestore.WriteBatch[] = [];
batchArray.push(firestore.batch());
let operationCounter = 0;
let batchIndex = 0;
followerRefs.docs.forEach((doc) => {
const followerId = doc.id;
const followingFeedRef = firestore.collection('users').doc(followerId)
.collection('feed').doc(postId);
//On Delete
if (!change.after.exists && change.before.exists) {
batchArray[batchIndex].delete(followingFeedRef);
} else {
const data = change.after.data();
batchArray[batchIndex].set(followingFeedRef, data);
}
operationCounter++;
if (operationCounter === 499) {
batchArray.push(firestore.batch());
batchIndex++;
operationCounter = 0;
}
});
batchArray.forEach(batch => batch.commit());
if (change.after.exists) {
const myFeedRef = firestore.collection('users').doc(uploader)
.collection('feed').doc(postId);
console.log('should update this post on my feed', myFeedRef.path);
return myFeedRef.set(change.after.data());
}
return null;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment