Skip to content

Commit

Permalink
Change clear collections to be a batch function
Browse files Browse the repository at this point in the history
- Firebase only supports 500 changes as part of a batch, so this
  function needs to loop through larger collections.
  • Loading branch information
rickerbh committed Jan 22, 2019
1 parent adb9165 commit 40ccc0f
Showing 1 changed file with 27 additions and 11 deletions.
38 changes: 27 additions & 11 deletions lib/databases/firestore.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,18 +41,34 @@ function firestoreQueryParser(collectionRef, queryParams) {
};

function emptyCollection(db, collection, callback) {
var batchSize = 300;
var collectionRef = db.collection(collection);
var query = collectionRef.get().then(function (querySnapshot) {
var writeBatch = db.batch();
querySnapshot.forEach(function (documentSnapshot) {
var documentPath = collection + '/' + documentSnapshot.id;
var documentRef = db.doc(documentPath);
writeBatch.delete(documentRef);
});
writeBatch.commit().then(function () {
if (callback) callback(null);
});
});
var query = collectionRef.limit(batchSize);

return deleteQueryBatch(db, query, batchSize, callback);
}

function deleteQueryBatch(db, query, batchSize, callback) {
query.get()
.then((snapshot) => {
if (snapshot.size == 0) {
return 0;
}

var batch = db.batch();
snapshot.docs.forEach((doc) => batch.delete(doc.ref));
return batch.commit().then(() => {
return snapshot.size;
});
}).then((numDeleted) => {
if (numDeleted == 0) {
return callback();
}

process.nextTick(() => {
deleteQueryBatch(db, query, batchSize, callback);
});
}).catch(callback);
};

function getPrecondition(vm) {
Expand Down

0 comments on commit 40ccc0f

Please sign in to comment.