Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/horusgoul/nest-graphql-scalar-adapter

A better way to import external GraphQL scalars into your Nest.js projects.
https://github.com/horusgoul/nest-graphql-scalar-adapter

graphql nestjs nodejs typescript

Last synced: about 1 month ago
JSON representation

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

Awesome Lists containing this project

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!

```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.