主题
集成 Swagger
@nestjs/swagger 根据 Controller、路由参数和 DTO 生成 OpenAPI 文档,并提供可交互的 Swagger UI。以下配置以 VfanHub 为例。
依赖
bash
pnpm add @nestjs/swagger文档入口
VfanHub 在各环境默认关闭文档,只有 SWAGGER_ENABLED=true 时才注册 Swagger UI 和 OpenAPI JSON。
bash
SWAGGER_ENABLED=true应用入口 main.ts 调用 infrastructure/swagger/setup-swagger.ts。业务路由使用 /api/v1 前缀,文档使用独立路径 /api/docs 和 /api/openapi.json。raw: ['json'] 只发布 JSON 格式的原始规范。
ts
import type { INestApplication } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'
/** 按环境配置注册 OpenAPI 文档 */
export function setupSwagger(app: INestApplication) {
if (app.get(ConfigService).get<string>('SWAGGER_ENABLED') !== 'true') return
const config = new DocumentBuilder()
.setTitle('VfanHub API')
.setVersion('1.0.0')
.addBearerAuth({ type: 'http', scheme: 'bearer' }, 'access')
.addCookieAuth('refresh_token', { type: 'apiKey', in: 'cookie' }, 'refresh')
.build()
/** 按显式声明的标签分组 */
const documentFactory = () => SwaggerModule.createDocument(app, config, { autoTagControllers: false })
SwaggerModule.setup('api/docs', app, documentFactory, {
jsonDocumentUrl: 'api/openapi.json',
raw: ['json'],
swaggerOptions: { persistAuthorization: false, withCredentials: true },
})
}认证声明
access对应Authorization: Bearer <token>。VfanHub 的@AuthEndpoint()同时设置 Guard 读取的访问范围和@ApiBearerAuth('access')refresh对应refresh_tokenCookie,刷新和退出端点用@ApiCookieAuth('refresh')声明。调试时先调用登录接口,由浏览器保存并按 Cookie 规则自动发送- OpenAPI 的安全声明负责描述契约。限流、认证和权限校验由运行时 Guard 或 Service 执行
DTO 与响应 Schema
TypeScript 的运行时反射无法获得完整的字段信息。@ApiProperty() 和 @ApiPropertyOptional() 可补充字段、格式和示例。VfanHub 通过 TokenView 描述登录成功后 data 字段的结构。
ts
import { ApiProperty } from '@nestjs/swagger'
export class TokenView {
@ApiProperty()
accessToken!: string
@ApiProperty({ example: 900, description: '访问令牌的有效秒数' })
expiresIn!: number
}响应 DTO 不应包含密码、Refresh Token 或内部状态等敏感字段。数组、泛型、联合类型等无法自动推断时,需要显式声明 Schema。
| 装饰器 | 用途 |
|---|---|
@ApiProperty() | 描述必填字段的类型、格式、示例和约束 |
@ApiPropertyOptional() | 描述可选字段,等同于设置 required: false |
@ApiHideProperty() | 从生成的 OpenAPI Schema 中隐藏指定字段 |
@ApiExtraModels() | 注册未被 Controller 直接引用的额外 DTO 模型 |
VfanHub 使用 @ApiTags() 显式分组。业务端点大多通过 @Document(summary, model, kind) 描述全局响应拦截器和异常过滤器使用的 { code, msg, data } 结构。
kind支持单项、数组和{ items, total }分页。用ApiExtraModels()注册 DTO,再通过getSchemaPath()在data内引用@Document('密码登录', TokenView)声明 HTTP 200 和一组通用错误。返回其他成功状态、文件或原始文本的端点按实际契约声明- Guard 直接读取请求体的登录端点使用
@ApiBody({ type: ClientPasswordLoginDto })显式声明 DTO。缺失的路径和查询参数约束可用@ApiParam()和@ApiQuery()补充
