【问题标题】:How to generate openapi specification with nestjs without running the application如何在不运行应用程序的情况下使用 nestjs 生成 openapi 规范
【发布时间】:2021-03-03 17:56:44
【问题描述】:

我们有很多用 nodejs 编写的 API,使用的是 nestjs 框架。 我们可以使用来自 nestjs 的 SwaggerModule 生成 openapi.yaml。效果很好。但问题是它需要 API 启动,因此数据库启动并运行。这在我们的 CI/CD 中对我们来说是个问题,因为我们需要在运行 API 之前生成 openapi 规范。

是否可以从我们的代码生成 openapi 规范,而无需运行应用程序? 或者有没有一种简单的方法来模拟我们的数据库?

感谢您的帮助

【问题讨论】:

    标签: node.js swagger nestjs openapi


    【解决方案1】:

    简短的回答是否定的,there isn't a way to generate the docs 不运行 NestJS 应用程序。但是,您可以生成一个表示 OpenAPI 文档的 JSON 文件,然后从那里生成一个静态网站。 This issue 让你走到一半:

    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
    
      const options = new DocumentBuilder()
        .setTitle('Cats example')
        .setDescription('The cats API description')
        .setVersion('1.0')
        .addTag('cats')
        .build();
      const document = SwaggerModule.createDocument(app, options);
      const outputPath = path.resolve(process.cwd(), 'swagger.json');
      writeFileSync(outputPath, JSON.stringify(document), { encoding: 'utf8'});
    
      await app.close();
    }
    bootstrap();
    

    这将生成一个包含 OpenAPI 规范的文件swagger.json。从那里,您可以使用tool like Spectacle 来生成实际的 HTML:

    npx spectacle-docs -t public/docs swagger.json
    

    一个记录较少的功能是仅使用 curl 从常规端点检索 OpenAPI 规范的 JSON 表示的能力。

    假设您有一个标准的 @nestjs/swagger 集成,将 OpenAPI 文档发布到 /docs/

      const options = new DocumentBuilder()
        .setTitle('core-api')
        .setDescription('The core API description')
        .setVersion('3.0')
        .addTag('core-api')
        .setBasePath(version)
        .build();
      const document = SwaggerModule.createDocument(app, options);
      SwaggerModule.setup('docs', app, document);
    

    如果您浏览到http:/localhost:3000/docs/,您可以访问文档的 HTML 版本。但是,如果您浏览到 http://localhost:3000/docs-json,您将收到 JSON 表示。只需将-json 附加到您指定的路径即可。

    将所有这些结合在一起,您可以通过一些小技巧将其集成到 CI 管道中。我已将其集成到 Gitlab CI 管道中,如下所示:

    script:
      - until nc -vz $API_IP 3000; do sleep 1; done
      - curl http://$API_IP:3000/docs-json -o swagger.json
      - npx spectacle-docs -t public/docs swagger.json
    

    在您的 CI 管道中,您仍然需要运行 NestJS 应用程序以及 Mongo 和启动它所需的任何其他相关服务,但是一旦您生成 JSON,您就可以停止您的应用程序,构建静态 HTML网站并在其他地方发布。

    【讨论】:

    • 感谢您的回答。问题是我们需要我们的应用程序可以访问的规范。我们使用 Google Endpoints,它需要规范来构建路由。
    • @Jean-CharlesVERAZZI spectacle-docs,您只需将 html 文件复制到任何网络服务器(例如 nginx)来托管它们
    猜你喜欢
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 2014-03-07
    • 1970-01-01
    • 2022-10-13
    • 2021-06-07
    相关资源
    最近更新 更多