Skip to content

Commit 44b8cd1

Browse files
committed
use WriteBatch instead of creating documents individually
1 parent 05dd0d6 commit 44b8cd1

File tree

1 file changed

+31
-6
lines changed
  • packages/firestore/test/integration/util

1 file changed

+31
-6
lines changed

packages/firestore/test/integration/util/helpers.ts

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,9 @@ import {
3232
PrivateSettings,
3333
SnapshotListenOptions,
3434
newTestFirestore,
35-
newTestApp
35+
newTestApp,
36+
writeBatch,
37+
WriteBatch
3638
} from './firebase_export';
3739
import {
3840
ALT_PROJECT_ID,
@@ -315,11 +317,34 @@ export function withTestCollectionSettings<T>(
315317
const collectionId = 'test-collection-' + doc(collection(testDb, 'x')).id;
316318
const testCollection = collection(testDb, collectionId);
317319
const setupCollection = collection(setupDb, collectionId);
318-
const sets: Array<Promise<void>> = [];
319-
Object.keys(docs).forEach(key => {
320-
sets.push(setDoc(doc(setupCollection, key), docs[key]));
321-
});
322-
return Promise.all(sets).then(() => fn(testCollection, testDb));
320+
321+
const writeBatchCommits: Array<Promise<void>> = [];
322+
let writeBatch_: WriteBatch | null = null;
323+
let writeBatchSize = 0;
324+
325+
for (const key in docs) {
326+
if (writeBatch_ === null) {
327+
writeBatch_ = writeBatch(setupDb);
328+
}
329+
330+
writeBatch_.set(doc(setupCollection, key), docs[key]);
331+
writeBatchSize++;
332+
333+
// Write batches are capped at 500 writes. Use 400 just to be safe.
334+
if (writeBatchSize === 400) {
335+
writeBatchCommits.push(writeBatch_.commit());
336+
writeBatch_ = null;
337+
writeBatchSize = 0;
338+
}
339+
}
340+
341+
if (writeBatch_ !== null) {
342+
writeBatchCommits.push(writeBatch_.commit());
343+
}
344+
345+
return Promise.all(writeBatchCommits).then(() =>
346+
fn(testCollection, testDb)
347+
);
323348
}
324349
);
325350
}

0 commit comments

Comments
 (0)