Skip to content

Commit

Permalink
enhance(bigint): serialize as numbers if possible
Browse files Browse the repository at this point in the history
  • Loading branch information
ardatan committed Jun 7, 2023
1 parent 4e17baf commit b6d930f
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 16 deletions.
5 changes: 5 additions & 0 deletions .changeset/great-seahorses-switch.md
@@ -0,0 +1,5 @@
---
'graphql-scalars': patch
---

Serialize bigints as numbers if possible
6 changes: 3 additions & 3 deletions src/scalars/BigInt.ts
Expand Up @@ -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(
Expand Down
26 changes: 13 additions & 13 deletions 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({
Expand Down Expand Up @@ -35,7 +35,7 @@ describe('BigInt', () => {
fields: {
result: { type: new GraphQLNonNull(GraphQLBigInt) },
},
})
}),
),
args: {
input: {
Expand All @@ -45,7 +45,7 @@ describe('BigInt', () => {
fields: {
num: { type: new GraphQLNonNull(GraphQLBigInt) },
},
})
}),
),
},
},
Expand Down Expand Up @@ -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,
});
});
Expand All @@ -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 },
});
});
});

0 comments on commit b6d930f

Please sign in to comment.