💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 联合类型 联合类型与接口非常相似,但是它们没有指定类型之间的任何公共字段(详情请参阅[这里](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` 包里导出。