类型推断
三种自动机制:接口变成内联 schema,class-validator 变成 JSON Schema,@HttpCode() 变成正确的状态码。
接口类型的 DTO
当响应或 body 的类型是 TypeScript interface(而不是 class)时,Swagger 无法把它用作 type: 的值,因为接口在运行时会被擦除。nestjs-docfy 会自动检测到这种情况,生成一个内联的 schema: 对象,不需要改动你的代码。
Sua interface
// Your existing interface (no need to convert to a class)
export interface RegisterResponseDto {
success: boolean;
message: string | null;
}生成结果:
Generated
ApiResponse({
status: 201,
description: 'Created',
schema: {
type: 'object',
properties: {
success: { type: 'boolean' },
message: { type: 'string', nullable: true },
},
required: ['success'],
},
}),支持:基本类型、可空联合类型(T | null)、数组、嵌套接口,以及可选属性(会被排除在 required 之外)。
class-validator 推断
当一个 DTO 类使用了 class-validator 装饰器、且其属性上还没有 @ApiProperty 时,nestjs-docfy 会从校验装饰器中推断出完整的 JSON Schema,不需要任何手动标注。
create-user.dto.ts
// create-user.dto.ts
import { IsString, IsEmail, MinLength, IsOptional } from 'class-validator';
export class CreateUserDto {
@IsString()
@MinLength(2)
name: string;
@IsEmail()
email: string;
@IsOptional()
@IsString()
bio?: string;
}生成结果:
ts
ApiBody({
schema: {
type: 'object',
properties: {
name: { type: 'string', minLength: 2 },
email: { type: 'string', format: 'email' },
bio: { type: 'string' },
},
required: ['name', 'email'],
},
}),支持的装饰器
| Decorator |
|---|
@IsString |
@IsEmail |
@IsUrl |
@IsUUID |
@IsDateString |
@IsNumber |
@IsInt |
@IsBoolean |
@IsArray |
@Min |
@Max |
@MinLength |
@MaxLength |
@IsOptional |
保留已有的标注
只要类上任何一个属性已经有 @ApiProperty,推断就会被跳过,改用 type: ClassName;你已有的 Swagger 标注永远不会被覆盖。
@HttpCode() 支持
NestJS 的 @HttpCode() 装饰器会覆盖某个路由处理函数默认的 HTTP 状态码。nestjs-docfy 会自动读取它,并在生成的 ApiResponse 中使用正确的状态码。
users.controller.ts
// users.controller.ts
@Post('logout')
@HttpCode(204)
logout(): void { ... }生成结果:
ts
logout: [
ApiOperation({ summary: 'Logout' }),
ApiResponse({ status: 204, description: 'No Content' }),
],没有 @HttpCode() 时,会应用默认状态码:@Post 对应 201,其他所有 HTTP 方法对应 200。