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

时间:2019-02-01 00:41:04

标签: 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
  }
}

2 个答案:

答案 0 :(得分:1)

根据this issue,有no additional exclude decorator,但是您可以扩展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);
  }
}

答案 1 :(得分:0)

hist(x, breaks = c(min(x), seq(min(x) + 36, max(x), 50)))