NestJS如何通过OpenAPI注解配置多响应媒体类型并关联TS类
解决NestJS控制器多响应格式的OpenAPI文档配置问题
核心配置方案
要在OpenAPI文档中同时记录JSON和CSV两种响应格式,并关联TypeScript类SystemStatistics,可以通过@ApiOkResponse的content属性结合getSchemaRef方法实现,具体步骤如下:
1. 导入必要依赖
确保导入@nestjs/swagger提供的工具方法:
import { ApiOkResponse, ApiProduces, getSchemaRef } from '@nestjs/swagger'; import { SystemStatistics } from './path/to/system-statistics.dto';
2. 配置@ApiOkResponse的多媒体类型响应
在控制器方法上添加注解,分别为application/json和text/csv配置响应结构:
@Get('system-stats') @ApiProduces('application/json', 'text/csv') // 声明接口支持的媒体类型 @ApiOkResponse({ content: { // JSON格式响应:关联SystemStatistics类 'application/json': { schema: getSchemaRef(SystemStatistics), }, // CSV格式响应:定义为纯文本字符串,可添加示例 'text/csv': { schema: { type: 'string', example: 'timestamp,cpuUsage,memoryUsage\n2024-05-20T12:00:00,42%,58%', }, }, }, }) async getSystemStats(@Req() req: Request): Promise<SystemStatistics | string> { // 业务逻辑:获取统计数据 const stats = await this.statsService.fetchStats(); // 根据Accept头或请求参数判断返回格式 if (req.headers.accept === 'text/csv') { // 将SystemStatistics转换为CSV字符串 return this.csvConverter.convert(stats); } return stats; }
3. 确保SystemStatistics类已添加Swagger注解
getSchemaRef依赖类上的@ApiProperty注解生成OpenAPI Schema,需提前配置:
import { ApiProperty } from '@nestjs/swagger'; export class SystemStatistics { @ApiProperty({ description: '统计时间戳' }) timestamp: Date; @ApiProperty({ description: 'CPU使用率' }) cpuUsage: string; @ApiProperty({ description: '内存使用率' }) memoryUsage: string; }
关键说明
getSchemaRef(SystemStatistics)会自动生成指向该类对应OpenAPI Schema的$ref字符串,无需手动编写,解决了类型仅支持字符串$ref的问题。@ApiProduces注解用于声明接口支持的媒体类型,会在OpenAPI文档中展示可选的Accept头选项。- CSV格式的响应直接定义为
string类型,并通过example字段提供示例值,方便文档使用者理解输出格式。
内容的提问来源于stack exchange,提问作者sleidig
相关产品推荐
相关产品推荐

