0

I am using CacheInterceptor by NestJS for caching requests and responses using Redis. One of the use cases that I have is to toggle caching (disable it completely) based on an environment variable.

I am using ConfigModule to read configs from environment variables and using it across the project.

Using ConfigService, I can optionally initialize CacheModule but the CacheInterceptor applied on the routes fails when it can't find a CacheManager.

I would like to add CacheInterceptor over a controller method only when the a config variable is set. How can I achieve this?

Sample code that I have:

Extended interceptor to ensure namespace prefix:

@Injectable()
export class CacheRequestInterceptor extends CacheInterceptor {

  trackBy(context: ExecutionContext): string | undefined {
    const request = context.switchToHttp().getRequest();
    const { httpAdapter } = this.httpAdapterHost;

    return `namespace-prefix:${httpAdapter.getRequestUrl(request)}`;
  }
}

Added interceptor over a route:

@UseInterceptors(CacheRequestInterceptor)
@Get()
getSomething(@Query() query: SampleQueryParams): Observable<Something[]> {
  return this.service.lookupSomething(query.q);
}

Is there a way to optionally add an interceptor (for example, based on a value read from ConfigService)?

devpolo
  • 2,487
  • 3
  • 12
  • 28
Nishkarsh
  • 274
  • 4
  • 16
  • You can override [`CacheInterceptor.intercept()`](https://github.com/nestjs/nest/blob/master/packages/common/cache/interceptors/cache.interceptor.ts) and call `super.intercept()` depdending on the config value. – skink Mar 07 '23 at 10:58
  • thanks for the suggestion, however, I won't be initialising the `CacheModule` and the initialisation of `CacheRequestInteceptor` would fail because of missing `CacheManager` dependency. – Nishkarsh Mar 07 '23 at 14:24

0 Answers0