[英]generating swagger json file without running nest js server
我有一個帶有 controller 路由和 DTO 的嵌套 js 應用程序,並用 @nest/swagger 裝飾器注釋文檔。 我知道我可以通過啟動服務器並訪問 /api-json 來獲取 swagger json 文件,但我需要能夠生成此文件而無需先啟動服務器。
我設法從我的 e2e 測試中生成了 swagger 文件,而無需啟動服務器。
下面的代碼在 *.json 文件中生成 swagger 規范,您可以將其粘貼到https://editor.Z5DB861Z770/78A7A1 中。
// 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.