如何在NestJS中读取YAML文件生成API文档,求相关配置方案
NestJS读取YAML文件生成API文档配置方案
你已经找到的YAML文件读取代码可以直接复用,以下是两种常用场景的完整配置:
前置依赖安装
首先安装所需的第三方包:
npm install @nestjs/swagger swagger-ui-express js-yaml npm install @types/js-yaml -D
使用Fastify作为服务框架的话,需要将swagger-ui-express替换为@fastify/swagger和@fastify/swagger-ui
场景1:直接加载现成OpenAPI规范YAML生成文档
如果已经写好了符合OpenAPI 3.0+规范的YAML格式接口文档,直接在项目启动时加载解析即可:
- 将YAML文档放入项目目录,例如
src/resources/openapi.yaml - 修改启动文件
main.ts的代码:
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { SwaggerModule } from '@nestjs/swagger'; import { readFileSync } from 'fs'; import * as yaml from 'js-yaml'; import { join } from 'path'; async function bootstrap() { const app = await NestFactory.create(AppModule); // 解析OpenAPI YAML文件 const apiDocument = yaml.load( readFileSync(join(__dirname, './resources/openapi.yaml'), 'utf8') ) as Record<string, any>; // 挂载文档路由,访问路径为/api-doc SwaggerModule.setup('api-doc', app, apiDocument); await app.listen(3000); } bootstrap();
启动服务后访问http://localhost:3000/api-doc即可查看生成的可交互API文档。
场景2:读取YAML接口配置动态生成接口和文档
如果需要把接口路径、参数、返回值等配置写在YAML中,动态生成接口逻辑和对应文档:
- 复用你已有的YAML加载逻辑,将接口配置加载为全局可访问的配置项
- 在模块初始化阶段,通过
@nestjs/swagger提供的动态装饰器,为自动生成的控制器和路由绑定文档信息,示例逻辑如下:
// 读取接口配置 import apiConfig from './config/api.config'; // 这里就是你写的YAML加载导出的方法 // 动态生成控制器路由和文档 for (const api of apiConfig.apis) { // 动态注册路由 app.get(api.path, (req, res) => { /* 接口逻辑 */ }); // 动态绑定文档信息 ApiOperation({ summary: api.summary })(controllerPrototype, api.methodName); ApiResponse({ status: 200, description: api.responseDesc })(controllerPrototype, api.methodName); }
注意事项
- 确保YAML文件格式符合要求,避免解析失败
- 打包部署时需要将YAML文件一同打包到运行目录,避免读取路径不存在的报错
- 多环境场景可以把YAML文件路径写在环境变量中,运行时动态切换
内容的提问来源于stack exchange,提问作者hoangkm
相关产品推荐
相关产品推荐

