LoginSignup
6
0

More than 3 years have passed since last update.

NestJSでOpenAPI(Swagger)定義をファイル出力する

Last updated at Posted at 2020-03-15

公式ドキュメントには起動しているサーバからJSON出力するサンプルしかなかったので調べてみました
単純に OpenAPIObject をYAMLなりJSONなりに出力すればよい模様

exportOpenAPIDocument.ts
import yaml from 'js-yaml';
import fs from 'fs-extra';
import path from 'path';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module';
import { NestFactory } from '@nestjs/core';

const exportOpenAPIDocument = async () => {
  const app = await NestFactory.create(AppModule);

  const documentBuilder = new DocumentBuilder()
    .setTitle('xxxxx')
    .setDescription('xxxxx')
    .setVersion('1.0')
    .build();

  const document = SwaggerModule.createDocument(app, documentBuilder);
  const yamlDocument = yaml.safeDump(document, {
    skipInvalid: true,
    noRefs: true,
  });
  const yamlPath = path.join(__dirname, 'path_to', 'openapi.yml');

  await fs.writeFile(yamlPath, yamlDocument);
};

(async () => await exportOpenAPIDocument())();

package.json には以下の感じで書いておくと便利でしょう

package.json(抜粋)
{
  "scripts": {
    "openapi:export": "ts-node src/exportOpenAPIDocument.ts"
  }
}
$ npm run openapi:export

お試しを!👳‍♂️

6
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
0