Skip to content

Commit c35db75

Browse files
committed
fix circular json on data routes
1 parent 225a826 commit c35db75

File tree

4 files changed

+35
-3
lines changed

4 files changed

+35
-3
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@elderjs/elderjs",
3-
"version": "1.7.3",
3+
"version": "1.7.4",
44
"main": "./build/index.js",
55
"types": "./build/index.d.ts",
66
"engineStrict": true,

src/routes/prepareRouter.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import get from 'lodash.get';
44
import Page from '../utils/Page';
55
import { RequestOptions, ServerOptions } from '../utils/types';
66
import { RouteOptions } from './types';
7+
import fixCircularJson from '../utils/fixCircularJson';
78

89
export function extractDynamicRouteParams({ path, $$meta }) {
910
let i = 0;
@@ -175,13 +176,13 @@ function prepareRouter(Elder) {
175176

176177
if (type === 'data' && data) {
177178
res.setHeader('Content-Type', 'application/json');
178-
res.end(JSON.stringify(data));
179+
res.end(JSON.stringify(fixCircularJson(data)));
179180
return undefined;
180181
}
181182

182183
if (type === 'allRequests' && allRequests) {
183184
res.setHeader('Content-Type', 'application/json');
184-
res.end(JSON.stringify(allRequests));
185+
res.end(JSON.stringify(fixCircularJson(allRequests)));
185186
return undefined;
186187
}
187188

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import fixCircularJson from '../fixCircularJson';
2+
3+
describe('#fixCircularJson', () => {
4+
it('Handles circular', () => {
5+
const one = { f: 'this-should-work', b: undefined };
6+
const two = { h: 123, one };
7+
one.b = two;
8+
9+
expect(JSON.stringify(fixCircularJson(one))).toBe('{"f":"this-should-work","b":{"h":123,"one":"[Circular]"}}');
10+
});
11+
});

src/utils/fixCircularJson.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
function fixCircularJson(val, cache = undefined) {
2+
cache = cache || new WeakSet();
3+
4+
if (val && typeof val === 'object') {
5+
if (cache.has(val)) return '[Circular]';
6+
7+
cache.add(val);
8+
9+
const obj = Array.isArray(val) ? [] : {};
10+
for (const idx of Object.keys(val)) {
11+
obj[idx] = fixCircularJson(val[idx], cache);
12+
}
13+
14+
cache.delete(val);
15+
return obj;
16+
}
17+
18+
return val;
19+
}
20+
export default fixCircularJson;

0 commit comments

Comments
 (0)