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
)?