简体   繁体   中英

nestjs how to no apply interceptor global to a controller

I have a global interceptor but I need not apply in a controller specified.

app.useGlobalInterceptors(new ResponseInterceptor());

  @Get()
  async method(@Query() query) {
      code here......
  }

Does anyone know how to do it?

If the interceptor is global, it will be applied to everything. The only way around it is to apply some sort of custom metadata to the route that tells the interceptor to not run for this route. You'll need to add a check in the interceptor to look for that metadata. Something like this may be what you're looking for:

export function OgmaSkip() {
  return (
    target: any,
    key?: string | symbol,
    descriptor?: TypedPropertyDescriptor<any>,
  ) => {
    if (descriptor) {
      Reflect.defineMetadata(OGMA_INTERCEPTOR_SKIP, true, descriptor.value);
      return descriptor;
    }
    Reflect.defineMetadata(OGMA_INTERCEPTOR_SKIP, true, target);
    return target;
  };
}

Where this decorator applies metadata to either the controller or the method, and then in the interceptor you can apply a check like this:

public shouldSkip(context: ExecutionContext): boolean {
  const decoratorSkip =
    this.reflector.get(OGMA_INTERCEPTOR_SKIP, context.getClass()) ||
    this.reflector.get(OGMA_INTERCEPTOR_SKIP, context.getHandler());
  if (decoratorSkip) {
    return true;
  }
}

I have more logic to this check in my actual codebase, but it should be a start for you.

You can bind interceptor

@UseInterceptors(ResponseInterceptor)
@Get()
async method(@Query() query) {
  code here......
}

https://docs.nestjs.com/interceptors

hope will help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM