Skip to content

Commit eb5065b

Browse files
authored
fix: need to encode ref before setting it (#82)
* fix: need to encode ref before setting it * fix: linting
1 parent ff6daa4 commit eb5065b

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/__tests__/decycle.spec.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,4 +74,32 @@ describe('decycle', () => {
7474
},
7575
});
7676
});
77+
78+
it('should properly encode pointers when decycling a json object', () => {
79+
const obj2 = {
80+
circle: {},
81+
};
82+
obj2.circle = obj2;
83+
84+
const obj = {
85+
paths: {
86+
'/circle': {
87+
obj2: {},
88+
},
89+
},
90+
};
91+
obj.paths['/circle'].obj2 = obj2;
92+
93+
expect(decycle(obj)).toEqual({
94+
paths: {
95+
'/circle': {
96+
obj2: {
97+
circle: {
98+
$ref: '#/paths/~1circle/obj2',
99+
},
100+
},
101+
},
102+
},
103+
});
104+
});
77105
});

src/decycle.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { isPlainObject } from './_utils';
2+
import { encodePointer } from './encodePointer';
23

34
export const decycle = (obj: unknown, replacer?: (value: any) => any) => {
45
const objs = new WeakMap<object, string>();
@@ -14,7 +15,7 @@ export const decycle = (obj: unknown, replacer?: (value: any) => any) => {
1415
const oldPath = objs.get(value);
1516
// If the value is an object or array, look to see if we have already
1617
// encountered it. If so, return a {"$ref":PATH} object.
17-
if (oldPath) return { $ref: oldPath };
18+
if (oldPath) return { $ref: encodePointer(oldPath) };
1819

1920
objs.set(value, path);
2021
// If it is an array, replicate the array.

0 commit comments

Comments
 (0)