From 67cddadd1e11b03d737529a2d3a57b560e637acf Mon Sep 17 00:00:00 2001 From: Ulf Gebhardt Date: Sun, 27 Feb 2022 02:07:33 +0100 Subject: [PATCH] graphql recognizes decimal type now and successfully starts --- backend/src/graphql/scalar/Decimal.ts | 26 ++++++++++++++++++++++++++ backend/src/graphql/schema.ts | 3 +++ 2 files changed, 29 insertions(+) create mode 100644 backend/src/graphql/scalar/Decimal.ts diff --git a/backend/src/graphql/scalar/Decimal.ts b/backend/src/graphql/scalar/Decimal.ts new file mode 100644 index 000000000..001596fb3 --- /dev/null +++ b/backend/src/graphql/scalar/Decimal.ts @@ -0,0 +1,26 @@ +import { GraphQLScalarType, Kind } from 'graphql' +import Decimal from 'decimal.js-light' + +export default new GraphQLScalarType({ + name: 'Decimal', + description: 'The `Decimal` scalar type to represent currency values', + + serialize(value: unknown) { + if (!(value instanceof Decimal)) { + throw new Error('DecimalScalar can only serialize Decimal values') + } + return value.toString() + }, + + parseValue(value) { + return new Decimal(value) + }, + + parseLiteral(ast) { + if (ast.kind !== Kind.STRING) { + throw new TypeError(`${String(ast)} is not a valid decimal value.`) + } + + return new Decimal(ast.value) + }, +}) diff --git a/backend/src/graphql/schema.ts b/backend/src/graphql/schema.ts index 02caf2784..97bd3b632 100644 --- a/backend/src/graphql/schema.ts +++ b/backend/src/graphql/schema.ts @@ -1,13 +1,16 @@ import { GraphQLSchema } from 'graphql' import { buildSchema } from 'type-graphql' +import Decimal from 'decimal.js-light' import path from 'path' import isAuthorized from './directive/isAuthorized' +import DecimalScalar from './scalar/Decimal' const schema = async (): Promise => { return buildSchema({ resolvers: [path.join(__dirname, 'resolver', `!(*.test).{js,ts}`)], authChecker: isAuthorized, + scalarsMap: [{ type: Decimal, scalar: DecimalScalar }], }) }