Skip to content
Advertisement

How can I handle long Int with GraphQL?

As you know that GraphQL has no data type like long int. So, whenever the number is something big like 10000000000, it throws an error like this: Int cannot represent non 32-bit signed integer value: 1000000000000

For that I know two solutions:

  1. Use scalars.
import { GraphQLScalarType } from 'graphql';
import { makeExecutableSchema } from '@graphql-tools/schema';

const myCustomScalarType = new GraphQLScalarType({
  name: 'MyCustomScalar',
  description: 'Description of my custom scalar type',
  serialize(value) {
    let result;
    return result;
  },
  parseValue(value) {
    let result;
    return result;
  },
  parseLiteral(ast) {
    switch (ast.kind) {
    }
  }
});

const schemaString = `

scalar MyCustomScalar

type Foo {
  aField: MyCustomScalar
}

type Query {
  foo: Foo
}

`;

const resolverFunctions = {
  MyCustomScalar: myCustomScalarType
};

const jsSchema = makeExecutableSchema({
  typeDefs: schemaString,
  resolvers: resolverFunctions,
});
  1. Use apollo-type-bigint package.

Both of those solutions convert the big int to string, and I’d rather not use string (I prefer a number type).

Advertisement

Answer

Correct, there’s no concept like bigInt in graphQL.

You can try one of these:

  1. Set type as Float instead of Int – it will handle all large int values and also send them as number [below are technically options, although you stated you don’t like string solutions]
  2. Set type as String, as you described
  3. Give (an npm-provided data type, like) BigInt, as you described. It will handle big int, but will convert your values into string

npm BigInt dependency with Graphql v16 support:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement