Skip to content

Instantly share code, notes, and snippets.

@shramee
Created February 12, 2019 11:39
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 shramee/5b142f7a1d18472f8081c88cedb17999 to your computer and use it in GitHub Desktop.
Save shramee/5b142f7a1d18472f8081c88cedb17999 to your computer and use it in GitHub Desktop.
Class to do a batch set using firestore admin object.
/**
* Class to handle batch set to docs maximum 500 per commit
*/
class BatchSetHandler {
/**
* Construct BatchSetHandler object
* @param {firebase.firestore.WriteBatch} dbBatch
* @param {function} commitCallback Callback after commit promise is resolved.
*/
constructor( dbBatch, commitCallback ) {
if ( typeof commitCallback !== 'function' ) {
commitCallback = ( count ) => {
console.log( 'Committed ' + count + ' transactions.' );
};
}
this.batch = dbBatch;
this.count = 0;
this._promises = [];
this.commitCallback = commitCallback;
}
/**
* Set object to docRef
* Handles maximum 500 items in one batch
* @param {firebase.firestore.DocumentReference} docRef Document reference
* @param {object} obj Object to push to Document reference
*/
set( docRef, obj ) {
batchSetHandle.batch.set( docRef, obj, {merge: true} );
this.count++;
if ( batchSetHandle.count > 499 ) {
this.commit();
}
}
/**
* Commit the batch
*/
commit() {
const that = this;
this._promises.push(
this.batch.commit().then( () => {
const count = that.count;
that.count = 0;
return this.commitCallback( count, that ) || null;
} )
);
}
/**
* Get all promises from commits
* @returns {Array} Promise[]
*/
promises() {
return this._promises;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment