Skip to content

Commit

Permalink
fix: handle BigInts that has a .toJSON property
Browse files Browse the repository at this point in the history
  • Loading branch information
bjornua committed Aug 15, 2023
1 parent 088ea47 commit 36088a6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/request-base.js
Original file line number Diff line number Diff line change
Expand Up @@ -662,7 +662,8 @@ RequestBase.prototype.send = function (data) {
// merge
if (isObject_ && isObject(this._data)) {
for (const key in data) {
if (typeof data[key] == "bigint") throw new Error("Cannot serialize BigInt value to json");
if (typeof data[key] == 'bigint' && !data[key].toJSON)
throw new Error('Cannot serialize BigInt value to json');
if (hasOwn(data, key)) this._data[key] = data[key];
}
}
Expand Down
26 changes: 26 additions & 0 deletions test/json.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,32 @@ describe('req.send(Object) as "json"', function () {
done();
});

describe('when BigInts have a .toJSON property', function () {
before(function () {
// eslint-disable-next-line node/no-unsupported-features/es-builtins
BigInt.prototype.toJSON = function () {
return this.toString();
};
});

it('should accept BigInt properties', (done) => {
request
.post(`${uri}/echo`)
.send({ number: 1n })
.end((error, res) => {
res.should.be.json();
res.text.should.equal('{"number":"1"}');
done();
});
});

after(function () {
// eslint-disable-next-line node/no-unsupported-features/es-builtins
delete BigInt.prototype.toJSON;
});
});


it('should error for BigInt primitive', (done) => {
try {
request
Expand Down

0 comments on commit 36088a6

Please sign in to comment.