/
index.ts
58 lines (48 loc) · 1.38 KB
/
index.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
type BatchFn<K, E> = (keys: K[]) => Promise<E[]>;
interface PromiseMeta<E> {
resolve: ((entity: E) => void) | null;
promise: null | Promise<E>;
}
export default class DataLoader<Key, Entity> {
readonly batchFn: BatchFn<Key, Entity>;
readonly keys: Key[] = [];
readonly cache: Map<Key, PromiseMeta<Entity>> = new Map();
constructor(batchFn: BatchFn<Key, Entity>) {
this.batchFn = batchFn;
}
load(key: Key): Promise<Entity> {
const cache = this.cache.get(key);
if (cache && cache.promise) {
return cache.promise;
}
const shouldScheduleBatch = this.cache.size === 0;
const promiseMeta: PromiseMeta<Entity> = {
resolve: null,
promise: null,
};
promiseMeta.promise = new Promise<Entity>((resolve) => {
promiseMeta.resolve = resolve;
});
promiseMeta.promise.catch(() => {
this.cache.delete(key);
});
this.cache.set(key, promiseMeta);
this.keys.push(key);
if (shouldScheduleBatch) {
setImmediate(() => {
this.doBatch(this.keys);
});
}
return promiseMeta.promise;
}
doBatch(keys: Key[]): Promise<void> {
return this.batchFn(keys).then((results) =>
results.forEach((result, index) => {
const promiseMeta = this.cache.get(this.keys[index]);
if (promiseMeta && promiseMeta.resolve) {
promiseMeta.resolve(result);
}
}),
);
}
}