NestJSのSwagger(OpenAPI)定義をJSON / YAML出力する
NestJSでAPIサーバーを出したいけども、API定義についてはなにかしらの理由で別サーバーに置きたい時用の覚書です。 平たく言えばAWS LambdaなどのFaaSでNestJSを動かすケースですね。 OpenAPI […]
広告ここから
広告ここまで
目次
NestJSでAPIサーバーを出したいけども、API定義についてはなにかしらの理由で別サーバーに置きたい時用の覚書です。
平たく言えばAWS LambdaなどのFaaSでNestJSを動かすケースですね。
OpenAPI(Swagger)でのドキュメント生成
公式のSwaggerモジュールをyarn addして、src/main.tsに定義書くだけでOKです。
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const port = Number(process.env.PORT) || 3000
  const options = new DocumentBuilder()
    .setTitle('API example')
    .setDescription('The example API description')
    .setVersion('1.0')
    .addTag('example')
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api', app, document);
  await app.listen(port);
}
bootstrap();ファイル出力する
この定義をJSONやYAMLで吐き出す場合はこうします。
import { NestFactory } from '@nestjs/core';
import * as fs from 'fs'
import { dump } from 'js-yaml'
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const port = Number(process.env.PORT) || 3000
  const options = new DocumentBuilder()
    .setTitle('API xample')
    .setDescription('The example API description')
    .setVersion('1.0')
    .addTag('example')
    .build();
  const document = SwaggerModule.createDocument(app, options);
   
  // JSON
  fs.writeFileSync("./swagger-spec.json", JSON.stringify(document, undefined, 2));
  // YAML
  fs.writeFileSync("./swagger-spec.yaml", dump(document, {}));
  SwaggerModule.setup('api', app, document);
  await app.listen(port);
}
bootstrap();
サーバーを起動する際にJSON / YAMLそれぞれのファイルも出力するイメージです。
参考
https://github.com/nestjs/swagger/issues/57#issuecomment-368238060