/
multi-caching.ts
80 lines (78 loc) · 2.2 KB
/
multi-caching.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
import { Cache, Milliseconds } from './caching';
export type MultiCache = Omit<Cache, 'store'> &
Pick<Cache['store'], 'mset' | 'mget' | 'mdel'>;
/**
* Module that lets you specify a hierarchy of caches.
*/
export function multiCaching<Caches extends Cache[]>(
caches: Caches,
): MultiCache {
const get = async <T>(key: string) => {
for (const cache of caches) {
try {
const val = await cache.get<T>(key);
if (val !== undefined) return val;
} catch (e) {}
}
};
const set = async <T>(
key: string,
data: T,
ttl?: Milliseconds | undefined,
) => {
await Promise.all(caches.map((cache) => cache.set(key, data, ttl)));
};
return {
get,
set,
del: async (key) => {
await Promise.all(caches.map((cache) => cache.del(key)));
},
async wrap<T>(
key: string,
fn: () => Promise<T>,
ttl?: Milliseconds,
): Promise<T> {
let value: T | undefined;
let i = 0;
for (; i < caches.length; i++) {
try {
value = await caches[i].get<T>(key);
if (value !== undefined) break;
} catch (e) {}
}
if (value === undefined) {
const result = await fn();
await set<T>(key, result, ttl);
return result;
} else {
await Promise.all(
caches.slice(0, i).map((cache) => cache.set(key, value, ttl)),
);
}
return value;
},
reset: async () => {
await Promise.all(caches.map((x) => x.reset()));
},
mget: async (...keys: string[]) => {
const values = new Array(keys.length).fill(undefined);
for (const cache of caches) {
if (values.every((x) => x !== undefined)) break;
try {
const val = await cache.store.mget(...keys);
val.forEach((v, i) => {
if (values[i] === undefined && v !== undefined) values[i] = v;
});
} catch (e) {}
}
return values;
},
mset: async (args: [string, unknown][], ttl?: Milliseconds) => {
await Promise.all(caches.map((cache) => cache.store.mset(args, ttl)));
},
mdel: async (...keys: string[]) => {
await Promise.all(caches.map((cache) => cache.store.mdel(...keys)));
},
};
}