如何在NestJS中使用外部生成的swagger.json文件?

3
我已经从外部文档库生成了swagger.yaml/swagger.json。现在,我想将其导入并托管为API文档,我的API平台正在运行NestJS。我知道,我们可以从NestJS代码生成和导出Swagger,但对我来说需要反向操作,我们有swagger.json,需要在NestJS平台上呈现它,例如https://example.com/docs
1个回答

3

如果您已经有一个 swagger.json 文件,可以忽略 SwaggerModule.createDocumentDocumentBuilder,只需将解析后的 JSON 文件传递给 SwaggerModule.setup() 即可。


import { NestFactory } from '@nestjs/core';
import { SwaggerModule } from '@nestjs/swagger';
import { readFile } from 'fs/promises';
import { path } from 'join';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // read the JSON file to string and parse the string to object literal
  const document = JSON.parse(
    (await readFile(join(process.cwd(), 'swagger.json'))).toString('utf-8')
  )
  SwaggerModule.setup('api', app, document);

  await app.listen(3000);
}
bootstrap();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接