Created
February 12, 2019 11:39
-
-
Save shramee/5b142f7a1d18472f8081c88cedb17999 to your computer and use it in GitHub Desktop.
Class to do a batch set using firestore admin object.
This file contains hidden or 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
/** | |
* 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