A better way to import external GraphQL scalars into your Nest.js projects.
npm install nest-graphql-scalar-adapterA better way to import external GraphQL scalars into your Nest.js projects.
``
npm i nest-graphql-scalar-adapter
yarn add nest-graphql-scalar-adapter
`
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!
`ts
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:
`ts`
export const JSONScalar = createFromGraphQLScalar({
scalar: JSON,
name: 'JSONStatham',
});
And also a type, which is useful when you're using the Code First approach:
`ts
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:
`ts
...
@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:
`graphql`
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.