问题
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