## 指令
一個指令可以被附加在一個字段或對象片段上,并能按照服務器所希望的任何方式影響查詢語句的執行(參見[此處](https://graphql.org/learn/queries/#directives))。GraphQL 規范中提供了幾個默認的指令:
- `@include(if: Boolean)` - 僅在參數為真時,才在結果中包含此字段
- `@skip(if: Boolean)` - 參數為真時,跳過此字段
- `@deprecated(reason: String)` - 標記此字段為已棄用,并附上原因
指令其實就是一個帶有 `@` 符號前綴的標識符,可選項為后面緊跟著的命名參數列表,它可以出現在 GraphQL 查詢和模式語言中的幾乎任何元素之后。
### 自定義指令
要指示當 Apollo/Mercurius 遇到您的指令時應該發生什么,您可以創建一個轉換器函數。 此函數使用 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;
// Replace the original resolver with a function that *first* calls
// the original resolver, then converts its result to upper case
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;
}
},
});
}
~~~
現在,使用 `transformSchema` 函數在 `GraphQLModule#forRoot` 方法中應用 `upperDirectiveTransformer` 轉換函數:
~~~typescript
GraphQLModule.forRoot({
// ...
transformSchema: (schema) => upperDirectiveTransformer(schema, 'upper'),
});
~~~
一旦注冊,`@upper` 指令就可以在我們的模式中使用。 但是,您應用指令的方式將根據您使用的方法(代碼優先或模式優先)而有所不同。
### 代碼優先
在代碼優先方式中,使用 `@Directive()` 裝飾器來應用指令。
```typescript
@Directive('@upper')
@Field()
title: string;
```
> `@Directive()` 裝飾器是從 `@nestjs/graphql` 包里導出的。
指令可以被應用在字段、字段解析器、輸入和對象類型上,同樣也可以應用在查詢、變更和訂閱上。這里有一個將指令應用于查詢處理層的例子:
```typescript
@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);
}
```
通過 `@Directive()` 裝飾器所應用的指令,將不會被映射在生成的模式定義文件中。
最后,確保在 GraphQLModule 中聲明指令,如下所示:
~~~typescript
GraphQLModule.forRoot({
// ...,
transformSchema: schema => upperDirectiveTransformer(schema, 'upper'),
buildSchemaOptions: {
directives: [
new GraphQLDirective({
name: 'upper',
locations: [DirectiveLocation.FIELD_DEFINITION],
}),
],
},
}),
~~~
`GraphQLDirective` 和 `DirectiveLocation` 都是從 `graphql` 包中導出的。
### 架構優先
在架構優先方式中,直接在 SDL 中應用指令。
```graphql
directive @upper on FIELD_DEFINITION
type Post {
id: Int!
title: String! @upper
votes: Int
}
```
- 介紹
- 概述
- 第一步
- 控制器
- 提供者
- 模塊
- 中間件
- 異常過濾器
- 管道
- 守衛
- 攔截器
- 自定義裝飾器
- 基礎知識
- 自定義提供者
- 異步提供者
- 動態模塊
- 注入作用域
- 循環依賴
- 模塊參考
- 懶加載模塊
- 應用上下文
- 生命周期事件
- 跨平臺
- 測試
- 技術
- 數據庫
- Mongo
- 配置
- 驗證
- 緩存
- 序列化
- 版本控制
- 定時任務
- 隊列
- 日志
- Cookies
- 事件
- 壓縮
- 文件上傳
- 流式處理文件
- HTTP模塊
- Session(會話)
- MVC
- 性能(Fastify)
- 服務器端事件發送
- 安全
- 認證(Authentication)
- 授權(Authorization)
- 加密和散列
- Helmet
- CORS(跨域請求)
- CSRF保護
- 限速
- GraphQL
- 快速開始
- 解析器(resolvers)
- 變更(Mutations)
- 訂閱(Subscriptions)
- 標量(Scalars)
- 指令(directives)
- 接口(Interfaces)
- 聯合類型
- 枚舉(Enums)
- 字段中間件
- 映射類型
- 插件
- 復雜性
- 擴展
- CLI插件
- 生成SDL
- 其他功能
- 聯合服務
- 遷移指南
- Websocket
- 網關
- 異常過濾器
- 管道
- 守衛
- 攔截器
- 適配器
- 微服務
- 概述
- Redis
- MQTT
- NATS
- RabbitMQ
- Kafka
- gRPC
- 自定義傳輸器
- 異常過濾器
- 管道
- 守衛
- 攔截器
- 獨立應用
- Cli
- 概述
- 工作空間
- 庫
- 用法
- 腳本
- Openapi
- 介紹
- 類型和參數
- 操作
- 安全
- 映射類型
- 裝飾器
- CLI插件
- 其他特性
- 遷移指南
- 秘籍
- CRUD 生成器
- 熱重載
- MikroORM
- TypeORM
- Mongoose
- 序列化
- 路由模塊
- Swagger
- 健康檢查
- CQRS
- 文檔
- Prisma
- 靜態服務
- Nest Commander
- 問答
- Serverless
- HTTP 適配器
- 全局路由前綴
- 混合應用
- HTTPS 和多服務器
- 請求生命周期
- 常見錯誤
- 實例
- 遷移指南
- 發現
- 誰在使用Nest?