-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cacheable.ts
82 lines (73 loc) · 2.33 KB
/
Cacheable.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
import hash from 'object-hash';
import { CacheOptions } from '../BaseCacheLoader';
import { CacheableLoader } from '../CacheableLoader';
export function Cacheable({ cacheId, options: { expirationTime, maxSize } = {}, argsToKey, keyToString, serialize, deserialize }: CacheableParams = {}) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
if (descriptor === undefined) {
descriptor = Object.getOwnPropertyDescriptor(target, propertyKey);
}
const className = target.constructor?.name || target.name;
const resolvedCacheId = cacheId || `${className}#${propertyKey}`;
const originalMethod = descriptor.value;
class CacheableCache extends CacheableLoader<CacheableKey, any> {
constructor() {
super(resolvedCacheId, {
expirationTime: expirationTime || 3600,
maxSize: maxSize || 1000
});
}
protected async load(key: CacheableKey): Promise<any> {
return originalMethod.apply(key.scope, key.args);
}
protected keyToString(key: CacheableKey): string {
let keyObject: any;
const argsToKeyFunction = argsToKey || keyToString;
if (argsToKey) {
keyObject = argsToKeyFunction(...key.args);
}
else {
keyObject = key.args;
}
if (typeof keyObject === 'string') {
return keyObject;
}
else {
return hash(keyObject);
}
}
protected serialize(value: any): any {
if (serialize) {
return serialize.call(this, value);
}
else {
return super.serialize(value);
}
}
protected deserialize(value: any): any {
if (deserialize) {
return deserialize.call(this, value);
}
else {
return super.deserialize(value);
}
}
}
const cache = new CacheableCache();
descriptor.value = function (...args: any[]) {
return cache.get({ scope: this, args: args });
};
};
}
export interface CacheableParams {
cacheId?: string;
options?: CacheOptions;
argsToKey?: (...args: any[]) => any;
/* @deprecated: replaced with argsToKey */
keyToString?: (...args: any[]) => any;
serialize?: (value: any) => any;
deserialize?: (value: any) => any;
}
interface CacheableKey {
scope: any;
args: any[];
}