Skip to content

Commit 9029d0a

Browse files
committed
Do not parse BigInt values as BigInt if they are safe and BigInt is not serializable in the env
1 parent 2ae307c commit 9029d0a

File tree

2 files changed

+27
-9
lines changed

2 files changed

+27
-9
lines changed

.changeset/warm-pets-yell.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+
Parse BigInt as Number s if they are safe and BigInt is not serializable

src/scalars/BigInt.ts

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,27 +5,34 @@ import { serializeObject } from './utilities.js';
55

66
let warned = false;
77

8-
function isSafeInteger(val: bigint): boolean {
8+
function isSafeInteger(val: bigint | number): boolean {
99
return val <= Number.MAX_SAFE_INTEGER && val >= Number.MIN_SAFE_INTEGER;
1010
}
1111

1212
function serializeSafeBigInt(val: bigint): bigint | number | string {
1313
if (isSafeInteger(val)) {
1414
return Number(val);
1515
}
16-
if ('toJSON' in BigInt.prototype) {
16+
if (isBigIntSerializable()) {
1717
return val;
1818
}
19-
if (!warned) {
20-
warned = true;
21-
console.warn(
22-
'By default, BigInts are not serialized to JSON as numbers but instead as strings which may lead an unintegrity in your data. ' +
23-
'To fix this, you can use "json-bigint-patch" to enable correct serialization for BigInts.',
24-
);
25-
}
2619
return val.toString();
2720
}
2821

22+
function isBigIntSerializable() {
23+
if (!('toJSON' in BigInt.prototype)) {
24+
if (!warned) {
25+
warned = true;
26+
console.warn(
27+
'By default, BigInts are not serialized to JSON as numbers but instead as strings which may lead an unintegrity in your data. ' +
28+
'To fix this, you can use "json-bigint-patch" to enable correct serialization for BigInts.',
29+
);
30+
}
31+
return false;
32+
}
33+
return true;
34+
}
35+
2936
export const GraphQLBigIntConfig: GraphQLScalarTypeConfig<
3037
bigint | number,
3138
bigint | string | number
@@ -73,6 +80,9 @@ export const GraphQLBigIntConfig: GraphQLScalarTypeConfig<
7380
if (inputValue.toString() !== bigint.toString()) {
7481
throw createGraphQLError(`BigInt cannot represent value: ${inputValue}`);
7582
}
83+
if (!isSafeInteger(bigint) && !isBigIntSerializable()) {
84+
return Number(bigint.toString());
85+
}
7686
return bigint;
7787
},
7888
parseLiteral(valueNode) {
@@ -86,6 +96,9 @@ export const GraphQLBigIntConfig: GraphQLScalarTypeConfig<
8696
if (strOrBooleanValue.toString() !== bigint.toString()) {
8797
throw createGraphQLError(`BigInt cannot represent value: ${strOrBooleanValue}`);
8898
}
99+
if (!isSafeInteger(bigint) && !isBigIntSerializable()) {
100+
return Number(bigint.toString());
101+
}
89102
return bigint;
90103
},
91104
extensions: {

0 commit comments

Comments
 (0)