跳转至

Directives

A directive can be attached to a field or fragment inclusion, and can affect execution of the query in any way the server desires (read more here). The GraphQL specification provides several default directives:

  • @include(if: Boolean) - only include this field in the result if the argument is true
  • @skip(if: Boolean) - skip this field if the argument is true
  • @deprecated(reason: String) - marks field as deprecated with message

A directive is an identifier preceded by a @ character, optionally followed by a list of named arguments, which can appear after almost any element in the GraphQL query and schema languages.

Custom directives

To create a custom schema directive, declare a class which extends the SchemaDirectiveVisitor class exported from the @graphql-tools/utils package.

import { SchemaDirectiveVisitor } from '@graphql-tools/utils';
import { defaultFieldResolver, GraphQLField } from 'graphql';

export class UpperCaseDirective extends SchemaDirectiveVisitor {
  visitFieldDefinition(field: GraphQLField<any, any>) {
    const { resolve = defaultFieldResolver } = field;
    field.resolve = async function (...args) {
      const result = await resolve.apply(this, args);
      if (typeof result === 'string') {
        return result.toUpperCase();
      }
      return result;
    };
  }
}

Hint

Note that directives cannot be decorated with the @Injectable() decorator. Thus, they are not able to inject dependencies.

Warning

SchemaDirectiveVisitor is exported from the @graphql-tools/utils package. Note that the 8.x release of graphql-tools removes this export and provides a different and incompatible approach to directives, so make sure to install @graphql-tools/utils@^7 in your project.

Now, register the UpperCaseDirective in the GraphQLModule.forRoot() method:

1
2
3
4
5
6
GraphQLModule.forRoot({
  // ...
  schemaDirectives: {
    upper: UpperCaseDirective,
  },
});

Once registered, the @upper directive can be used in our schema. However, the way you apply the directive will vary depending on the approach you use (code first or schema first).

Code first

In the code first approach, use the @Directive() decorator to apply the directive.

1
2
3
@Directive('@upper')
@Field()
title: string;

Hint

The @Directive() decorator is exported from the @nestjs/graphql package.

Directives can be applied on fields, field resolvers, input and object types, as well as queries, mutations, and subscriptions. Here's an example of the directive applied on the query handler level:

1
2
3
4
5
@Directive('@deprecated(reason: "This query will be removed in the next version")')
@Query(returns => Author, { name: 'author' })
async getAuthor(@Args({ name: 'id', type: () => Int }) id: number) {
  return this.authorsService.findOneById(id);
}

Directives applied through the @Directive() decorator will not be reflected in the generated schema definition file.

Schema first

In the schema first approach, apply directives directly in SDL.

1
2
3
4
5
6
7
directive @upper on FIELD_DEFINITION

type Post {
  id: Int!
  title: String! @upper
  votes: Int
}