nest-graphql-scalar-adapter

A better way to import external GraphQL scalars into your Nest.js projects.

Usage no npm install needed!

<script type="module">
  import nestGraphqlScalarAdapter from 'https://cdn.skypack.dev/nest-graphql-scalar-adapter';
</script>

README

Nest Logo

nest-graphql-scalar-adapter

NPM Version Package License GitHub Actions Coverage Nest.js Version Star the project Follow me on Twitter

Description

A better way to import external GraphQL scalars into your Nest.js projects.

npm i nest-graphql-scalar-adapter

# or

yarn add nest-graphql-scalar-adapter

How to use

We're going to use the graphql-type-json package that allows us to add the JSON scalar type in our GraphQL schema.

The only thing we need to do is wrap it with the createFromGraphQLScalar function!

import JSON from 'graphql-type-json';
import { createFromGraphQLScalar } from 'nest-graphql-scalar-adapter';

export const JSONScalar = createFromGraphQLScalar({ scalar: JSON });
//                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

We can also give it a custom name using the name option of the createFromGraphQLScalar configuration:

export const JSONScalar = createFromGraphQLScalar({
  scalar: JSON,
  name: 'JSONStatham',
});

And also a type, which is useful when you're using the Code First approach:

export const JSONScalar = createFromGraphQLScalar({
  scalar: JSON,
  name: 'JSONStatham',

  // The type that you would use with the `@Scalar` decorator.
  type: () => Object,
});

createFromGraphQLScalar returns a class that is already decorated with the @Scalar decorator. Thanks to this, we can register our scalars as providers:

...

@Module({
  providers: [JSONScalar]
})
export class MyModule {}

...

And the scalar is ready! If you're using the Schema First remember to add the scalar to your schema like this:

scalar JSON

~

What's the benefit of doing this instead of adding it to the GraphQLModule configuration?

This approach provides you a better way to add external scalars to your project, as it doesn't require you to define every single scalar in the resolvers configuration of the GraphQLModule, and instead allows you to register it as a provider in any module.