# 联合与枚举

来源：https://docs.nestjs.com/graphql/unions-and-enums

联合类型与接口类似，但联合类型不规定各成员类型之间有任何共同字段（参见 GraphQL 文档中的[联合类型](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,
});
```

> warning **警告** 请为 `createUnionType` 函数的 `types` 属性所返回的数组加上 const 断言（`as const`）。否则，TypeScript 在编译期会生成错误的声明文件，其他项目使用该联合时会报错失败。

现在你可以在查询中引用 `ResultUnion` 了：

```typescript
@Query(() => [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()` 函数，请在 `createUnionType()` 函数的选项对象中传入 `resolveType` 属性：

```typescript
export const ResultUnion = createUnionType({
  name: 'ResultUnion',
  types: () => [Author, Book] as const,
  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
```

然后，你可以使用类型定义生成功能（如 [GraphQL 快速开始](/graphql/quick-start) 一章所示）来生成对应的 TypeScript 定义：

```typescript
export class Author {
  name: string;
}

export class Book {
  title: string;
}

export type ResultUnion = Author | Book;
```

联合需要在解析器映射中额外提供一个 `__resolveType` 字段，以确定该联合解析为哪个类型。请创建 `ResultUnionResolver` 类并定义 `__resolveType` 方法，该方法返回具体类型的名称。记得把 `ResultUnionResolver` 注册为模块中的提供者。

```typescript
@Resolver('ResultUnion')
export class ResultUnionResolver {
  @ResolveField()
  __resolveType(value) {
    if (value.name) {
      return 'Author';
    }
    if (value.title) {
      return 'Book';
    }
    return null;
  }
}
```

> info **提示** 所有装饰器都由 `@nestjs/graphql` 包导出。

### 枚举

枚举类型是一种特殊的标量，其取值范围被限制在一组特定的允许值内（参见 GraphQL 文档中的[枚举类型](https://graphql.org/learn/schema/#enumeration-types)）。枚举让你可以：

- 校验该类型的任何参数都取自允许值之一
- 通过类型系统表明某个字段的取值始终是有限集合中的某一个

#### 代码优先

在代码优先方式中，定义一个 GraphQL 枚举类型的做法是创建一个 TypeScript 枚举：

```typescript
export enum AllowedColor {
  RED,
  GREEN,
  BLUE,
}
```

有了这个枚举之后，使用 `@nestjs/graphql` 包导出的 `registerEnumType` 函数注册 `AllowedColor` 枚举：

```typescript
registerEnumType(AllowedColor, {
  name: 'AllowedColor',
});
```

现在你可以在类型中引用 `AllowedColor` 了：

```typescript
@Field(type => AllowedColor)
favoriteColor: AllowedColor;
```

这会在 SDL 中生成 GraphQL 模式的以下片段：

```graphql
enum AllowedColor {
  RED
  GREEN
  BLUE
}
```

要为枚举提供描述，请把 `description` 属性传给 `registerEnumType()` 函数：

```typescript
registerEnumType(AllowedColor, {
  name: 'AllowedColor',
  description: 'The supported colors.',
});
```

要为各个枚举值提供描述，或把某个值标记为已废弃，请传入 `valuesMap` 属性：

```typescript
registerEnumType(AllowedColor, {
  name: 'AllowedColor',
  description: 'The supported colors.',
  valuesMap: {
    RED: {
      description: 'The default color.',
    },
    BLUE: {
      deprecationReason: 'Too blue.',
    },
  },
});
```

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

```graphql
"""
The supported colors.
"""
enum AllowedColor {
  """
  The default color.
  """
  RED
  GREEN
  BLUE @deprecated(reason: "Too blue.")
}
```

#### 模式优先

要在模式优先方式中定义枚举，请用 SDL 创建 GraphQL 枚举：

```graphql
enum AllowedColor {
  RED
  GREEN
  BLUE
}
```

然后，你可以使用类型定义生成功能（如 [GraphQL 快速开始](/graphql/quick-start) 一章所示）来生成对应的 TypeScript 定义：

```typescript
export enum AllowedColor {
  RED = "RED",
  GREEN = "GREEN",
  BLUE = "BLUE"
}
```

有时后端对某个枚举使用的内部值与公开 API 中暴露的值并不相同。在这个示例中，API 里是 `RED`，但解析器改用 `#f00`（参见 Apollo 文档中的[内部值](https://www.apollographql.com/docs/apollo-server/schema/scalars-enums/#internal-values)）。要做到这一点，请为 `AllowedColor` 枚举声明一个解析器对象：

```typescript
export const allowedColorResolver: Partial<Record<keyof typeof AllowedColor, any>> = {
  RED: '#f00',
};
```

> info **提示** 所有装饰器都由 `@nestjs/graphql` 包导出。

然后，在 `GraphQLModule#forRoot()` 方法的 `resolvers` 属性中传入这个解析器对象：

```typescript
GraphQLModule.forRoot({
  resolvers: {
    AllowedColor: allowedColorResolver,
  },
});
```
