Skip to content

Commit 4e35ff1

Browse files
committed
handle circular structures
1 parent 7be80d1 commit 4e35ff1

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

packages/client/lib/single-entry-cache.spec.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,4 +70,16 @@ describe('SingleEntryCache', () => {
7070

7171
assert.strictEqual(cache.get(keyObj2), undefined);
7272
});
73+
74+
it('should handle circular structures', () => {
75+
const keyObj: any = {};
76+
keyObj.self = keyObj;
77+
78+
const instance = { data: 'test data' };
79+
80+
cache.set(keyObj, instance);
81+
82+
assert.strictEqual(cache.get(keyObj), instance);
83+
});
84+
7385
});
Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,36 @@
1+
function makeCircularReplacer() {
2+
const seen = new WeakSet();
3+
return function serialize(_: string, value: any) {
4+
if (value && typeof value === 'object') {
5+
if (seen.has(value)) {
6+
return 'circular';
7+
}
8+
seen.add(value);
9+
return value;
10+
}
11+
return value;
12+
}
13+
}
114
export default class SingleEntryCache {
215
#cached?: any;
316
#key?: string;
417

518
/**
619
* Retrieves an instance from the cache based on the provided key object.
7-
*
20+
*
821
* @param keyObj - The key object to look up in the cache.
922
* @returns The cached instance if found, undefined otherwise.
10-
*
23+
*
1124
* @remarks
1225
* This method uses JSON.stringify for comparison, which may not work correctly
1326
* if the properties in the key object are rearranged or reordered.
1427
*/
1528
get(keyObj?: object) {
16-
return JSON.stringify(keyObj) === this.#key
17-
? this.#cached
18-
: undefined;
29+
return JSON.stringify(keyObj, makeCircularReplacer()) === this.#key ? this.#cached : undefined;
1930
}
2031

2132
set(keyObj: object | undefined, obj: any) {
2233
this.#cached = obj;
23-
this.#key = JSON.stringify(keyObj);
34+
this.#key = JSON.stringify(keyObj, makeCircularReplacer());
2435
}
2536
}

0 commit comments

Comments
 (0)