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 }], }) }