Skip to content

Commit eb006e4

Browse files
committed
Add safeParse(). Closes #9
1 parent f778a0a commit eb006e4

File tree

3 files changed

+36
-7
lines changed

3 files changed

+36
-7
lines changed

lib/index.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,3 +84,14 @@ exports.scan = function (obj, options) {
8484
}
8585
}
8686
};
87+
88+
89+
exports.safeParse = function (text, reviver) {
90+
91+
try {
92+
return exports.parse(text, reviver);
93+
}
94+
catch (ignoreError) {
95+
return null;
96+
}
97+
};

package.json

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,13 @@
1212
],
1313
"dependencies": {},
1414
"devDependencies": {
15-
"benchmark": "^2.1.4",
16-
"code": "5.x.x",
17-
"lab": "18.x.x"
15+
"@hapi/code": "5.x.x",
16+
"@hapi/lab": "18.x.x",
17+
"benchmark": "^2.1.4"
1818
},
1919
"scripts": {
20-
"test": "lab -a code -t 100 -L",
21-
"test-cov-html": "lab -a code -r html -o coverage.html"
20+
"test": "lab -a @hapi/code -t 100 -L",
21+
"test-cov-html": "lab -a @hapi/code -r html -o coverage.html"
2222
},
2323
"license": "BSD-3-Clause"
2424
}

test/index.js

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
'use strict';
22

3-
const Code = require('code');
3+
const Code = require('@hapi/code');
44
const Bourne = require('..');
5-
const Lab = require('lab');
5+
const Lab = require('@hapi/lab');
66

77

88
const internals = {};
@@ -137,4 +137,22 @@ describe('Bourne', () => {
137137
expect(obj).to.equal({ a: 5, b: 6, hasOwnProperty: 'text' });
138138
});
139139
});
140+
141+
describe('safeParse()', () => {
142+
143+
it('parses object string', () => {
144+
145+
expect(Bourne.safeParse('{"a": 5, "b": 6}')).to.equal({ a: 5, b: 6 });
146+
});
147+
148+
it('returns null on proto object string', () => {
149+
150+
expect(Bourne.safeParse('{ "a": 5, "b": 6, "__proto__": { "x": 7 } }')).to.be.null();
151+
});
152+
153+
it('returns null on invalid object string', () => {
154+
155+
expect(Bourne.safeParse('{"a": 5, "b": 6')).to.be.null();
156+
});
157+
});
140158
});

0 commit comments

Comments
 (0)