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!
js allows us to create multiple routes on a single express server. Creating multiple routes on a single server is better to practice rather than creating single routes for handling different requests made by the client.
A route is a combination of an HTTP method, a path, and the function to handle it defined in an application. They help determine which controllers receive certain requests. A controller is a class defined with methods for handling one or more requests. The controller provides the handler function for a route.
To get the URL parameter values or params from a GET request, we can use the @Param decorator function from the @nestjs/common module before the Controller method in Nestjs.
A module is a class annotated with a @Module() decorator. The @Module() decorator provides metadata that Nest makes use of to organize the application structure. Each application has at least one module, a root module.
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();
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",
]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With