如何在Nestjs中获取所有路由(从每个模块上的所有模块和控制器)?

时间:2019-10-06 07:03:36

标签: node.js typescript express nestjs

使用Nestjs,我想获得带有HTTP动词的所有可用路由(控制器方法)的列表,如下所示:

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

似乎需要访问Express路由器,但是我还没有在Nestjs中找到一种方法来做到这一点。为了表达方便,有一些库,例如“ express-list-routes”或“ express-list-endpoints”。

谢谢!

4 个答案:

答案 0 :(得分:2)

我刚刚发现Nestjs应用程序具有一个“ getHttpServer()”方法,通过它我可以访问“路由器堆栈”,这是解决方案:

// 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();

Nestjs available routes!

答案 1 :(得分:1)

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();

答案 2 :(得分:1)

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",
    ]
}

答案 3 :(得分:0)

在Nest中,每个本机服务器都在适配器中wrapped。对于那些使用Fastify的人:

// main.ts

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

有关固定钩子here的更多信息。