Skip to content

Commit

Permalink
fix: add json module with jsonStringifyLargeObject
Browse files Browse the repository at this point in the history
  • Loading branch information
maxjeffos committed Nov 6, 2020
1 parent 8b14d00 commit 7012caa
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/lib/json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const debug = require('debug')('snyk-json');

/**
* Attempt to json-stringify an object which is potentially very large and might exceed the string limit.
* If it does exceed the string limit, try again without pretty-print to hopefully come out below the string limit.
* @param obj the object from which you want to get a JSON string
*/
export function jsonStringifyLargeObject(obj: any): string {
let res = '';
try {
// first try pretty-print
res = JSON.stringify(obj, null, 2);
return res;
} catch (err) {
// if that doesn't work, try non-pretty print
debug('JSON.stringify failed - trying again without pretty print', err);
res = JSON.stringify(obj);
return res;
}
}
30 changes: 30 additions & 0 deletions test/json.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { jsonStringifyLargeObject } from '../src/lib/json';

describe('jsonStringifyLargeObject', () => {
it('works normally with a small object', () => {
const smallObject = {
name: 'Brian',
isGoodBoy: true,
};
const s = jsonStringifyLargeObject(smallObject);
expect(s).toEqual('{\n "name": "Brian",\n "isGoodBoy": true\n}');
});

it('fallsback on non-pretty-print on very large object', () => {
const largeObject = {
name: 'Brian',
isGoodBoy: true,
type: 'big',
};
const jsonStringifyMock = jest
.spyOn(JSON, 'stringify')
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.mockImplementationOnce((any) => {
throw new Error('fake error to simulate an `Invalid string length`');
});

const s = jsonStringifyLargeObject(largeObject);
expect(jsonStringifyMock).toHaveBeenCalledTimes(2);
expect(s).toEqual(`{"name":"Brian","isGoodBoy":true,"type":"big"}`);
});
});

0 comments on commit 7012caa

Please sign in to comment.