JavaScriptNestjsNode.js

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

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts