# 指令

来源：https://docs.nestjs.com/graphql/directives

指令可以附加到字段或片段包含（fragment inclusion）上，并能以服务器期望的任何方式影响查询的执行（参见 GraphQL 文档中的[指令](https://graphql.org/learn/queries/#directives)）。GraphQL 规范提供了若干默认指令：

- `@include(if: Boolean)`：仅当该参数为 `true` 时，才把此字段包含在结果中
- `@skip(if: Boolean)`：当该参数为 `true` 时跳过此字段
- `@deprecated(reason: String)`：把该字段标记为已废弃，并附上一条说明

指令是一个前面带 `@` 字符的标识符，其后可以选择性地跟一组具名参数。在 GraphQL 的查询语言与模式语言（schema language）中，几乎任何元素之后都可以出现指令。

#### 自定义指令

要定义 Apollo 或 Mercurius 遇到你的指令时会发生什么，请创建一个转换器函数（transformer function）。该函数使用 `mapSchema` 函数遍历模式中的各个位置（字段定义、类型定义等），并施加相应的变换。

```typescript
import { getDirective, MapperKind, mapSchema } from '@graphql-tools/utils';
import { defaultFieldResolver, GraphQLSchema } from 'graphql';

export function upperDirectiveTransformer(
  schema: GraphQLSchema,
  directiveName: string,
) {
  return mapSchema(schema, {
    [MapperKind.OBJECT_FIELD]: (fieldConfig) => {
      const upperDirective = getDirective(
        schema,
        fieldConfig,
        directiveName,
      )?.[0];

      if (upperDirective) {
        const { resolve = defaultFieldResolver } = fieldConfig;

        // 用一个函数替换原来的解析器：该函数 *先* 调用原解析器，
        // 再把其结果转换为大写
        fieldConfig.resolve = async function (source, args, context, info) {
          const result = await resolve(source, args, context, info);
          if (typeof result === 'string') {
            return result.toUpperCase();
          }
          return result;
        };
        return fieldConfig;
      }
    },
  });
}
```

接下来，在 `GraphQLModule#forRoot()` 方法中通过 `transformSchema` 选项应用 `upperDirectiveTransformer` 函数：

```typescript
GraphQLModule.forRoot({
  // ...
  transformSchema: (schema) => upperDirectiveTransformer(schema, 'upper'),
});
```

注册之后，就可以在模式中使用 `@upper` 指令了。如何应用该指令取决于你采用的方式（代码优先还是模式优先）。

#### 代码优先

在代码优先方式中，使用 `@Directive()` 装饰器来应用指令：

```typescript
@Directive('@upper')
@Field()
title: string;
```

> info **提示** `@Directive()` 装饰器由 `@nestjs/graphql` 包导出。

指令既可以应用于字段、字段解析器、输入类型和对象类型，也可以应用于查询、变更和订阅。下面的示例在查询处理器这一层应用指令：

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

> warning **警告** 通过 `@Directive()` 装饰器应用的指令不会反映在生成的模式定义文件中。

最后，在 `GraphQLModule` 配置中声明这些指令：

```typescript
GraphQLModule.forRoot({
  // ...,
  transformSchema: schema => upperDirectiveTransformer(schema, 'upper'),
  buildSchemaOptions: {
    directives: [
      new GraphQLDirective({
        name: 'upper',
        locations: [DirectiveLocation.FIELD_DEFINITION],
      }),
    ],
  },
}),
```

> info **提示** `GraphQLDirective` 与 `DirectiveLocation` 都由 `graphql` 包导出。

#### 模式优先

在模式优先方式中，直接在 SDL 中应用指令：

```graphql
directive @upper on FIELD_DEFINITION

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