我目前在整个应用程序中都使用http缓存。这很棒,而且任何人都可以轻松地对请求进行缓存,即
return this
.$http({
url: "/api/vehicles",
method: "GET",
cache: true,
params: { minsToLive: 30, invalidateCache: invalidateCache }
})
然后我有一个cacheInterceptorService
(在下面)来处理无效等。
这一切正常,但是,每次访问高速缓存时,使用内置的$http
高速缓存都会导致昂贵的JSON解析损失。这是因为缓存实际上存储了$http
响应,而不是解析的JSON。我的一些有效负载很大,并且JSON解析时间越来越长。
所以我的问题是,如何缓存JSON响应而不是整个GET响应来否定解析时间?理想情况下,我希望在拦截器级别进行更改,以便无需更改单个服务即可支持新的缓存。
export class CacheInterceptor {
httpTimeToLiveCache: [string, number] = [] as any;
static Factory($cacheFactory: angular.ICacheFactoryService) {
return new CacheInterceptor($cacheFactory);
}
constructor(private $cacheFactory: angular.ICacheFactoryService) {
}
request = (config: angular.IRequestConfig) => {
if (config.params) {
if (config.params.invalidateCache) {
this.invalidateCache(config);
}
else if (config.params.minsToLive) {
config.cache = true;
const n = config.params.minsToLive * 60 * 1000; // convert from minutes into milliseconds
if (new Date().getTime() - (this.httpTimeToLiveCache[config.url] as any || 0) > n) {
this.invalidateCache(config);
}
}
}
this.removeCacheVariables(config);
return config;
}
private invalidateCache(config: angular.IRequestConfig) {
this.removeCacheVariables(config);
this.$cacheFactory.get("$http").remove(config.url);
this.httpTimeToLiveCache[config.url] = new Date().getTime();
}
private removeCacheVariables(config: angular.IRequestConfig) {
if (config.params) {
delete config.params.invalidateCache;
delete config.params.minsToLive;
}
}
}
CacheInterceptor.Factory.$inject = ["$cacheFactory"];