From 36088a64f64b545677e132d20758318fe652e758 Mon Sep 17 00:00:00 2001 From: Bjorn Arnholtz Date: Tue, 15 Aug 2023 22:35:05 +0200 Subject: [PATCH] fix: handle BigInts that has a .toJSON property --- src/request-base.js | 3 ++- test/json.js | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/request-base.js b/src/request-base.js index cd6020bb..a2649979 100644 --- a/src/request-base.js +++ b/src/request-base.js @@ -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]; } } diff --git a/test/json.js b/test/json.js index 3d10d7b4..967c3904 100644 --- a/test/json.js +++ b/test/json.js @@ -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