11

I want to use Decimal as a type for latitude & longitude field in my GraphGL schema. But GraphQL provides only Float and Int. Is there is any package to solve this?

Debotos Das
  • 519
  • 1
  • 6
  • 17
  • Hi and welcome to SO! Generally, questions asking for library recommendations are off-topic for SO. You could edit your question and ask how to write such a scalar yourself. That would be more appropriate for this site. However, it's also not totally clear what data you're trying to represent with such a scalar. Are you specifically targeting a database type, like postgres' decimal type? What are your requirements for this scalar? – Daniel Rearden Jul 18 '19 at 12:14
  • Hey, Thanks for the reply. I updated the question. – Debotos Das Jul 18 '19 at 17:27
  • Why would Float not satisfy your requirement? You have tagged node.js so the value would be handled as a Number, which is a 64 bit floating type? – Glen Thomas Jul 22 '19 at 14:33
  • Okay! Thanks for the confirmation. I thought that if there anything specific for Decimal. – Debotos Das Jul 23 '19 at 10:02
  • I guess it depends on context. For example, a FLOAT/DOUBLE and a DECIMAL are definitely NOT the same in MySQL, a DECIMAL is not finite precision, it is an exact representation of a decimal number. See [this](https://dev.mysql.com/doc/refman/5.7/en/precision-math-decimal-characteristics.html). In fact, support for the Decimal type in python was added to the Graphene library, see [this PR](https://github.com/graphql-python/graphene/issues/703) – Alex Oct 22 '19 at 20:10

1 Answers1

3

I looked at the source code for this module can came up with this:




///  I M P O R T

import Big from "big.js";
import { GraphQLScalarType, Kind } from "graphql";



///  E X P O R T

export default new GraphQLScalarType({
  name: "Decimal",
  description: "The `Decimal` scalar type to represent currency values",

  serialize(value) {
    return new Big(value);
  },

  parseLiteral(ast) {
    if (ast.kind !== Kind.STRING) {
      // @ts-ignore | TS2339
      throw new TypeError(`${String(ast.value)} is not a valid decimal value.`);
    }

    return Big(ast.value);
  },

  parseValue(value) {
    return Big(value);
  }
});

Then, I add the reference to my resolver so I can just add Decimal to my SDL code.

NetOperator Wibby
  • 1,354
  • 5
  • 22
  • 44