2

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?

2 Answers 2

2

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

I found the solution. Before all, I made a CustomHttpCacheInterceptor that extends the CacheInterceptor:

@Injectable()
export default class CustomHttpCacheInterceptor extends CacheInterceptor {
  httpServer: any;
  trackBy(context: ExecutionContext): string | undefined {
    const request = context.switchToHttp().getRequest();
    const isGetRequest = request.method === 'GET';
    const requestURl = request.path;
    const excludePaths = ['/my/custom/route'];

    if (
      !isGetRequest ||
      (isGetRequest && excludePaths.some(url => requestURl.includes(url)))
    ) {
      return undefined;
    }
    return requestURl;
  }
}

and then I add it as a global cache interceptor in app.module

//...
  providers: [
    AppService,
    {
      provide: APP_INTERCEPTOR,
      useClass: CustomHttpCacheInterceptor,
    },
  ],
//...
1
  • your concept is great, thanks. However, in order to not change the default behavior, I did this little change: // return requestURl; return super.trackBy(context); Oct 20, 2021 at 12:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.