Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle BigInts that has a .toJSON property #1776

Merged
merged 1 commit into from
Aug 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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