Search code examples
typescriptcachinginterceptornestjs

How to ignore global cache on some routes in NestJs


I activate the global cache by APP_INTERCEPTOR in my NestJS app. But now, I need to ignore it on some routes. How can I do that?


Solution

  • A different take on what Sadra suggested, instead of the trackBy() method you can override the isRequestCacheable() method on the CacheInterceptor class. It is a little easier.

    @Injectable()
    export class CustomCacheInterceptor extends CacheInterceptor {
    
      excludePaths = ["/my/custom/route"];
    
      isRequestCacheable(context: ExecutionContext): boolean {
        const req = context.switchToHttp().getRequest();
        return (
          this.allowedMethods.includes(req.method) &&
          !this.excludePaths.includes(req.url)
        );
      }
    }