Skip to content

Commit 36088a6

Browse files
committedAug 15, 2023
fix: handle BigInts that has a .toJSON property
1 parent 088ea47 commit 36088a6

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed
 

‎src/request-base.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -662,7 +662,8 @@ RequestBase.prototype.send = function (data) {
662662
// merge
663663
if (isObject_ && isObject(this._data)) {
664664
for (const key in data) {
665-
if (typeof data[key] == "bigint") throw new Error("Cannot serialize BigInt value to json");
665+
if (typeof data[key] == 'bigint' && !data[key].toJSON)
666+
throw new Error('Cannot serialize BigInt value to json');
666667
if (hasOwn(data, key)) this._data[key] = data[key];
667668
}
668669
}

‎test/json.js

+26
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,32 @@ describe('req.send(Object) as "json"', function () {
132132
done();
133133
});
134134

135+
describe('when BigInts have a .toJSON property', function () {
136+
before(function () {
137+
// eslint-disable-next-line node/no-unsupported-features/es-builtins
138+
BigInt.prototype.toJSON = function () {
139+
return this.toString();
140+
};
141+
});
142+
143+
it('should accept BigInt properties', (done) => {
144+
request
145+
.post(`${uri}/echo`)
146+
.send({ number: 1n })
147+
.end((error, res) => {
148+
res.should.be.json();
149+
res.text.should.equal('{"number":"1"}');
150+
done();
151+
});
152+
});
153+
154+
after(function () {
155+
// eslint-disable-next-line node/no-unsupported-features/es-builtins
156+
delete BigInt.prototype.toJSON;
157+
});
158+
});
159+
160+
135161
it('should error for BigInt primitive', (done) => {
136162
try {
137163
request

0 commit comments

Comments
 (0)
Please sign in to comment.