## 聯合類型
聯合類型與接口非常相似,但是它們沒有指定類型之間的任何公共字段(詳情請參閱[這里](https://graphql.org/learn/schema/#union-types))。聯合類型對于單個字段返回不相交的數據類型很有用。
### 代碼優先
要定義 GraphQL 聯合類型,我們必須先定義組成這個聯合類型的各個類。遵循 Apollo 文檔中的[示例](https://www.apollographql.com/docs/apollo-server/schema/unions-interfaces/#union-type),我們將創建兩個類。首先,`Book`:
```typescript
import { Field, ObjectType } from '@nestjs/graphql';
@ObjectType()
export class Book {
@Field()
title: string;
}
```
然后是 `Author`:
```typescript
import { Field, ObjectType } from '@nestjs/graphql';
@ObjectType()
export class Author {
@Field()
name: string;
}
```
在這里,我們使用從 `@nestjs/graphql` 包里導出的 `createUnionType` 函數來注冊 `ResultUnion` 這個聯合類型。
~~~typescript
export const ResultUnion = createUnionType({
name: 'ResultUnion',
types: () => [Author, Book] as const,
});
~~~
> `createUnionType` 函數的 types 屬性返回的數組應該被賦予一個 `const `斷言。 如果沒有給出 `const` 斷言,編譯時會生成錯誤的聲明文件,從另一個項目中使用時會出錯。
現在,我們就可以在查詢中引用 `ResultUnion` 這個聯合類型來。
```typescript
@Query(returns => [ResultUnion])
search(): Array<typeof ResultUnion> {
return [new Author(), new Book()];
}
```
最終的結果是在 SDL 中生成以下部分的 GraphQL schema:
```graphql
type Author {
name: String!
}
type Book {
title: String!
}
union ResultUnion = Author | Book
type Query {
search: [ResultUnion!]!
}
```
默認的 `resolveType()` 函數是通過庫根據解析器方法返回值提取的類型來生成的。這意味著你必須返回類的實例(你不能返回 JavaScript 對象字面量)。
提供自定義的 `resolveType()` 函數,將 `resolveType` 屬性傳遞給 `@InterfaceType()` 裝飾器里的選項對象,如下所示:
```typescript
export const ResultUnion = createUnionType({
name: 'ResultUnion',
types: () => [Author, Book],
resolveType(value) {
if (value.name) {
return Author;
}
if (value.title) {
return Book;
}
return null;
},
});
```
### 模式優先
在模式優先方式中定義聯合類型,只需使用 SDL 創建一個 GraphQL 聯合類型。
```graphql
type Author {
name: String!
}
type Book {
title: String!
}
union ResultUnion = Author | Book
```
然后,你可以使用類型生成功能(如[快速開始](/8/graphql?id=快速開始)章節所示)生成相應的 TypeScript 定義。
```typescript
export class Author {
name: string;
}
export class Book {
title: string;
}
export type ResultUnion = Author | Book;
```
在解析器映射圖中,聯合類型需要一個額外的 `__resolveType` 字段,來確定聯合類型應該解析為哪個類型。另外,請注意, `ResultUnionResolver` 這個類在任何模塊中都必須被注冊為提供者。讓我們創建一個 `ResultUnionResolver` 類并定義 `__resolveType` 方法:
```typescript
@Resolver('ResultUnion')
export class ResultUnionResolver {
@ResolveField()
__resolveType(value) {
if (value.name) {
return 'Author';
}
if (value.title) {
return 'Book';
}
return null;
}
}
```
> 所有裝飾器都是從 `@nestjs/graphql` 包里導出。
- 介紹
- 概述
- 第一步
- 控制器
- 提供者
- 模塊
- 中間件
- 異常過濾器
- 管道
- 守衛
- 攔截器
- 自定義裝飾器
- 基礎知識
- 自定義提供者
- 異步提供者
- 動態模塊
- 注入作用域
- 循環依賴
- 模塊參考
- 懶加載模塊
- 應用上下文
- 生命周期事件
- 跨平臺
- 測試
- 技術
- 數據庫
- 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?