我在尝试在我正在编写的拦截器中获取 NestJS 处理程序的路由时遇到问题。例如,如果控制器有这样的路由:
@Get('/params/:p1/:p2')
routeWithParams(@Param() params): string {
return `params are ${params.p1} and ${params.p2}`;
}
我希望能够以/param/:p1/:p2
编程方式获取价值。使用 url 和 deparameterizing 不是一种选择,因为实际上没有办法以 %100 密封的方式这样做。进行了一些挖掘,但没有找到记录在案的方法来获取处理程序的路线。想知道其他人有没有运气?这是我从项目中剥离的一些示例代码:
import { Injectable, ExecutionContext, CallHandler, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { Request } from 'express';
import { FastifyRequest } from 'fastify';
function isExpressRequest(request: Request | FastifyRequest): request is Request {
return (request as FastifyRequest).req === undefined;
}
@Injectable()
export class MyInterceptor implements NestInterceptor {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const request: Request | FastifyRequest = context.switchToHttp().getRequest();
if( !isExpressRequest(request) ) { // if req fufills the FastifyRequest interface, we will rename the transaction
const req = request as FastifyRequest;
const route = `` // TODO how can I grab the route either using the FastifyRequest or ExecutionContext??
} // otherwise, we are in express request
const route = `` // TODO how can I grab the route either using the Request or ExecutionContext?
return next.handle();
}
}
如果事实证明拦截器无法解决问题,而像警卫这样的其他东西可以用来获取这些信息,我会全力以赴。