有没有人知道有一种方法(官方的或第三方的工具)可以在不需要nest js服务器运行的情况下生成挥霍无度的json文件?
我有一个带有控制器路由的nest js应用程序,还有一个带有@nest/swagger装饰器的DTO注释文档。我知道我可以通过启动服务器和访问/api-json来获得swagger json文件,但是我需要能够生成这个文件,而不必先启动服务器。
发布于 2022-07-29 12:29:41
我设法在没有启动服务器的情况下从我的e2e测试中生成一个swagger文件。
下面的代码在*.json文件中生成一个可以粘贴到https://editor.swagger.io/中的swagger规范
// 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));
});
});
注意:我的package.json中@nestjs/swagger的版本是5.2.0
https://stackoverflow.com/questions/72852736
复制