NestJSでRoute一覧を確認する方法をまとめてみた

npm i express-list-endpointsを実行する

$ npm i express-list-endpoints
npm WARN ajv-keywords@3.5.2 requires a peer of ajv@^6.9.1 but none is installed. You must install peer dependencies yourself.

+ express-list-endpoints@6.0.0
added 1 package from 1 contributor and audited 749 packages in 4.419s
found 0 vulnerabilities

npm i -D @types/express-list-endpointsを実行する

$ npm i -D @types/express-list-endpoints
npm WARN ajv-keywords@3.5.2 requires a peer of ajv@^6.9.1 but none is installed. You must install peer dependencies yourself.

+ @types/express-list-endpoints@6.0.0
added 1 package from 1 contributor and audited 750 packages in 4.645s
found 0 vulnerabilities

main.tsを編集する

編集前のmain.tsはこんな感じです。

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

それを以下のように編集します。

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as listEndpoints from "express-list-endpoints"  //追加

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);

  const server = app.getHttpServer();                    //追加
  const router = server._events.request._router;         //追加
  console.log(listEndpoints(router));                    //追加
}
bootstrap();

ちなみにコントローラーはusersコントローラーのみで以下のようになってます。

import { Controller, Get } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get()
  hello(): string {
    return 'hello, world';
  }
}

この状態で「npm run start」をしたら、全てのRouteが確認できるようになるはずです。

$ npm run start

> pens-mate@0.0.1 start /Users/asakura/AsakuraProjects/Pens_Mate/pens-mate
> nest start

[Nest] 95308  - 2021-09-09 18:13:09     LOG [NestFactory] Starting Nest application...
[Nest] 95308  - 2021-09-09 18:13:09     LOG [InstanceLoader] AppModule dependencies initialized +14ms
[Nest] 95308  - 2021-09-09 18:13:09     LOG [RoutesResolver] AppController {/}: +4ms
[Nest] 95308  - 2021-09-09 18:13:09     LOG [RouterExplorer] Mapped {/, GET} route +2ms
[Nest] 95308  - 2021-09-09 18:13:09     LOG [RoutesResolver] UsersController {/users}: +0ms
[Nest] 95308  - 2021-09-09 18:13:09     LOG [RouterExplorer] Mapped {/users, GET} route +0ms
[Nest] 95308  - 2021-09-09 18:13:09     LOG [NestApplication] Nest application successfully started +2ms
[
  { path: '/', methods: [ 'GET' ], middlewares: [ 'anonymous' ] },
  { path: '/users', methods: [ 'GET' ], middlewares: [ 'anonymous' ] }
]
タイトルとURLをコピーしました