Amos Tan
Amos Tan

Reputation: 41

How to create custom graphql scalars on Nestjs? Graphql Scalars

I am implementing a framework using Nestjs on Apollo Server using GraphQL and I would like to use some custom GraphQL scalars. I found this site, https://www.graphql-scalars.dev/docs/quick-start, which is helpful for importing custom scalars without actually implementing them as written on https://docs.nestjs.com/graphql/scalars#create-a-custom-scalar. To be specific, I would like to use BigInt, Time, and URL.

From the docs on the quick start page, I am uncertain where the code belongs at. Should I code this at app.module.ts?


// or import specific typeDefs only with ES6 Import
import { ScalarNameTypeDefinition } from 'graphql-scalars';
// or import specific typeDefs only with CommonJS
const { ScalarNameTypeDefinition } = require('graphql-scalars');
// or import all typeDefs once with ES6 Import
import { typeDefs as scalarTypeDefs } from 'graphql-scalars';
// or import all typeDefs once with CommonJS
const { typeDefs: scalarTypeDefs } = require('graphql-scalars');

const typeDefs = [
  ...scalarTypeDefs,
  // other typeDefs
];
// or
const typeDefs = [
  ScalarNameTypeDefinition,
  // other typeDefs
];

my current GraphQLModule:

GraphQLModule.forRoot<ApolloDriverConfig>({
  driver: ApolloDriver,
  typePaths: ['./**/**/**/*.graphql'],
  definitions: {
    path: join(process.cwd(), 'src/graphql.ts'),
    outputAs: 'class',
  },  
}),

How about the resolver map? Where should the code belong at? assets.resolver.ts? I also don't understand where this code belongs to?

In short, how to use graphql-scalars package in the Nestjs framework on Apollo Server? Is there any open-source GitHub repository to look into?

Upvotes: 0

Views: 3041

Answers (1)

Andy
Andy

Reputation: 33

Have a look here NestJs Import a custom scalar

This is how my app.module.ts looks:

import { BigIntResolver, DateResolver, DateTimeResolver } from 'graphql-scalars';

GraphQLModule.forRoot<ApolloDriverConfig>({
  driver: ApolloDriver,
  typePaths: ['./**/*.graphql'],
  definitions: {
    path: join(process.cwd(), 'src/graphql/graphql-types.ts'),
    customScalarTypeMapping: {
      BigInt: 'bigint',
      DateTime: 'Date',
    },
  },
  resolvers: {
    BigInt: BigIntResolver,
    Date: DateResolver,
    DateTime: DateTimeResolver,
  },
  playground: true,
  debug: true,
}),

In my .graphql file I can then use those types:

scalar BigInt
scalar Date
scalar DateTime

input WorkperiodContent {
  editedAt: DateTime
  startDate: Date
  endDate: Date
}

After I did this I could successfully run queries on the GraphQL Playground using those new scalars.

You don't even need to create your own custom scalar. You can just import the three that you need and you are good to go.

Upvotes: 3

Related Questions