类型和参数
类型和参数
SwaggerModule 搜索路由处理程序中的所有 @Body()、@Query() 和 @Param() 装饰器来生成 API 文档。它还通过利用反射来创建相应的模型定义。考虑以下代码:
@Post()
async create(@Body() createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
}
提示 要显式设置主体定义,请使用 @ApiBody() 装饰器(从 @nestjs/swagger 包导入)。
基于 CreateCatDto,将创建以下模型定义 Swagger UI:

如您所见,尽管该类有一些声明的属性,但定义是空的。为了使类属性对 SwaggerModule 可见,我们必须使用 @ApiProperty() 装饰器对它们进行注释,或使用 CLI 插件(在 Plugin 部分阅读更多内容),它将自动执行此操作:
import { ApiProperty } from '@nestjs/swagger';
export class CreateCatDto {
@ApiProperty()
name: string;
@ApiProperty()
age: number;
@ApiProperty()
breed: string;
}
提示 不要手动注释每个属性,考虑使用 Swagger 插件(参见插件部分),它将自动为您提供此功能。
让我们打开浏览器并验证生成的 CreateCatDto 模型:

此外,@ApiProperty() 装饰器允许设置各种模式对象属性:
@ApiProperty({
description: 'The age of a cat',
minimum: 1,
default: 1,
})
age: number;
提示 不要显式输入 {{"@ApiProperty({ required: false })"}},您可以使用 @ApiPropertyOptional() 简写装饰器。
为了显式设置属性的类型,请使用 type 键:
@ApiProperty({
type: Number,
})
age: number;
数组
当属性是数组时,我们必须手动指示数组类型,如下所示:
@ApiProperty({ type: [String] })
names: string[];
提示 考虑使用 Swagger 插件(参见插件部分),它将自动检测数组。
要么将类型作为数组的第一个元素包含(如上所示),要么将 isArray 属性设置为 true。
循环依赖
当类之间存在循环依赖时,使用惰性函数为 SwaggerModule 提供类型信息:
@ApiProperty({ type: () => Node })
node: Node;
提示 考虑使用 Swagger 插件(参见插件部分),它将自动检测循环依赖。
泛型和接口
由于 TypeScript 不存储有关泛型或接口的元数据,当您在 DTO 中使用它们时,SwaggerModule 可能无法在运行时正确生成模型定义。例如,以下代码不会被 Swagger 模块正确检查:
createBulk(@Body() usersDto: CreateUserDto[])
为了克服这个限制,您可以显式设置类型:
@ApiBody({ type: [CreateUserDto] })
createBulk(@Body() usersDto: CreateUserDto[])
枚举
要识别 enum,我们必须在 @ApiProperty 上手动设置 enum 属性,并提供一个值数组。
@ApiProperty({ enum: ['Admin', 'Moderator', 'User']})
role: UserRole;
或者,定义一个实际的 TypeScript 枚举,如下所示:
export enum UserRole {
Admin = 'Admin',
Moderator = 'Moderator',
User = 'User',
}
然后,您可以将枚举与 @Query() 参数装饰器结合使用,并与 @ApiQuery() 装饰器结合使用。
@ApiQuery({ name: 'role', enum: UserRole })
async filterByRole(@Query('role') role: UserRole = UserRole.User) {}

将 isArray 设置为 true 时,enum 可以选择为多选:

枚举模式
默认情况下,enum 属性将在 parameter 上添加枚举的原始定义。
- breed:
type: 'string'
enum:
- Persian
- Tabby
- Siamese
上述规范在大多数情况下都能正常工作。但是,如果您使用的工具将规范作为输入并生成客户端代码,您可能会遇到生成的代码包含重复 enums 的问题。考虑以下代码片段:
// 生成的客户端代码
export class CatDetail {
breed: CatDetailEnum;
}
export class CatInformation {
breed: CatInformationEnum;
}
export enum CatDetailEnum {
Persian = 'Persian',
Tabby = 'Tabby',
Siamese = 'Siamese',
}
export enum CatInformationEnum {
Persian = 'Persian',
Tabby = 'Tabby',
Siamese = 'Siamese',
}
提示 上述代码片段是使用名为 NSwag 的工具生成的。
您可以看到现在您有两个完全相同的 enums。
要解决此问题,您可以在装饰器中传递 enumName 以及 enum 属性。
export class CatDetail {
@ApiProperty({ enum: CatBreed, enumName: 'CatBreed' })
breed: CatBreed;
}
enumName 属性使 @nestjs/swagger 将 CatBreed 转换为自己的 schema,这反过来使 CatBreed 枚举可重用。规范将如下所示:
CatDetail:
type: 'object'
properties:
...
- breed:
schema:
$ref: '#/components/schemas/CatBreed'
CatBreed:
type: string
enum:
- Persian
- Tabby
- Siamese
提示 任何将 enum 作为属性的装饰器也将接受 enumName。
属性值示例
您可以使用 example 键为属性设置单个示例,如下所示:
@ApiProperty({
example: 'persian',
})
breed: string;
如果您想提供多个示例,可以通过传入如下结构的对象来使用 examples 键:
@ApiProperty({
examples: {
Persian: { value: 'persian' },
Tabby: { value: 'tabby' },
Siamese: { value: 'siamese' },
'Scottish Fold': { value: 'scottish_fold' },
},
})
breed: string;
原始定义
在某些情况下,例如深度嵌套的数组或矩阵,您可能需要手动定义您的类型:
@ApiProperty({
type: 'array',
items: {
type: 'array',
items: {
type: 'number',
},
},
})
coords: number[][];
您还可以指定原始对象模式,如下所示:
@ApiProperty({
type: 'object',
properties: {
name: {
type: 'string',
example: 'Error'
},
status: {
type: 'number',
example: 400
}
},
required: ['name', 'status']
})
rawDefinition: Record<string, any>;
要在控制器类中手动定义输入/输出内容,请使用 schema 属性:
@ApiBody({
schema: {
type: 'array',
items: {
type: 'array',
items: {
type: 'number',
},
},
},
})
async create(@Body() coords: number[][]) {}
额外模型
要定义在控制器中没有直接引用但应该被 Swagger 模块检查的额外模型,请使用 @ApiExtraModels() 装饰器:
@ApiExtraModels(ExtraModel)
export class CreateCatDto {}
提示 对于特定的模型类,您只需要使用一次 @ApiExtraModels()。
或者,您可以将带有指定 extraModels 属性的选项对象传递给 SwaggerModule.createDocument() 方法,如下所示:
const documentFactory = () =>
SwaggerModule.createDocument(app, options, {
extraModels: [ExtraModel],
});
要获取对模型的引用($ref),请使用 getSchemaPath(ExtraModel) 函数:
'application/vnd.api+json': {
schema: { $ref: getSchemaPath(ExtraModel) },
},
oneOf、anyOf、allOf
要组合模式,您可以使用 oneOf、anyOf 或 allOf 关键字(阅读更多)。
@ApiProperty({
oneOf: [
{ $ref: getSchemaPath(Cat) },
{ $ref: getSchemaPath(Dog) },
],
})
pet: Cat | Dog;
如果您想定义一个多态数组(即,其成员跨越多个模式的数组),您应该使用原始定义(见上文)手动定义您的类型。
type Pet = Cat | Dog;
@ApiProperty({
type: 'array',
items: {
oneOf: [
{ $ref: getSchemaPath(Cat) },
{ $ref: getSchemaPath(Dog) },
],
},
})
pets: Pet[];
提示 getSchemaPath() 函数从 @nestjs/swagger 导入。
Cat 和 Dog 都必须使用 @ApiExtraModels() 装饰器(在类级别)定义为额外模型。
模式名称和描述
如您可能已经注意到的,生成的模式的名称基于原始模型类的名称(例如,CreateCatDto 模型生成 CreateCatDto 模式)。如果您想更改模式名称,可以使用 @ApiSchema() 装饰器。
这是一个示例:
@ApiSchema({ name: 'CreateCatRequest' })
class CreateCatDto {}
上面的模型将被转换为 CreateCatRequest 模式。
默认情况下,不会向生成的模式添加描述。您可以使用 description 属性添加一个:
@ApiSchema({ description: 'Description of the CreateCatDto schema' })
class CreateCatDto {}
这样,描述将包含在模式中,如下所示:
schemas:
CreateCatDto:
type: object
description: Description of the CreateCatDto schema