-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOnionCache.ts
More file actions
77 lines (59 loc) · 1.95 KB
/
OnionCache.ts
File metadata and controls
77 lines (59 loc) · 1.95 KB
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
import { ICache } from './ICache';
import Debug from 'debug';
const debug = Debug('layer-cache:onion');
type OnionCacheConstructor = new (...caches: ICache[]) => ICache;
class OnionCacheImpl implements ICache {
caches: ICache[]
constructor(...caches: ICache[]) {
this.caches = caches;
}
async get(key: string): Promise<string> {
debug('get %s', key);
return this.__get(key, 0);
}
private async __get(key: string, index: number): Promise<string> {
if (index >= this.caches.length) {
return undefined;
}
const cache = this.caches[index];
const result = await cache.get(key);
if (!result) {
return this.__get(key, index + 1);
}
await this.__update(key, result, index - 1);
return result;
}
private async __update(key: string, value: string, index: number): Promise<void> {
if (index < 0) {
return;
}
const cache = this.caches[index];
await cache.set(key, value);
return this.__update(key, value, index - 1);
}
async set(key: string, value: string): Promise<void> {
debug('set %s', key);
return this.__set(key, value, 0);
}
private async __set(key: string, value: string, index: number): Promise<void> {
if (index >= this.caches.length) {
return;
}
const cache = this.caches[index];
await cache.set(key, value);
return this.__set(key, value, index + 1);
}
async del(key: string): Promise<void> {
debug('del %s', key);
return this.__del(key, 0);
}
private async __del(key: string, index: number): Promise<void> {
if (index >= this.caches.length) {
return;
}
const cache = this.caches[index];
await cache.del(key);
return this.__del(key, index + 1);
}
}
export const OnionCache: OnionCacheConstructor = OnionCacheImpl;