Mr.*_* MX 8 node.js express typescript nestjs
使用 Nestjs,我想使用 http 动词获取所有可用路由(控制器方法)的列表,如下所示:
API:
POST /api/v1/user
GET /api/v1/user
PUT /api/v1/user
Run Code Online (Sandbox Code Playgroud)
似乎需要访问 express 路由器,但我在 Nestjs 中找到了一种方法。对于 express 有一些库,例如“ express-list-routes ”或“ express-list-endpoints ”。
提前致谢!
Mr.*_* MX 10
我刚刚发现 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();
Run Code Online (Sandbox Code Playgroud)
主文件
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();
Run Code Online (Sandbox Code Playgroud)
小智 9
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)
}
}
...
Run Code Online (Sandbox Code Playgroud)
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)
}
}
...
Run Code Online (Sandbox Code Playgroud)
在 Nest 中,每个本机服务器都包装在一个适配器中。对于那些使用Fastify:
// main.ts
app
.getHttpAdapter()
.getInstance()
.addHook('onRoute', opts => {
console.log(opts.url)
})
Run Code Online (Sandbox Code Playgroud)
有关 fastify hooks 的更多信息请参见此处。
| 归档时间: |
|
| 查看次数: |
7119 次 |
| 最近记录: |