Skip to content

Commit

Permalink
fix circular json on data routes
Browse files Browse the repository at this point in the history
  • Loading branch information
nickreese committed May 19, 2022
1 parent 225a826 commit c35db75
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@elderjs/elderjs",
"version": "1.7.3",
"version": "1.7.4",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"engineStrict": true,
Expand Down
5 changes: 3 additions & 2 deletions src/routes/prepareRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import get from 'lodash.get';
import Page from '../utils/Page';
import { RequestOptions, ServerOptions } from '../utils/types';
import { RouteOptions } from './types';
import fixCircularJson from '../utils/fixCircularJson';

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

if (type === 'data' && data) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(data));
res.end(JSON.stringify(fixCircularJson(data)));
return undefined;
}

if (type === 'allRequests' && allRequests) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(allRequests));
res.end(JSON.stringify(fixCircularJson(allRequests)));
return undefined;
}

Expand Down
11 changes: 11 additions & 0 deletions src/utils/__tests__/replaceCircular.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import fixCircularJson from '../fixCircularJson';

describe('#fixCircularJson', () => {
it('Handles circular', () => {
const one = { f: 'this-should-work', b: undefined };
const two = { h: 123, one };
one.b = two;

expect(JSON.stringify(fixCircularJson(one))).toBe('{"f":"this-should-work","b":{"h":123,"one":"[Circular]"}}');
});
});
20 changes: 20 additions & 0 deletions src/utils/fixCircularJson.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
function fixCircularJson(val, cache = undefined) {
cache = cache || new WeakSet();

if (val && typeof val === 'object') {
if (cache.has(val)) return '[Circular]';

cache.add(val);

const obj = Array.isArray(val) ? [] : {};
for (const idx of Object.keys(val)) {
obj[idx] = fixCircularJson(val[idx], cache);
}

cache.delete(val);
return obj;
}

return val;
}
export default fixCircularJson;

0 comments on commit c35db75

Please sign in to comment.