Skip to content

Commit

Permalink
fix(ext-json): deserialize doubles as Number in relaxed mode
Browse files Browse the repository at this point in the history
This ensures we take relaxed/strict mode into account when
deserializing a double, similar to the integer checks above it.

NODE-1639
  • Loading branch information
mbroadst committed Oct 29, 2018
1 parent 4ba5226 commit a767fa1
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
12 changes: 7 additions & 5 deletions lib/extended_json.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,17 @@ const keysToCodecs = {

function deserializeValue(self, key, value, options) {
if (typeof value === 'number') {
if (options.relaxed) {
return value;
}

// if it's an integer, should interpret as smallest BSON integer
// that can represent it exactly. (if out of range, interpret as double.)
if (Math.floor(value) === value) {
let int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX,
int64Range = value >= BSON_INT64_MIN && value <= BSON_INT64_MAX;

if (int32Range) return options.strict ? new Int32(value) : value;
if (int64Range) return options.strict ? new Long.fromNumber(value) : value;
if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) return new Int32(value);
if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) return new Long.fromNumber(value);
}

// If the number is a non-integer or out of integer range, should interpret as BSON Double.
return new Double(value);
}
Expand Down
6 changes: 6 additions & 0 deletions test/node/extended_json_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -247,4 +247,10 @@ describe('Extended JSON', function() {
// timestamp
expect(result.timestamp).to.be.an.instanceOf(BSON.Timestamp);
});

it('should return a native number for a double in relaxed mode', function() {
const result = EJSON.deserialize({ test: 34.12 }, { relaxed: true });
expect(result.test).to.equal(34.12);
expect(result.test).to.be.a('number');
});
});

0 comments on commit a767fa1

Please sign in to comment.