forked from redis/node-redis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingle-entry-cache.ts
More file actions
36 lines (34 loc) · 1.01 KB
/
Copy pathsingle-entry-cache.ts
File metadata and controls
36 lines (34 loc) · 1.01 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
function makeCircularReplacer() {
const seen = new WeakSet();
return function serialize(_: string, value: any) {
if (value && typeof value === 'object') {
if (seen.has(value)) {
return 'circular';
}
seen.add(value);
return value;
}
return value;
}
}
export default class SingleEntryCache {
#cached?: any;
#key?: string;
/**
* Retrieves an instance from the cache based on the provided key object.
*
* @param keyObj - The key object to look up in the cache.
* @returns The cached instance if found, undefined otherwise.
*
* @remarks
* This method uses JSON.stringify for comparison, which may not work correctly
* if the properties in the key object are rearranged or reordered.
*/
get(keyObj?: object) {
return JSON.stringify(keyObj, makeCircularReplacer()) === this.#key ? this.#cached : undefined;
}
set(keyObj: object | undefined, obj: any) {
this.#cached = obj;
this.#key = JSON.stringify(keyObj, makeCircularReplacer());
}
}