-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise.ts
117 lines (105 loc) · 2.71 KB
/
promise.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
export interface Keeper<R> {
fresh: () => Promise<R>;
get: () => Promise<R>;
stale: () => R;
start: (timeout?: number) => undefined;
stop: () => void;
timer: number | undefined;
}
const empty = Symbol('Empty');
const defaultStorage = new WeakMap<() => Promise<unknown>, unknown>();
/**
* Promise Keeper: caching for promises.
*
* Provides caching behavior to an expensive function. Can perform periodic
* background refresh.
*
* The purpose of this module is to minimize waiting for time intensive
* functions to complete. This can also be used to provide a
* stale-while-revalidate pattern.
*
* Terminology
* * **settled**: the last returned value of the expensive function, when it is
* a promise, then that promise has already settled.
* * **pending**: the latest returned value of the expensive function, when it
* is a promise, it has not settled yet.
*
* Possible States:
* | state | cache | promise |
* | ------: | ----: | ------: |
* | empty | ❌ | ❌ |
* | pending | ❌ | ✅ |
* | fresh | ✅ | ❌ |
* | stale | ✅ | ✅ |
*/
const keep = <R>(fn: () => Promise<R>) => {
let settled: R | typeof empty = empty;
let pending: Promise<R> | typeof empty = empty;
let timeout: number | undefined;
const invoke = () =>
fn().then((data) => {
settled = data;
pending = empty;
return data;
});
const fresh = () => {
if (pending !== empty) {
// If we already have an unsettled promise, then chain this invocation.
pending = pending.then(invoke);
} else {
pending = invoke();
}
return pending;
};
const get = () => {
if (pending !== empty) {
return pending;
}
if (settled !== empty) {
return Promise.resolve(settled);
}
return fresh();
};
const stale = () => {
if (settled !== empty) {
return settled;
}
throw new Error('No settled data available.');
};
/**
* Terminate any keepFresh() intervals.
*/
const stop = () => {
if (timeout) {
clearTimeout(timeout as number);
timeout = undefined;
}
};
/**
* Refresh cache on a given interval.
* @param delay milliseconds to keep refreshing data
*/
const start = (delay = 1000 * 60 * 60 * 30) => {
stop();
timeout = setInterval(fresh, delay) as unknown as number;
};
return {
fresh,
get,
stale,
start,
stop,
/**
* Return the current timer. Useful if you wish to `unref` it.
*/
get timer() {
return timeout;
},
};
};
export const keeper = <R>(fn: () => Promise<R>, storage = defaultStorage) => {
if (!storage.has(fn)) {
storage.set(fn, keep(fn));
}
return storage.get(fn) as Keeper<R>;
};