【问题标题】:How to ignore an interceptor for a particular route in NestJS如何忽略 NestJS 中特定路由的拦截器
【发布时间】:2019-02-01 00:41:03
【问题描述】:

我设置了一个控制器级别的拦截器@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
  }
}

【问题讨论】:

    标签: javascript node.js typescript nestjs


    【解决方案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);
      }
    }
    

    【讨论】:

    • 我在 github 问题中搜索,但没有找到。感谢您的帮助。
    • 顺便说一句,您可以使用custom/extended 拦截器为每个路径设置一个特定的 ttl 吗?假设我想要 route1route2ttl 5 小时,route3route4 24 小时
    【解决方案2】:
      const IgnoredPropertyName = Symbol('IgnoredPropertyName')
      
      export function CustomInterceptorIgnore() {
        return function(target, propertyKey: string, descriptor: PropertyDescriptor) {
          descriptor.value[IgnoredPropertyName] = true
        };
      }
      
      
      @Injectable()
      export class CustomInterceptor implements NestInterceptor {
        constructor() {}
      
        async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
          const request: ExtendedUserRequest = context.switchToHttp().getRequest()
          const isIgnored = context.getHandler()[IgnoredPropertyName]
          if (isIgnored) {
            return next.handle()
          }
        }
      }
      
      @Patch('route')
      @CustomInterceptorIgnore()
      async someHandle () {
      
      }
    

    【讨论】:

    • 为每个处理程序(函数)添加特殊属性。然后如果在拦截器中找到此属性,则拦截器将不适用于此处理程序。
    • 这可能是一个有效的例子,但不幸的是我无法使用这种方法。
    猜你喜欢
    • 2015-10-25
    • 2020-02-05
    • 2020-01-03
    • 2020-12-12
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 2018-01-08
    相关资源
    最近更新 更多