如何在 NestJS Interceptor 中获取处理程序路由(对于 Express 和 Fastify)

Som*_*Guy 5 express nestjs fastify

我在尝试在我编写的拦截器中获取 NestJS 处理程序的路由时遇到问题。例如,如果控制器有这样的路由:

  @Get('/params/:p1/:p2')
  routeWithParams(@Param() params): string {
    return `params are ${params.p1} and ${params.p2}`;
  }
Run Code Online (Sandbox Code Playgroud)

我希望能够以/param/:p1/:p2编程方式获取价值。使用 url 和去参数化不是一种选择,因为实际上没有一种方法可以以 %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();
  }
}

Run Code Online (Sandbox Code Playgroud)

如果事实证明拦截器无法解决问题,而像警卫这样的其他东西可以用来获取这些信息,我会全神贯注。

Som*_*Guy 12

在与 NestJS Discord 上的好人交谈后,我被指向Reflectors. 因此,使用反射器,我实际上可以获取传递给 HTTP 方法装饰器的路径数据。

import { Injectable, ExecutionContext, CallHandler, NestInterceptor } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import { Request } from 'express';
import { FastifyRequest } from 'fastify';
import { PATH_METADATA } from '@nestjs/common/constants';

function isExpressRequest(request: Request | FastifyRequest): request is Request {
  return (request as FastifyRequest).req === undefined;
}

@Injectable()
export class MyInterceptor implements NestInterceptor {
  constructor(private readonly reflector: Reflector) {}

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request: Request | FastifyRequest = context.switchToHttp().getRequest();

    const path = this.reflector.get<string[]>(PATH_METADATA, context.getHandler()); 
    const method = isExpressRequest(request) ? request.method : (request as FastifyRequest).req.method;

    // can now do something with the path and method

    return next.handle();
  }
}

Run Code Online (Sandbox Code Playgroud)

现在有一个有效的担忧,即PATH_METADATA密钥可能会在 NestJS 中移动,从而破坏此代码。完全有可能并且需要注意一些事情。但事实上,根据 git 对常量的指责,路径键已经 3 年没有更新了,这缓解了 imo 的这些担忧:https : //github.com/nestjs/nest/blame/master/packages/common/constants。 ts

  • 我发现如果您想获取完整路径(包括控制器级别路径和全局前缀),这种方法不太有效。为此,我求助于使用 `const path = context.switchToHttp().getRequest().route?.path`,这似乎工作正常。 (2认同)