简体   繁体   中英

How to use 'Decimal' as a field type in GraphQL schema?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM