@unchainedshop/utils 4.8.4 → 4.8.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/memoize-with-ttl.d.ts +8 -0
- package/lib/memoize-with-ttl.js +35 -0
- package/package.json +1 -1
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
type AsyncFunction = (...args: any[]) => Promise<any>;
|
|
2
|
+
interface MemoizeOptions {
|
|
3
|
+
cacheKey?: (args: any[]) => string;
|
|
4
|
+
}
|
|
5
|
+
export declare function memoizeWithTTL<T extends AsyncFunction>(fn: T, ttlMs: number, options?: MemoizeOptions): T & {
|
|
6
|
+
clear: () => void;
|
|
7
|
+
};
|
|
8
|
+
export {};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
function createTTLCache(ttlMs) {
|
|
2
|
+
const store = new Map();
|
|
3
|
+
return {
|
|
4
|
+
get(key) {
|
|
5
|
+
const entry = store.get(key);
|
|
6
|
+
if (!entry)
|
|
7
|
+
return undefined;
|
|
8
|
+
if (Date.now() > entry.expiry) {
|
|
9
|
+
store.delete(key);
|
|
10
|
+
return undefined;
|
|
11
|
+
}
|
|
12
|
+
return entry.value;
|
|
13
|
+
},
|
|
14
|
+
set(key, value) {
|
|
15
|
+
store.set(key, { value, expiry: Date.now() + ttlMs });
|
|
16
|
+
},
|
|
17
|
+
clear() {
|
|
18
|
+
store.clear();
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export function memoizeWithTTL(fn, ttlMs, options) {
|
|
23
|
+
const cache = createTTLCache(ttlMs);
|
|
24
|
+
const memoized = async function (...args) {
|
|
25
|
+
const key = options?.cacheKey ? options.cacheKey(args) : JSON.stringify(args);
|
|
26
|
+
const cached = cache.get(key);
|
|
27
|
+
if (cached !== undefined)
|
|
28
|
+
return cached;
|
|
29
|
+
const result = await fn(...args);
|
|
30
|
+
cache.set(key, result);
|
|
31
|
+
return result;
|
|
32
|
+
};
|
|
33
|
+
memoized.clear = () => cache.clear();
|
|
34
|
+
return memoized;
|
|
35
|
+
}
|
package/package.json
CHANGED