Skip to content

Commit b6d930f

Browse files
committed
enhance(bigint): serialize as numbers if possible
1 parent 4e17baf commit b6d930f

File tree

3 files changed

+21
-16
lines changed

3 files changed

+21
-16
lines changed

.changeset/great-seahorses-switch.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'graphql-scalars': patch
3+
---
4+
5+
Serialize bigints as numbers if possible

src/scalars/BigInt.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@ function isSafeInteger(val: bigint): boolean {
1010
}
1111

1212
function serializeSafeBigInt(val: bigint): bigint | number | string {
13-
if ('toJSON' in BigInt.prototype) {
14-
return val;
15-
}
1613
if (isSafeInteger(val)) {
1714
return Number(val);
1815
}
16+
if ('toJSON' in BigInt.prototype) {
17+
return val;
18+
}
1919
if (!warned) {
2020
warned = true;
2121
console.warn(

tests/BigInt.test.ts

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import { GraphQLObjectType, GraphQLNonNull, GraphQLInputObjectType } from 'graphql/type/definition';
2-
import { GraphQLSchema, graphql } from 'graphql';
3-
import { GraphQLBigInt } from '../src/scalars/BigInt.js';
1+
import { graphql, GraphQLSchema } from 'graphql';
2+
import { GraphQLInputObjectType, GraphQLNonNull, GraphQLObjectType } from 'graphql/type/definition';
43
import 'json-bigint-patch';
4+
import { GraphQLBigInt } from '../src/scalars/BigInt.js';
55

66
describe('BigInt', () => {
77
const Query = new GraphQLObjectType({
@@ -35,7 +35,7 @@ describe('BigInt', () => {
3535
fields: {
3636
result: { type: new GraphQLNonNull(GraphQLBigInt) },
3737
},
38-
})
38+
}),
3939
),
4040
args: {
4141
input: {
@@ -45,7 +45,7 @@ describe('BigInt', () => {
4545
fields: {
4646
num: { type: new GraphQLNonNull(GraphQLBigInt) },
4747
},
48-
})
48+
}),
4949
),
5050
},
5151
},
@@ -99,11 +99,11 @@ describe('BigInt', () => {
9999
const { data, errors } = await graphql({ schema, source: validQuery });
100100
expect(errors).toEqual(undefined);
101101
expect(data).toEqual({
102-
a: 2n,
103-
b: 2147483647n,
104-
c: 2147483648n,
105-
d: 2147483649n,
106-
e: 439857257821346n,
102+
a: 2,
103+
b: 2147483647,
104+
c: 2147483648,
105+
d: 2147483649,
106+
e: 439857257821346,
107107
f: 9007199254740993n,
108108
});
109109
});
@@ -115,9 +115,9 @@ describe('BigInt', () => {
115115
});
116116
expect(errors).toEqual(undefined);
117117
expect(data).toEqual({
118-
a: { result: 2147483647n },
119-
b: { result: 9007199254740991n },
120-
d: { result: 2n },
118+
a: { result: 2147483647 },
119+
b: { result: 9007199254740991 },
120+
d: { result: 2 },
121121
});
122122
});
123123
});

0 commit comments

Comments
 (0)