From b6d930fd31f8ad8b4aa2532f4e25d5b15fcadd4a Mon Sep 17 00:00:00 2001 From: Arda TANRIKULU Date: Wed, 7 Jun 2023 15:35:20 +0300 Subject: [PATCH] enhance(bigint): serialize as numbers if possible --- .changeset/great-seahorses-switch.md | 5 +++++ src/scalars/BigInt.ts | 6 +++--- tests/BigInt.test.ts | 26 +++++++++++++------------- 3 files changed, 21 insertions(+), 16 deletions(-) create mode 100644 .changeset/great-seahorses-switch.md diff --git a/.changeset/great-seahorses-switch.md b/.changeset/great-seahorses-switch.md new file mode 100644 index 000000000..6a76345f1 --- /dev/null +++ b/.changeset/great-seahorses-switch.md @@ -0,0 +1,5 @@ +--- +'graphql-scalars': patch +--- + +Serialize bigints as numbers if possible diff --git a/src/scalars/BigInt.ts b/src/scalars/BigInt.ts index 78da258d7..1b0b3e3dc 100644 --- a/src/scalars/BigInt.ts +++ b/src/scalars/BigInt.ts @@ -10,12 +10,12 @@ function isSafeInteger(val: bigint): boolean { } function serializeSafeBigInt(val: bigint): bigint | number | string { - if ('toJSON' in BigInt.prototype) { - return val; - } if (isSafeInteger(val)) { return Number(val); } + if ('toJSON' in BigInt.prototype) { + return val; + } if (!warned) { warned = true; console.warn( diff --git a/tests/BigInt.test.ts b/tests/BigInt.test.ts index 67eeaf745..45437711a 100644 --- a/tests/BigInt.test.ts +++ b/tests/BigInt.test.ts @@ -1,7 +1,7 @@ -import { GraphQLObjectType, GraphQLNonNull, GraphQLInputObjectType } from 'graphql/type/definition'; -import { GraphQLSchema, graphql } from 'graphql'; -import { GraphQLBigInt } from '../src/scalars/BigInt.js'; +import { graphql, GraphQLSchema } from 'graphql'; +import { GraphQLInputObjectType, GraphQLNonNull, GraphQLObjectType } from 'graphql/type/definition'; import 'json-bigint-patch'; +import { GraphQLBigInt } from '../src/scalars/BigInt.js'; describe('BigInt', () => { const Query = new GraphQLObjectType({ @@ -35,7 +35,7 @@ describe('BigInt', () => { fields: { result: { type: new GraphQLNonNull(GraphQLBigInt) }, }, - }) + }), ), args: { input: { @@ -45,7 +45,7 @@ describe('BigInt', () => { fields: { num: { type: new GraphQLNonNull(GraphQLBigInt) }, }, - }) + }), ), }, }, @@ -99,11 +99,11 @@ describe('BigInt', () => { const { data, errors } = await graphql({ schema, source: validQuery }); expect(errors).toEqual(undefined); expect(data).toEqual({ - a: 2n, - b: 2147483647n, - c: 2147483648n, - d: 2147483649n, - e: 439857257821346n, + a: 2, + b: 2147483647, + c: 2147483648, + d: 2147483649, + e: 439857257821346, f: 9007199254740993n, }); }); @@ -115,9 +115,9 @@ describe('BigInt', () => { }); expect(errors).toEqual(undefined); expect(data).toEqual({ - a: { result: 2147483647n }, - b: { result: 9007199254740991n }, - d: { result: 2n }, + a: { result: 2147483647 }, + b: { result: 9007199254740991 }, + d: { result: 2 }, }); }); });