如何忽略 NestJS 中特定路由的拦截器

sre*_*moh 7 javascript node.js typescript nestjs

我已经设置了控制器级拦截器@UseInterceptors(CacheInterceptor)。现在我希望控制器路由之一忽略该拦截器,有什么方法可以在nest.js 中实现这一点吗?

对于这种特殊情况,我希望能够禁用CacheInterceptor其中一条路线。

@Controller()
@UseInterceptors(CacheInterceptor)
export class AppController {
  @Get('route1')
  route1() {
    return ...;
  }

  @Get('route2')
  route2() {
    return ...;
  }
  @Get('route3')
  route3() {
    return ...;
  }
  @Get('route4')
  route4() {
    return ...; // do not want to cache this route
  }
}
Run Code Online (Sandbox Code Playgroud)

Kim*_*ern 5

根据这个问题,没有额外的排除装饰器,但您可以扩展CacheInterceptor并提供排除的路线。

@Injectable()
class HttpCacheInterceptor extends CacheInterceptor {
  trackBy(context: ExecutionContext): string | undefined {
    const request = context.switchToHttp().getRequest();
    const isGetRequest = this.httpServer.getRequestMethod(request) === 'GET';
    const excludePaths = ['path1', 'path2'];
          ^^^^^^^^^^^^
    if (
      !isGetRequest ||
      (isGetRequest && excludePaths.includes(this.httpServer.getRequestUrl))
    ) {
      return undefined;
    }
    return this.httpServer.getRequestUrl(request);
  }
}
Run Code Online (Sandbox Code Playgroud)