apollographql / apollo-link

:link: Interface for fetching and modifying control flow of GraphQL requests
https://www.apollographql.com/docs/link/
MIT License
1.44k stars 344 forks source link

BigINT json parsing #924

Open sulliwane opened 5 years ago

sulliwane commented 5 years ago

Hello,

the JSON parser used to parse gql query returns will truncate all JSON integers that are higher than Number.MAX_SAFE_INTEGER (9007199254740991).

My question: Is it possible to switch the default JSON parser for one that would support Big Integer (like this one => https://github.com/sidorares/json-bigint, that's using this kind of library => https://github.com/indutny/bn.js/).

If not, should I deduce that storing a string in the database is the only workaround?

Many thanks for your help!

JoviDeCroock commented 5 years ago

I think it's quite hard to integrate a custom JSON parser in the frontend, big int isn't widely supported afaik

helfer commented 5 years ago

Rather than storing strings in the DB, I would recommend a custom serialize function for your BigInt or Long scalar (which you already need anyway if you're using graphql-js). That serialize function should return a string instead of a number. If the UI is the only client of your API and if you're not doing arithmetic with these numbers on the frontend, that solution should be sufficient. If you have other consumers of the API that can parse BigInts in JSON, or if you're doing arithmetic in JS with the BigInts, then having the ability to use a custom JSON parser would indeed be nice.

Since it isn't configurable on the http-link at the moment, you could try monkey-patching it as a last resort (JSON.parse = JSONBig.parse). I wouldn't recommend doing that, but sometimes you have to pick the lesser of two evils.