Skip to content

Commit 98c58f9

Browse files
authored
fix: handle slashes better when decycling (#90)
- needed by stoplightio/prism#1456
1 parent 867da5b commit 98c58f9

File tree

2 files changed

+11
-11
lines changed

2 files changed

+11
-11
lines changed

src/__tests__/decycle.spec.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -83,19 +83,19 @@ describe('decycle', () => {
8383

8484
const obj = {
8585
paths: {
86-
'/circle': {
86+
'/circle/foo': {
8787
obj2: {},
8888
},
8989
},
9090
};
91-
obj.paths['/circle'].obj2 = obj2;
91+
obj.paths['/circle/foo'].obj2 = obj2;
9292

9393
expect(decycle(obj)).toEqual({
9494
paths: {
95-
'/circle': {
95+
'/circle/foo': {
9696
obj2: {
9797
circle: {
98-
$ref: '#/paths/~1circle/obj2',
98+
$ref: '#/paths/~1circle~1foo/obj2',
9999
},
100100
},
101101
},

src/decycle.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import { isPlainObject } from './_utils';
2-
import { encodePointer } from './encodePointer';
2+
import { pathToPointer } from './pathToPointer';
33

44
export const decycle = (obj: unknown, replacer?: (value: any) => any) => {
55
const objs = new WeakMap<object, string>();
6-
return (function derez(value: any, path: string) {
6+
return (function derez(value: any, path: string[]) {
77
// The new object or array
88
let curObj: any;
99

@@ -15,22 +15,22 @@ export const decycle = (obj: unknown, replacer?: (value: any) => any) => {
1515
const oldPath = objs.get(value);
1616
// If the value is an object or array, look to see if we have already
1717
// encountered it. If so, return a {"$ref":PATH} object.
18-
if (oldPath) return { $ref: encodePointer(oldPath) };
18+
if (oldPath) return { $ref: oldPath };
1919

20-
objs.set(value, path);
20+
objs.set(value, pathToPointer(path));
2121
// If it is an array, replicate the array.
2222
if (Array.isArray(value)) {
23-
curObj = value.map((element, i) => derez(element, `${path}/${i}`));
23+
curObj = value.map((element, i) => derez(element, [...path, String(i)]));
2424
} else {
2525
// It is an object, replicate the object.
2626
curObj = {};
2727
Object.keys(value).forEach(name => {
28-
curObj[name] = derez(value[name], `${path}/${name}`);
28+
curObj[name] = derez(value[name], [...path, name]);
2929
});
3030
}
3131
objs.delete(value);
3232
return curObj;
3333
}
3434
return value;
35-
})(obj, '#');
35+
})(obj, []);
3636
};

0 commit comments

Comments
 (0)