Skip to content

Commit

Permalink
Do not parse BigInt values as BigInt if they are safe and BigInt is n…
Browse files Browse the repository at this point in the history
…ot serializable in the env
  • Loading branch information
ardatan committed Oct 9, 2023
1 parent 2ae307c commit 9029d0a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
5 changes: 5 additions & 0 deletions .changeset/warm-pets-yell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'graphql-scalars': patch
---

Parse BigInt as Number s if they are safe and BigInt is not serializable
31 changes: 22 additions & 9 deletions src/scalars/BigInt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,34 @@ import { serializeObject } from './utilities.js';

let warned = false;

function isSafeInteger(val: bigint): boolean {
function isSafeInteger(val: bigint | number): boolean {
return val <= Number.MAX_SAFE_INTEGER && val >= Number.MIN_SAFE_INTEGER;
}

function serializeSafeBigInt(val: bigint): bigint | number | string {
if (isSafeInteger(val)) {
return Number(val);
}
if ('toJSON' in BigInt.prototype) {
if (isBigIntSerializable()) {
return val;
}
if (!warned) {
warned = true;
console.warn(
'By default, BigInts are not serialized to JSON as numbers but instead as strings which may lead an unintegrity in your data. ' +
'To fix this, you can use "json-bigint-patch" to enable correct serialization for BigInts.',
);
}
return val.toString();
}

function isBigIntSerializable() {
if (!('toJSON' in BigInt.prototype)) {
if (!warned) {
warned = true;
console.warn(
'By default, BigInts are not serialized to JSON as numbers but instead as strings which may lead an unintegrity in your data. ' +
'To fix this, you can use "json-bigint-patch" to enable correct serialization for BigInts.',
);
}
return false;
}
return true;
}

export const GraphQLBigIntConfig: GraphQLScalarTypeConfig<
bigint | number,
bigint | string | number
Expand Down Expand Up @@ -73,6 +80,9 @@ export const GraphQLBigIntConfig: GraphQLScalarTypeConfig<
if (inputValue.toString() !== bigint.toString()) {
throw createGraphQLError(`BigInt cannot represent value: ${inputValue}`);
}
if (!isSafeInteger(bigint) && !isBigIntSerializable()) {
return Number(bigint.toString());
}
return bigint;
},
parseLiteral(valueNode) {
Expand All @@ -86,6 +96,9 @@ export const GraphQLBigIntConfig: GraphQLScalarTypeConfig<
if (strOrBooleanValue.toString() !== bigint.toString()) {
throw createGraphQLError(`BigInt cannot represent value: ${strOrBooleanValue}`);
}
if (!isSafeInteger(bigint) && !isBigIntSerializable()) {
return Number(bigint.toString());
}
return bigint;
},
extensions: {
Expand Down

0 comments on commit 9029d0a

Please sign in to comment.