Skip to content

Instantly share code, notes, and snippets.

@Cretezy
Last active June 3, 2018 05:36
Show Gist options
  • Save Cretezy/dc54fc859e307ef5e80f3e752c5987b0 to your computer and use it in GitHub Desktop.
Save Cretezy/dc54fc859e307ef5e80f3e752c5987b0 to your computer and use it in GitHub Desktop.
Helper for batching operations in Firestore
export class FirestoreBatcher {
batches = [];
index = 0;
constructor(firestore) {
this.firestore = firestore;
}
getNext() {
if (this.index++ % 500 === 0) {
this.batches.push(this.firestore.batch());
}
return this.batches[this.batches.length - 1];
}
async commit() {
await Promise.all(this.batches.map(batch => batch.commit()));
}
delete(ref) {
this.getNext().delete(ref);
}
set(ref, data) {
this.getNext().set(ref, data);
}
update(ref, data) {
this.getNext().update(ref, data);
}
}
@Cretezy
Copy link
Author

Cretezy commented Jun 3, 2018

Usage:

const batch = new FirestoreBatcher(firebase.firestore());

batch.set(
  firebase
    .firestore()
    .collection("users")
    .doc(USER_ID),
  { name: "Charles" }
);

await batch.commit();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment