sro*_*ool 6 documentation swagger nestjs
有谁知道一种方法(官方或通过第三方工具)生成 swagger json 文件而不需要运行 Nest js 服务器?
我有一个 Nest js 应用程序,其中包含控制器路由和 DTO,并使用 @nest/swagger 装饰器进行注释以用于文档。我知道我可以通过启动服务器并访问 /api-json 来获取 swagger json 文件,但我需要能够生成此文件,而无需先启动服务器。
我设法在不启动服务器的情况下从 e2e 测试中生成一个 swagger 文件。
下面的代码在 *.json 文件中生成 swagger 规范,您可以将其粘贴到https://editor.swagger.io/
// my-api.e2e-spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { HttpModule } from '@nestjs/axios';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import * as fs from 'fs';
describe('My E2E Tests', () => {
let app: NestFastifyApplication;
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [HttpModule],
}).compile();
app = module.createNestApplication(new FastifyAdapter());
app.setGlobalPrefix('/api/v1');
await app.init();
await app.getHttpAdapter().getInstance().ready();
});
afterAll(async () => {
await app.close();
});
it('should generate swagger spec', async () => {
const config = new DocumentBuilder().setTitle('My API').setDescription('My API').setVersion('1.0').build();
const document = SwaggerModule.createDocument(app, config);
fs.writeFileSync('./swagger.json', JSON.stringify(document));
});
});Run Code Online (Sandbox Code Playgroud)
注意:我的 package.json 中 @nestjs/swagger 的版本是 5.2.0