nestjs swagger moduleでswagger.jsonを出力する出力する
nestjs 公式の @nestjs/swaggerを使うと、nestjsで実装したhttp serverのAPIドキュメントを作成することができる。
main.ts(bootstrap)にセットアップした後、dto、コントローラー層にデコレータを使ってAPI仕様を定義する。
手元のlocalhostでswagger uiを立ち上げて確認する場合はいいのだが、staticなhtmlに出力して定常的にホスティングしたい場合などもあるのでstaticページを出力する方法はないものかと調べてみたが、今の所サポートされていなかった。
swagger.jsonを吐き出せれば、swagger code genでhtmlを生成出るので、次のようにすれば良い。
code:typescript
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
import * as path from 'path';
import { writeFileSync } from 'fs';
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();
ルートにswagger.jsonが吐き出されるので、あとは煮るなり焼くなり好きにすれば良さそう。
参考