@@ -41,18 +41,48 @@ function firestoreQueryParser(collectionRef, queryParams) {
4141} ;
4242
4343function emptyCollection ( db , collection , callback ) {
44+ console . log ( 'Emptying firestore collection' , collection ) ;
45+ var batchSize = 300 ;
4446 var collectionRef = db . collection ( collection ) ;
45- var query = collectionRef . get ( ) . then ( function ( querySnapshot ) {
46- var writeBatch = db . batch ( ) ;
47- querySnapshot . forEach ( function ( documentSnapshot ) {
48- var documentPath = collection + '/' + documentSnapshot . id ;
49- var documentRef = db . doc ( documentPath ) ;
50- writeBatch . delete ( documentRef ) ;
51- } ) ;
52- writeBatch . commit ( ) . then ( function ( ) {
53- if ( callback ) callback ( null ) ;
54- } ) ;
55- } ) ;
47+ var query = collectionRef . limit ( batchSize ) ;
48+
49+ console . log ( 'Calling deleteQueryBatch for collection' ) ;
50+ return deleteQueryBatch ( db , query , batchSize , callback ) ;
51+ }
52+
53+ function deleteQueryBatch ( db , query , batchSize , callback ) {
54+ console . log ( 'In deleteQueryBatch. Get query results' ) ;
55+ query . get ( )
56+ . then ( ( snapshot ) => {
57+ console . log ( 'Snapshot returned' ) ;
58+ console . log ( 'Size' , snapshot . size ) ;
59+ if ( snapshot . size == 0 ) {
60+ console . log ( 'Resolving because size is 0' ) ;
61+ return new Promise ( ( resolve ) => resolve ( 0 ) ) ;
62+ }
63+
64+ console . log ( 'Setting up batch for deletion' ) ;
65+ var batch = db . batch ( ) ;
66+ console . log ( 'Setting up docs for deletion' ) ;
67+ snapshot . docs . forEach ( ( doc ) => batch . delete ( doc . ref ) ) ;
68+ console . log ( 'Starting deletion commit' ) ;
69+ return batch . commit ( ) . then ( ( ) => {
70+ console . log ( 'Batch committed. Returning size' , snapshot . size ) ;
71+ return snapshot . size ;
72+ } ) ;
73+ } ) . then ( ( numDeleted ) => {
74+ console . log ( 'Num deleted' , numDeleted ) ;
75+ if ( numDeleted == 0 ) {
76+ console . log ( 'Call callback as numDeleted == 0' ) ;
77+ return callback ( ) ;
78+ }
79+
80+ console . log ( 'Schedule next batch for deletion on next tick' ) ;
81+ process . nextTick ( ( ) => {
82+ console . log ( 'TICK! Execute next batch' ) ;
83+ deleteQueryBatch ( db , query , batchSize , callback ) ;
84+ } ) ;
85+ } ) . catch ( ( e ) => { console . error ( 'Error on get' , e ) ; callback ( e ) } ) ;
5686} ;
5787
5888function getPrecondition ( vm ) {
@@ -263,14 +293,18 @@ _.extend(Firestore.prototype, {
263293 } ,
264294
265295 clear : function ( callback ) {
296+ console . log ( 'Entered clear' ) ;
266297 this . checkConnection ( ) ;
267298
268299 var self = this ;
269300 if ( ! this . collection ) {
301+ console . log ( 'No collection set, just callback' ) ;
270302 if ( callback ) callback ( null ) ;
271303 return ;
272304 }
273305
306+ console . log ( 'Calling emptyCollection for' , this . collection ) ;
307+
274308 emptyCollection ( this . db , this . collection , callback ) ;
275309 } ,
276310
0 commit comments