# 解析器

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

解析器提供了把一次 [GraphQL](https://graphql.org/) 操作（查询、变更或订阅）转换为数据的处理指令。它返回的数据形状与模式中指定的形状一致，既可以同步返回，也可以返回一个解析为该形状结果的 promise。通常，你需要手动创建**解析器映射**（resolver map）。而 `@nestjs/graphql` 包则会根据你用来标注类的装饰器所提供的元数据，自动生成解析器映射。为演示如何用该包创建 GraphQL API，我们将构建一个简单的作者 API。

#### 代码优先

在代码优先方式中，你不必用 SDL 手写 GraphQL 模式。你改用 TypeScript 装饰器，从 TypeScript 类定义生成 SDL。`@nestjs/graphql` 包读取通过装饰器定义的元数据，并为你生成模式。

#### 对象类型

GraphQL 模式中的大多数定义都是**对象类型**。你定义的每个对象类型都应当表示应用客户端可能需要交互的领域对象。例如，我们的示例 API 需要获取作者列表及其文章，因此我们定义一个 `Author` 类型和一个 `Post` 类型。

采用模式优先方式时，你会像下面这样在 SDL 中定义 `Author` 类型：

```graphql
type Author {
  id: Int!
  firstName: String
  lastName: String
  posts: [Post!]!
}
```

采用代码优先方式时，你用 TypeScript 类定义模式，并用 TypeScript 装饰器标注其字段。上面那段 SDL 在代码优先方式下的等价写法是：

```typescript
@@filename(authors/models/author.model)
import { Field, Int, ObjectType } from '@nestjs/graphql';
import { Post } from '../../posts/models/post.model.js';

@ObjectType()
export class Author {
  @Field(type => Int)
  id: number;

  @Field({ nullable: true })
  firstName?: string;

  @Field({ nullable: true })
  lastName?: string;

  @Field(type => [Post])
  posts: Post[];
}
```

> info **提示** TypeScript 的元数据反射系统存在若干限制。例如，它无法确定一个类由哪些属性组成，也无法确定某个属性是可选的还是必需的。正因这些限制，你必须要么在模式定义类中使用 `@Field()` 装饰器，为每个字段提供其 GraphQL 类型与可选性元数据；要么使用 [CLI 插件](/graphql/cli-plugin)为你生成这些元数据。

`Author` 对象类型和任何类一样，由一组字段构成，每个字段都声明了一个类型。字段的类型对应一种 [GraphQL 类型](https://graphql.org/learn/schema/)，它可以是另一个对象类型，也可以是标量类型。GraphQL 标量类型是一种解析为单个值的原始类型（如 `ID`、`String`、`Boolean` 或 `Int`）。

> info **提示** 除了 GraphQL 内置的标量类型，你还可以定义[自定义标量类型](/graphql/scalars)。

上面的 `Author` 对象类型定义会让 Nest **生成**前面展示的那段 SDL：

```graphql
type Author {
  id: Int!
  firstName: String
  lastName: String
  posts: [Post!]!
}
```

`@Field()` 装饰器接受一个可选的类型函数（如 `type => Int`），还可选地接受一个选项对象。

当 TypeScript 类型系统与 GraphQL 类型系统之间的映射存在歧义时，就必须提供类型函数。具体来说，`string` 与 `boolean` 类型**不需要**它，而 `number` 则**需要**它，因为 `number` 既可能映射为 GraphQL 的 `Int`，也可能映射为 `Float`（不提供类型函数时，`number` 默认映射为 `Float`）。类型函数返回你期望的 GraphQL 类型，正如这几章中各处示例所示。

选项对象可以包含以下任意键值对：

- `nullable`：字段是否可为 null（在 `@nestjs/graphql` 中，每个字段默认不可为 null）；`boolean`
- `description`：字段描述；`string`
- `deprecationReason`：把字段标记为已废弃；`string`

例如：

```typescript
@Field({ description: `Book title`, deprecationReason: 'Not useful in v2 schema' })
title: string;
```

> info **提示** 你还可以为整个对象类型添加描述或把它标记为废弃：`@ObjectType({{ '{' }} description: 'Author model' {{ '}' }})`。同样，如果你的应用提供[多个 GraphQL 端点](/graphql/quick-start#multiple-endpoints)，你可以把某个类型限定到特定模块：`@ObjectType({{ '{' }} registerIn: () => AuthorsModule {{ '}' }})`。

当字段是数组时，你必须在 `@Field()` 装饰器的类型函数中指明数组类型，如下所示：

```typescript
@Field(type => [Post])
posts: Post[];
```

> info **提示** 数组方括号写法（`[ ]`）表示数组的嵌套深度。例如，`[[Int]]` 表示一个整数矩阵。

要声明数组的元素（而非数组本身）可为 null，请把 `nullable` 属性设为 `'items'`，如下所示：

```typescript
@Field(type => [Post], { nullable: 'items' })
posts: Post[];
```

> info **提示** 如果数组及其元素都允许为 null，则把 `nullable` 设为 `'itemsAndList'`。

`Author` 对象类型就绪后，接着定义 `Post` 对象类型。

```typescript
@@filename(posts/models/post.model)
import { Field, Int, ObjectType } from '@nestjs/graphql';

@ObjectType()
export class Post {
  @Field(type => Int)
  id: number;

  @Field()
  title: string;

  @Field(type => Int, { nullable: true })
  votes?: number;
}
```

`Post` 对象类型会生成 GraphQL 模式中如下这段 SDL：

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

#### 代码优先的解析器

至此，我们已经定义了数据图中可以存在的对象（类型定义），但客户端还没有与它们交互的途径。为此，我们需要一个解析器类。在代码优先方式中，解析器类既定义解析器函数，**也**生成 **Query 类型**。下面的示例展示了具体做法：

```typescript
@@filename(authors/authors.resolver)
@Resolver(() => Author)
export class AuthorsResolver {
  constructor(
    private authorsService: AuthorsService,
    private postsService: PostsService,
  ) {}

  @Query(() => Author)
  async author(@Args('id', { type: () => Int }) id: number) {
    return this.authorsService.findOneById(id);
  }

  @ResolveField()
  async posts(@Parent() author: Author) {
    const { id } = author;
    return this.postsService.findAll({ authorId: id });
  }
}
```

> info **提示** 所有装饰器（如 `@Resolver`、`@ResolveField`、`@Args` 等）都从 `@nestjs/graphql` 包导出。

你可以定义多个解析器类，Nest 会在运行时把它们合并起来。有关代码组织的更多内容，请参见下文的[模块](/graphql/resolvers#module)小节。

> warning **注意** `AuthorsService` 与 `PostsService` 类中的逻辑可以随需要而定，简单或复杂皆可。本示例的重点是展示如何构建解析器，以及它们如何与其他提供者交互。

上面的 `AuthorsResolver` 定义了一个查询解析器函数和一个字段解析器函数。要创建解析器，请创建一个以解析器函数为方法的类，并用 `@Resolver()` 装饰器标注该类。

`author()` 方法是一个查询处理器，它返回请求中所发送 `id` 对应的作者对象。要把某个方法标记为查询处理器，请使用 `@Query()` 装饰器。

传给 `@Resolver()` 装饰器的参数是可选的，但当你的图变得不再简单时它就会派上用场：它为字段解析器函数在对象图中逐层向下遍历时提供父对象。

由于这个类包含**字段解析器**函数（针对 `Author` 对象类型的 `posts` 属性），你**必须**给 `@Resolver()` 装饰器传入一个值，指明该类内定义的所有字段解析器的父类型（即对应的 `ObjectType` 类）。字段解析器需要访问父对象（即被解析字段所属的对象）。此处字段解析器用作者的 `id` 调用服务，从而填充作者的 `posts` 数组，这就是必须在 `@Resolver()` 装饰器中指明父对象的原因。随后，`@Parent()` 方法参数装饰器会在字段解析器中提取对该父对象的引用。

你可以定义多个 `@Query()` 解析器函数（既可在这个类内，也可在其他解析器类中）。它们会连同解析器映射中对应的条目一起，被汇总为生成 SDL 中的单个 **Query 类型** 定义。这样你就可以把查询定义在贴近其使用的模型与服务的位置，并在模块中把它们组织得井井有条。

> info **提示** Nest CLI 提供了一个生成器（schematic），为你生成**全部样板代码**。详情请参见 [CRUD 生成器](/recipes/crud-generator)一章。

#### 查询类型名称

在上面的示例中，`@Query()` 装饰器从方法名推导出 GraphQL 查询名称。例如，看上面示例中的这段写法：

```typescript
@Query(() => Author)
async author(@Args('id', { type: () => Int }) id: number) {
  return this.authorsService.findOneById(id);
}
```

这会在模式中为 author 查询生成如下条目（查询使用与方法相同的名称）：

```graphql
type Query {
  author(id: Int!): Author!
}
```

> info **提示** 进一步了解 [GraphQL 查询](https://graphql.org/learn/queries/)。

按惯例，这些名称是解耦的。例如，你可以把查询处理器方法命名为 `getAuthor()`，但对外仍然把查询暴露为 `author`。字段解析器同理。要做到这一点，请把映射名称作为参数传给 `@Query()` 和 `@ResolveField()` 装饰器，如下所示：

```typescript
@@filename(authors/authors.resolver)
@Resolver(() => Author)
export class AuthorsResolver {
  constructor(
    private authorsService: AuthorsService,
    private postsService: PostsService,
  ) {}

  @Query(() => Author, { name: 'author' })
  async getAuthor(@Args('id', { type: () => Int }) id: number) {
    return this.authorsService.findOneById(id);
  }

  @ResolveField('posts', () => [Post])
  async getPosts(@Parent() author: Author) {
    const { id } = author;
    return this.postsService.findAll({ authorId: id });
  }
}
```

上面的 `getAuthor()` 处理器方法会生成 GraphQL 模式中如下这段 SDL：

```graphql
type Query {
  author(id: Int!): Author!
}
```

#### Query 装饰器选项

`@Query()` 装饰器的选项对象（即上面传入 `{{ '{' }}name: 'author'{{ '}' }}` 的地方）接受若干键值对：

- `name`：查询的名称；`string` 类型
- `description`：用于生成 GraphQL 模式文档（例如在 GraphiQL 中）的描述；`string` 类型
- `deprecationReason`：在模式元数据中把该查询标记为已废弃（例如在 GraphiQL 中显示）；`string` 类型
- `nullable`：查询是否可以返回 null 数据响应；`boolean`、`'items'` 或 `'itemsAndList'`（`'items'` 与 `'itemsAndList'` 的细节见上文）

#### Args 装饰器选项

使用 `@Args()` 装饰器从请求中提取参数，供处理器方法使用。其工作方式与 [REST 路由参数提取](/controllers#route-parameters)非常相似。

通常，`@Args()` 装饰器不需要选项对象。例如，如果标识符是字符串，下面这种写法就足够了：它从入站 GraphQL 请求中取出指定名称的字段，用作方法参数。

```typescript
@Args('id') id: string
```

`getAuthor()` 方法使用 `number` 类型，这带来了一个难题：TypeScript 的 `number` 类型没有携带足够的信息来表明期望的 GraphQL 表示（例如是 `Int` 还是 `Float`）。因此，你必须**显式**传入类型引用，方式是通过传给 `@Args()` 装饰器第二个参数的选项对象：

```typescript
@Query(() => Author, { name: 'author' })
async getAuthor(@Args('id', { type: () => Int }) id: number) {
  return this.authorsService.findOneById(id);
}
```

该选项对象接受以下可选的键值对：

- `type`：返回 GraphQL 类型的函数
- `defaultValue`：默认值；`any`
- `description`：描述元数据；`string`
- `deprecationReason`：用于废弃字段并提供说明原因的元数据；`string`
- `nullable`：字段是否可为 null

查询处理器方法可以接受多个参数。例如，要按 `firstName` 与 `lastName` 获取作者，请调用 `@Args()` 两次：

```typescript
getAuthor(
  @Args('firstName', { nullable: true }) firstName?: string,
  @Args('lastName', { defaultValue: '' }) lastName?: string,
) {}
```

> info **提示** 对于 `firstName` 这类 GraphQL 可空字段，你无需在字段的 TypeScript 类型中加上 `null` 或 `undefined`。但要注意，可空字段会把这两个值放行到你的解析器中，因此你需要在解析器里对它们做防护。

#### 专用参数类

使用内联 `@Args()` 调用时，上面那样的代码很快就会变得臃肿。你可以改为创建一个专用的 `GetAuthorArgs` 参数类，并在处理器方法中这样访问它：

```typescript
@Args() args: GetAuthorArgs
```

如下所示，用 `@ArgsType()` 创建 `GetAuthorArgs` 类：

```typescript
@@filename(authors/dto/get-author.args)
import { MinLength } from 'class-validator';
import { Field, ArgsType } from '@nestjs/graphql';

@ArgsType()
export class GetAuthorArgs {
  @Field({ nullable: true })
  firstName?: string;

  @Field({ defaultValue: '' })
  @MinLength(3)
  lastName: string;
}
```

> info **提示** 同样，由于 TypeScript 元数据反射系统的限制，你必须要么使用 `@Field()` 装饰器指明类型与可选性，要么使用 [CLI 插件](/graphql/cli-plugin)。与前面一样，你无需在可空的 `firstName` 字段类型中加上 `null` 或 `undefined`，但确实需要在解析器中对它们做防护。

这会在 GraphQL 模式中生成如下这段 SDL：

```graphql
type Query {
  author(firstName: String, lastName: String! = ""): Author!
}
```

> info **提示** 像 `GetAuthorArgs` 这样的参数类与 `ValidationPipe` 配合良好（参见[校验](/application/validation)）。

#### 类继承

你可以使用标准的 TypeScript 类继承，创建带有通用实用特性（字段与字段属性、校验等）的可扩展基类。例如，你可能有一组与分页相关的参数，它们总是包含标准的 `offset` 与 `limit` 字段，再加上其他类型特有的索引字段。你可以像下面这样搭建类继承层次。

基础 `@ArgsType()` 类：

```typescript
@ArgsType()
class PaginationArgs {
  @Field(() => Int)
  offset: number = 0;

  @Field(() => Int)
  limit: number = 10;
}
```

基础 `@ArgsType()` 类的具体类型子类：

```typescript
@ArgsType()
class GetAuthorArgs extends PaginationArgs {
  @Field({ nullable: true })
  firstName?: string;

  @Field({ defaultValue: '' })
  @MinLength(3)
  lastName: string;
}
```

`@ObjectType()` 对象也可以采用同样的方式。在基类上定义通用属性：

```typescript
@ObjectType()
class Character {
  @Field(() => Int)
  id: number;

  @Field()
  name: string;
}
```

在子类上添加具体类型的属性：

```typescript
@ObjectType()
class Warrior extends Character {
  @Field()
  level: number;
}
```

解析器同样可以使用继承，并与 TypeScript 泛型结合以保持类型安全。例如，要创建一个带有泛型 `findAll` 查询的基类，可以使用如下写法：

```typescript
function BaseResolver<T extends Type<unknown>>(classRef: T): any {
  @Resolver({ isAbstract: true })
  abstract class BaseResolverHost {
    @Query(() => [classRef], { name: `findAll${classRef.name}` })
    async findAll(): Promise<T[]> {
      return [];
    }
  }
  return BaseResolverHost;
}
```

请注意以下几点：

- 显式的返回类型（上面的 `any`）是必需的；否则 TypeScript 会对使用私有类定义报错。我们建议改为定义一个接口，而不是使用 `any`。
- `Type` 从 `@nestjs/common` 包导入。
- `isAbstract: true` 属性表示不应为该类生成 SDL（Schema Definition Language 语句）。你也可以在其他类型上设置该属性，以抑制 SDL 生成。

下面展示如何创建 `BaseResolver` 的具体子类：

```typescript
@Resolver(() => Recipe)
export class RecipesResolver extends BaseResolver(Recipe) {
  constructor(private recipesService: RecipesService) {
    super();
  }
}
```

这段写法会生成如下 SDL：

```graphql
type Query {
  findAllRecipe: [Recipe!]!
}
```

#### 泛型

上面我们已经看到泛型的一种用法。泛型让你可以构建可复用的抽象。例如，下面是根据 [GraphQL 分页指南](https://graphql.org/learn/pagination/#pagination-and-edges)实现的一个基于游标的分页：

```typescript
import { Field, ObjectType, Int } from '@nestjs/graphql';
import { Type } from '@nestjs/common';

interface IEdgeType<T> {
  cursor: string;
  node: T;
}

export interface IPaginatedType<T> {
  edges: IEdgeType<T>[];
  nodes: T[];
  totalCount: number;
  hasNextPage: boolean;
}

export function Paginated<T>(classRef: Type<T>): Type<IPaginatedType<T>> {
  @ObjectType(`${classRef.name}Edge`)
  abstract class EdgeType {
    @Field(() => String)
    cursor: string;

    @Field(() => classRef)
    node: T;
  }

  @ObjectType({ isAbstract: true })
  abstract class PaginatedType implements IPaginatedType<T> {
    @Field(() => [EdgeType], { nullable: true })
    edges: EdgeType[];

    @Field(() => [classRef], { nullable: true })
    nodes: T[];

    @Field(() => Int)
    totalCount: number;

    @Field()
    hasNextPage: boolean;
  }
  return PaginatedType as Type<IPaginatedType<T>>;
}
```

定义了这个基类之后，你就可以创建继承其行为的专用类型。例如：

```typescript
@ObjectType()
class PaginatedAuthor extends Paginated(Author) {}
```

#### 模式优先

正如[快速开始](/graphql/quick-start)一章所述，在模式优先方式中，你首先要在 SDL 中手动定义模式类型（参见 [GraphQL 类型语言](https://graphql.org/learn/schema/#type-language)）。请看下面的 SDL 类型定义。

> info **提示** 为方便起见，本章把所有 SDL 都放在一处（例如如下所示的单个 `.graphql` 文件）。实践中，你可能更倾向于模块化组织。例如，你可以为每个领域实体单独创建包含其类型定义的 SDL 文件，并把它们与该实体相关的服务、解析器代码和 Nest 模块类放在同一个专属目录下。Nest 会在运行时汇总所有单独的模式类型定义。

```graphql
type Author {
  id: Int!
  firstName: String
  lastName: String
  posts: [Post]
}

type Post {
  id: Int!
  title: String!
  votes: Int
}

type Query {
  author(id: Int!): Author
}
```

#### 模式优先的解析器

上面的模式只暴露了一个查询：`author(id: Int!): Author`。

> info **提示** 进一步了解 [GraphQL 查询](https://graphql.org/learn/queries/)。

现在创建一个解析 author 查询的 `AuthorsResolver` 类：

```typescript
@@filename(authors/authors.resolver)
@Resolver('Author')
export class AuthorsResolver {
  constructor(
    private authorsService: AuthorsService,
    private postsService: PostsService,
  ) {}

  @Query()
  async author(@Args('id') id: number) {
    return this.authorsService.findOneById(id);
  }

  @ResolveField()
  async posts(@Parent() author) {
    const { id } = author;
    return this.postsService.findAll({ authorId: id });
  }
}
```

> info **提示** 所有装饰器（如 `@Resolver`、`@ResolveField`、`@Args` 等）都从 `@nestjs/graphql` 包导出。

> warning **注意** `AuthorsService` 与 `PostsService` 类中的逻辑可以随需要而定，简单或复杂皆可。本示例的重点是展示如何构建解析器，以及它们如何与其他提供者交互。

`@Resolver()` 装饰器是必需的。它接受一个可选的字符串参数，即某个类型的名称。只要类中包含 `@ResolveField()` 装饰器，就必须提供这个名称，以告诉 Nest 被装饰的方法关联的是哪个父类型（本例中为 `Author` 类型）。另一种做法是不把 `@Resolver()` 施加到类上，而是施加到每个方法上：

```typescript
@Resolver('Author')
@ResolveField()
async posts(@Parent() author) {
  const { id } = author;
  return this.postsService.findAll({ authorId: id });
}
```

在这种情况下（`@Resolver()` 用在方法级别），如果一个类有多个 `@ResolveField()` 方法，你必须为每个方法都加上 `@Resolver()`。这不算最佳实践，因为会增加额外开销。

> info **提示** 传给 `@Resolver()` 的任何类名参数都**不会**影响查询（`@Query()` 装饰器）或变更（`@Mutation()` 装饰器）。

> warning **警告** 在方法级别使用 `@Resolver` 装饰器不受**代码优先**方式支持。

在上面的示例中，`@Query()` 与 `@ResolveField()` 装饰器依据方法名与 GraphQL 模式字段建立关联。例如，看上面示例中的这段写法：

```typescript
@Query()
async author(@Args('id') id: number) {
  return this.authorsService.findOneById(id);
}
```

这会在模式中为 author 查询生成如下条目（查询使用与方法相同的名称）：

```graphql
type Query {
  author(id: Int!): Author
}
```

按惯例，这些名称是解耦的，解析器方法使用 `getAuthor()` 或 `getPosts()` 这样的名称。要做到这一点，请把映射名称作为参数传给装饰器，如下所示：

```typescript
@@filename(authors/authors.resolver)
@Resolver('Author')
export class AuthorsResolver {
  constructor(
    private authorsService: AuthorsService,
    private postsService: PostsService,
  ) {}

  @Query('author')
  async getAuthor(@Args('id') id: number) {
    return this.authorsService.findOneById(id);
  }

  @ResolveField('posts')
  async getPosts(@Parent() author) {
    const { id } = author;
    return this.postsService.findAll({ authorId: id });
  }
}
```

> info **提示** Nest CLI 提供了一个生成器（schematic），为你生成**全部样板代码**。详情请参见 [CRUD 生成器](/recipes/crud-generator)一章。

#### 生成类型

如果你使用模式优先方式并启用了类型定义生成（使用 `outputAs: 'class'`，如[快速开始](/graphql/quick-start)一章所示），运行应用就会在你于 `GraphQLModule.forRoot()` 方法中指定的位置生成如下文件，例如 `src/graphql.ts`：

```typescript
@@filename(graphql)
export class Author {
  id: number;
  firstName?: string;
  lastName?: string;
  posts?: Post[];
}
export class Post {
  id: number;
  title: string;
  votes?: number;
}

export abstract class IQuery {
  abstract author(id: number): Author | Promise<Author>;
}
```

生成类（而非默认的接口）让你可以把声明式校验**装饰器**与模式优先方式结合起来（参见[校验](/application/validation)）。例如，你可以像下面这样，在生成的 `CreatePostInput` 类上添加 `class-validator` 装饰器，以强制限制 `title` 字段的最小与最大字符串长度：

```typescript
import { MinLength, MaxLength } from 'class-validator';

export class CreatePostInput {
  @MinLength(3)
  @MaxLength(50)
  title: string;
}
```

> warning **注意** 要启用对输入（与参数）的自动校验，请使用 `ValidationPipe`。更多内容参见[校验](/application/validation)与[管道](/pipes)章节。

但是，直接添加到生成文件中的装饰器在每次文件重新生成时都会被**覆盖**。你应当另建一个文件，并扩展生成的类。

```typescript
import { MinLength, MaxLength } from 'class-validator';
import { Post } from '../../graphql.js';

export class CreatePostInput extends Post {
  @MinLength(3)
  @MaxLength(50)
  title: string;
}
```

#### GraphQL 参数装饰器

你可以用专用装饰器访问标准的 GraphQL 解析器参数。下表列出了 Nest 装饰器与其所代表的原生 Apollo 参数的对应关系。

<table>
  <tbody>
    <tr>
      <td><code>@Root()</code> 与 <code>@Parent()</code></td>
      <td><code>root</code>/<code>parent</code></td>
    </tr>
    <tr>
      <td><code>@Context(param?: string)</code></td>
      <td><code>context</code> / <code>context[param]</code></td>
    </tr>
    <tr>
      <td><code>@Info(param?: string)</code></td>
      <td><code>info</code> / <code>info[param]</code></td>
    </tr>
    <tr>
      <td><code>@Args(param?: string)</code></td>
      <td><code>args</code> / <code>args[param]</code></td>
    </tr>
  </tbody>
</table>

这些参数的含义如下：

- `root`：一个对象，包含父字段上的解析器返回的结果；对于顶层 `Query` 字段，则是从服务器配置传入的 `rootValue`。
- `context`：一个在特定查询中由所有解析器共享的对象，通常用于存放按请求的状态。
- `info`：一个包含查询执行状态信息的对象。
- `args`：一个包含查询中传入该字段的参数的对象。

<app-banner-observe></app-banner-observe>

#### 模块

经过上述步骤，我们已用声明式的方式指定了 `GraphQLModule` 生成解析器映射所需的全部信息。`GraphQLModule` 利用反射内省装饰器提供的元数据，并自动把这些类转换为正确的解析器映射。

你唯一还需要做的，就是**提供**解析器类（`AuthorsResolver`），即在某个模块中把它列为提供者，并在某处导入该模块（`AuthorsModule`），以便 Nest 能够使用它。

例如，你可以在 `AuthorsModule` 中完成这件事，该模块还可以提供此场景中需要的其他服务。务必在某处导入 `AuthorsModule`（例如在根模块中，或在根模块导入的另一个模块中）。

```typescript
@@filename(authors/authors.module)
@Module({
  imports: [PostsModule],
  providers: [AuthorsService, AuthorsResolver],
})
export class AuthorsModule {}
```

> info **提示** 按**领域模型**组织代码会很有帮助（类似于在 REST API 中组织入口点的方式）。在这种做法下，把模型（`ObjectType` 类）、解析器和服务放在同一个表示该领域模型的 Nest 模块中，每个模块对应一个文件夹。这样组织并使用 [Nest CLI](/cli/overview) 生成各个元素时，CLI 会为你把这些部分串联起来（把文件放到合适的文件夹、向 `providers` 与 `imports` 数组添加条目等）。
