如何在 NestJs 中忽略某些路由上的全局缓存
How to ignore global cache on some routes in NestJs
我在我的 NestJS 应用程序中通过 APP_INTERCEPTOR
激活了全局缓存。
但是现在,我需要在某些路线上忽略它。
我该怎么做?
我找到了解决方案。首先,我做了一个扩展 CacheInterceptor
:
的 CustomHttpCacheInterceptor
@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;
}
}
然后我将它添加为 app.module
中的全局缓存拦截器
//...
providers: [
AppService,
{
provide: APP_INTERCEPTOR,
useClass: CustomHttpCacheInterceptor,
},
],
//...
我在我的 NestJS 应用程序中通过 APP_INTERCEPTOR
激活了全局缓存。
但是现在,我需要在某些路线上忽略它。
我该怎么做?
我找到了解决方案。首先,我做了一个扩展 CacheInterceptor
:
CustomHttpCacheInterceptor
@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;
}
}
然后我将它添加为 app.module
//...
providers: [
AppService,
{
provide: APP_INTERCEPTOR,
useClass: CustomHttpCacheInterceptor,
},
],
//...