企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 接口 像许多类型系统一样,GraphQL 支持接口。 接口是一种抽象类型,它包含一组特定的字段,类型必须包含这些字段才能实现接口(在[此处](https://graphql.org/learn/schema/#interfaces)阅读更多内容)。 ### 代码优先 当使用代码优先方式时,你可以通过创建一个带有 `@InterfaceType()` 装饰器注释的抽象类,来定义一个 GraphQL 接口,这个装饰器是从 `@nestjs/graphql` 包里导出。 ```typescript import { Field, ID, InterfaceType } from '@nestjs/graphql'; @InterfaceType() export abstract class Character { @Field(type => ID) id: string; @Field() name: string; } ``` > TypeScript 接口不能用来定义 GraphQL 接口。 最终的结果是在 SDL 中生成以下部分的 GraphQL schema: ```graphql interface Character { id: ID! name: String! } ``` 现在,使用 `implements` 关键字来实现 `Character` 这个接口: ```typescript @ObjectType({ implements: () => [Character], }) export class Human implements Character { id: string; name: string; } ``` > `@ObjectType()` 装饰器是从 `@nestjs/graphql` 包里导出。 默认的 `resolveType()` 函数是通过库根据解析器方法返回值提取的类型来生成的。这意味着你必须返回类的实例(你不能返回 JavaScript 对象字面量)。 提供自定义的 `resolveType()` 函数,将 `resolveType` 属性传递给 `@InterfaceType()` 装饰器里的选项对象,如下所示: ```typescript @InterfaceType({ resolveType(book) { if (book.colors) { return ColoringBook; } return TextBook; }, }) export abstract class Book { @Field(type => ID) id: string; @Field() title: string; } ``` ### 模式优先 在模式优先方式中定义接口,只需使用 SDL 创建一个 GraphQL 接口。 ```graphql interface Character { id: ID! name: String! } ``` 然后,你可以使用类型生成功能(如[快速开始](/8/graphql?id=快速开始)章节所示)生成相应的 TypeScript 定义。 ```typescript export interface Character { id: string; name: string; } ``` 在解析器映射图中,接口需要一个额外的 `__resolveType` 字段,来确定接口应该解析为哪个类型。让我们创建一个 `CharactersResolver` 类并定义 `__resolveType` 方法: ```typescript @Resolver('Character') export class CharactersResolver { @ResolveField() __resolveType(value) { if ('age' in value) { return Person; } return null; } } ``` > 所有装饰器都是从 `@nestjs/graphql` 包里导出。