How can I get all the routes (from all the modules and controllers available on each module) in Nestjs?

自作多情 提交于 2021-01-22 10:35:12

问题


Using Nestjs I'd like to get a list of all the available routes (controller methods) with http verbs, like this:

API:
      POST   /api/v1/user
      GET    /api/v1/user
      PUT    /api/v1/user

It seems that access to express router is required, but I haven found a way to do this in Nestjs. For express there are some libraries like "express-list-routes" or "express-list-endpoints".

Thanks in advance!


回答1:


I just found that Nestjs app has a "getHttpServer()" method, with this I was able to access the "router stack", here's the solution:

// main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as expressListRoutes from 'express-list-routes';

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


  const server = app.getHttpServer();
  const router = server._events.request._router;
  console.log(expressListRoutes({}, 'API:', router));

}
bootstrap();




回答2:


main.ts

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
  const server = app.getHttpServer();
  const router = server._events.request._router;

  const availableRoutes: [] = router.stack
    .map(layer => {
      if (layer.route) {
        return {
          route: {
            path: layer.route?.path,
            method: layer.route?.stack[0].method,
          },
        };
      }
    })
    .filter(item => item !== undefined);
  console.log(availableRoutes);
}
bootstrap();



回答3:


import { Controller, Get, Request } from "@nestjs/common";
import { Request as ExpressRequest, Router } from "express";

...

@Get()
root(@Request() req: ExpressRequest) {
    const router = req.app._router as Router;
    return {
        routes: router.stack
            .map(layer => {
                if(layer.route) {
                    const path = layer.route?.path;
                    const method = layer.route?.stack[0].method;
                    return `${method.toUpperCase()} ${path}`
                }
            })
            .filter(item => item !== undefined)
    }
}

...
{
    "routes": [
        "GET /",
        "GET /users",
        "POST /users",
        "GET /users/:id",
        "PUT /users/:id",
        "DELETE /users/:id",
    ]
}



回答4:


In Nest every native server is wrapped in an adapter. For those, who use Fastify:

// main.ts

app
    .getHttpAdapter()
    .getInstance()
    .addHook('onRoute', opts => {
      console.log(opts.url)
    })

More about fastify hooks here.



来源:https://stackoverflow.com/questions/58255000/how-can-i-get-all-the-routes-from-all-the-modules-and-controllers-available-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!