-
Notifications
You must be signed in to change notification settings - Fork 26
/
common.ts
195 lines (184 loc) · 4.98 KB
/
common.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import type { CreateReporter, Reporter } from './reporter';
export interface CacheMetadata {
createdTime: number;
ttl?: number | null;
swv?: number | null;
}
export interface CacheEntry<Value> {
metadata: CacheMetadata;
value: Value;
}
export type Eventually<Value> =
| Value
| null
| undefined
| Promise<Value | null | undefined>;
export interface Cache<Value> {
name?: string;
get: (key: string) => Eventually<CacheEntry<Value>>;
set: (key: string, value: CacheEntry<Value>) => unknown | Promise<unknown>;
delete: (key: string) => unknown | Promise<unknown>;
}
export const HANDLE = Symbol();
export type GetFreshValue<Value> = {
(): Promise<Value> | Value;
[HANDLE]?: () => void;
};
export const MIGRATED = Symbol();
export type MigratedValue<Value> = {
[MIGRATED]: true;
value: Value;
};
export type ValueCheckResultOk<Value> =
| true
| undefined
| null
| void
| MigratedValue<Value>;
export type ValueCheckResultInvalid = false | string;
export type ValueCheckResult<Value> =
| ValueCheckResultOk<Value>
| ValueCheckResultInvalid;
export interface CachifiedOptions<Value> {
/**
* The key this value is cached by
*
* @type {string} Required
*/
key: string;
/**
* Cache implementation to use
*
* Must conform with signature
* - set(key: string, value: object): void | Promise<void>
* - get(key: string): object | Promise<object>
* - delete(key: string): void | Promise<void>
*
* @type {Cache} Required
*/
cache: Cache<Value>;
/**
* This is called when no valid value is in cache for given key.
* Basically what we would do if we wouldn't use a cache.
*
* Can be async and must return fresh value or throw.
*
* @type {function(): Promise | Value} Required
*/
getFreshValue: GetFreshValue<Value>;
/**
* Time To Live; often also referred to as max age.
*
* Amount of milliseconds the value should stay in cache
* before we get a fresh one
*
* @type {number} Optional (Default: Infinity) - must be positive, can be infinite
*/
ttl?: number;
/**
* Amount of milliseconds that a value with exceeded ttl is still returned
* while a fresh value is refreshed in the background
*
* @type {number} Optional (Default: 0) - must be positive, can be infinite
*/
staleWhileRevalidate?: number;
/**
* Called for each fresh or cached value to check if it matches the
* typescript type.
*
* Value considered ok when returns:
* - true
* - migrate(newValue)
* - undefined
* - null
*
* Value considered bad when:
* - returns false
* - returns reason as string
* - throws
*
* @type {function(): boolean | undefined | string | MigratedValue} Optional, default makes no value check
*/
checkValue?: (
value: unknown,
migrate: (value: Value) => MigratedValue<Value>,
) => ValueCheckResult<Value> | Promise<ValueCheckResult<Value>>;
/**
* Set true to not even try reading the currently cached value
*
* Will write new value to cache even when cached value is
* still valid.
*
* @type {boolean} Optional (Default: false)
*/
forceFresh?: boolean;
/**
* Weather of not to fall back to cache when getting a forced fresh value
* fails.
*
* Can also be the maximum age in milliseconds that a fallback value might
* have
*
* @type {boolean | number} Optional (Default: Infinity) - number must be positive
*/
fallbackToCache?: boolean | number;
/**
* Amount of time in milliseconds before revalidation of a stale
* cache entry is started
*
* @type {number} Optional (Default: 0) - must be positive and finite
*/
staleRefreshTimeout?: number;
/**
* A reporter receives events during the runtime of
* cachified and can be used for debugging and monitoring
*
* @type {(context) => (event) => void} Optional, defaults to no reporting
*/
reporter?: CreateReporter<Value>;
}
export interface Context<Value>
extends Omit<
Required<CachifiedOptions<Value>>,
'fallbackToCache' | 'reporter'
> {
report: Reporter<Value>;
fallbackToCache: number;
metadata: CacheMetadata;
}
export function createContext<Value>({
fallbackToCache,
reporter,
...options
}: CachifiedOptions<Value>): Context<Value> {
const ttl = options.ttl ?? Infinity;
const staleWhileRevalidate = options.staleWhileRevalidate ?? 0;
const contextWithoutReport = {
checkValue: () => true,
ttl,
staleWhileRevalidate,
fallbackToCache:
fallbackToCache === false
? 0
: fallbackToCache === true || fallbackToCache === undefined
? Infinity
: fallbackToCache,
staleRefreshTimeout: 0,
forceFresh: false,
...options,
metadata: {
ttl: ttl === Infinity ? null : ttl,
swv: staleWhileRevalidate === Infinity ? null : staleWhileRevalidate,
createdTime: Date.now(),
},
};
const report =
reporter?.(contextWithoutReport) ||
(() => {
/* ¯\_(ツ)_/¯ */
});
return {
...contextWithoutReport,
report,
};
}