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?
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,
},
],
//...
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)
);
}
}
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.