typescriptgraphqltypegraphql

How can I use the `graphql-scalars` package with `typegraphql`?


I would like to make use of the graphql-scalars package of the-guild.dev. However, I don't understand how I can integrate it with typegraphql. This is their quick start guide https://the-guild.dev/graphql/scalars/docs/quick-start which I will paste the main parts below:

//schema.graphql
scalar ScalarName

You can also import ready-to-use type definitions for scalars like below

// or import specific typeDefs only with ES6 Import
import { ScalarNameTypeDefinition } from 'graphql-scalars';
// or import all typeDefs once with ES6 Import
import { typeDefs as scalarTypeDefs } from 'graphql-scalars';

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

You can either import the specific scalar's resolvers or all of the resolvers once.

// or import specific resolvers only with ES6 Import
import { ScalarNameResolver } from 'graphql-scalars';
// or import all resolvers once with ES6 Import
import { resolvers as scalarResolvers } from 'graphql-scalars';

Adding to the Root Resolver Map

const myResolverMap = {
  ScalarName: ScalarNameResolver,
 
  Query: {
    // more stuff here
  },
 
  Mutation: {
    // more stuff here
  },
};

How can I adapt this logic to use it with typegraphql?


Solution

  • Since most of the scalars from graphql-scalars library are mapped to primitive types (number, string, boolean) you cannot use scalarsMap (automatically infer the association between the reflected property type and the scalar, no need for explicit type annotation).
    Therefore, whenever you want to use a custom scalar, you must explicitly use the type annotation (note that this is valid also for basic GraphQL scalars):

    import { GraphQLID } from 'graphql';
    import { GraphQLTimestamp, GraphQLNonEmptyString } from 'graphql-scalars';
    
    @ObjectType()
    class MyObj {
      // GraphQL scalar
      @Field(() => GraphQLID)
      id!: string
    
      // graphql-scalars scalar
      @Field(() => GraphQLTimestamp)
      createdAt!: Date;
    }
    
    @Resolver(MyObj)
    class MyObjResolver {
      // graphql-scalars scalar
      hello(@Arg('name', () => GraphQLNonEmptyString) name: string) {
        return `Hello ${name}!`;
      }
    }
    
    /* ... */
    

    See example