javascript - Hvordan ignorere en interceptor for en bestemt rute i NestJS


Jeg har satt en interceptor på kontroller-nivå @UseInterceptors(CacheInterceptor). Nå ønsker jeg at en av kontroller-rutene skal ignorere den interceptor, finnes det noen måte å oppnå det på i nest.js?

For dette spesifikke tilfellet vil jeg kunne deaktivere CacheInterceptor for en av rutene.

@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
  }
}

Svar #1

Ifølge dette problemet finnes det ingen ekstra exclude-dekorator, men i stedet kan du bare utvide CacheInterceptor og angi de ekskluderte rutene.

@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);
  }
}

Svar #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 () {
  
  }

Relaterte artikler