Skip to content

Commit

Permalink
fix(NODE-3390): serialize non-finite doubles correctly in EJSON (#445)
Browse files Browse the repository at this point in the history
  • Loading branch information
addaleax authored Jul 2, 2021
1 parent 804050d commit 7eb7998
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/extended_json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ function serializeValue(value: any, options: EJSONSerializeOptions): any {
: { $date: { $numberLong: value.getTime().toString() } };
}

if (typeof value === 'number' && !options.relaxed) {
if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) {
// it's an integer
if (Math.floor(value) === value) {
const int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX,
Expand Down
9 changes: 9 additions & 0 deletions test/node/extended_json_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,15 @@ describe('Extended JSON', function () {
expect(serialized).to.equal('42');
});

it('should correctly serialize non-finite numbers', function () {
const numbers = { neginf: -Infinity, posinf: Infinity, nan: NaN };
const serialized = EJSON.stringify(numbers);
expect(serialized).to.equal(
'{"neginf":{"$numberDouble":"-Infinity"},"posinf":{"$numberDouble":"Infinity"},"nan":{"$numberDouble":"NaN"}}'
);
expect(EJSON.parse(serialized)).to.deep.equal(numbers);
});

it('should correctly parse null values', function () {
expect(EJSON.parse('null')).to.be.null;
expect(EJSON.parse('[null]')[0]).to.be.null;
Expand Down

0 comments on commit 7eb7998

Please sign in to comment.