-
Notifications
You must be signed in to change notification settings - Fork 532
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: add json module with jsonStringifyLargeObject
- Loading branch information
Showing
2 changed files
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"}`); | ||
}); | ||
}); |