-
Notifications
You must be signed in to change notification settings - Fork 0
/
BatchPool.ts
71 lines (59 loc) · 1.64 KB
/
BatchPool.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import {
DocumentReference,
getFirestore,
SetOptions,
UpdateData,
WriteBatch,
WriteResult,
} from 'firebase-admin/firestore';
import { BatchInfo } from './types';
const MAX_SIZE = 500;
export class BatchPool {
pool: BatchInfo[] = [];
constructor(private size: number = MAX_SIZE) {}
private createBatchInfo = (): BatchInfo => {
return {
numberOfWrites: 0,
batch: getFirestore().batch(),
};
};
private getBatchInfo = () => {
let batch = this.pool.find(
(info) => info.numberOfWrites < Math.min(this.size, MAX_SIZE)
);
if (!batch) {
batch = this.createBatchInfo();
this.pool = [...this.pool, batch];
}
return batch;
};
private batch = () => {
const info = this.getBatchInfo();
info.numberOfWrites++;
return info.batch;
};
// public interface
create<T>(documentRef: DocumentReference<T>, data: T): WriteBatch {
return this.batch().create(documentRef, data);
}
set<T>(
documentRef: DocumentReference<T>,
data: Partial<T>,
options?: SetOptions
): WriteBatch {
if (options) return this.batch().set(documentRef, data, options);
else return this.batch().set(documentRef, data);
}
update(documentRef: DocumentReference<any>, data: UpdateData): WriteBatch {
return this.batch().update(documentRef, data);
}
delete(documentRef: DocumentReference<any>): WriteBatch {
return this.batch().delete(documentRef);
}
async commit(): Promise<WriteResult[]> {
const commits = await Promise.all(
this.pool.map((info) => info.batch.commit())
);
return commits.reduce((results, writes) => [...results, ...writes], []);
}
}