我有多个使用树存储的自定义树选择器实例,这些树存储可远程加载JSON数据。其中一些请求的等待时间最长为25秒。
那么,有没有一种方法可以在将数据加载以供将来使用后对其进行缓存?
我检查了文档,专门针对LocalStorageProxy,但无法处理JSON数据。
谢谢。
最佳答案
这是一个将根据URL缓存其响应的代理
(function(){
// Key is the url, value is the response from the AJAX request
var requestCache = {};
/**
* A proxy that caches GET requests.
*/
Ext.define('Common.proxy.CachingRestProxy', {
extend: 'Ext.data.proxy.Rest',
alias: 'proxy.cachingrest',
statics: {
clearCache: function() {
requestCache = {};
}
},
createCacheKeyFromRequest: function (request) {
var url = request.getUrl();
var questionMarkIndex = url.indexOf('?');
var queryString = '';
// Don't want to include the cache buster in the cacheKey
if (questionMarkIndex > -1) {
queryString = url.substring(questionMarkIndex);
} url = url.substring(0, questionMarkIndex);
var queryStringObj = Ext.Object.fromQueryString(queryString);
delete queryStringObj[this.cacheString];
var params = Ext.apply(queryStringObj, request.getParams());
return url + JSON.stringify(params);
},
// Overridden to use GET requests from the cache if available
sendRequest: function(request) {
// The cacheKey is just a non readable string that includes all the data that makes up a unique rest call,
// including the url and the param keys and values.
var cacheKey = this.createCacheKeyFromRequest(request);
var cachedResponse = requestCache[cacheKey];
if(cachedResponse){
this.processResponse(true, request.getOperation(), request, cachedResponse);
return request;
} else {
return this.callParent([request]);
}
},
// Overridden to cache GET responses
processResponse: function(success, operation, request, response) {
this.callParent(arguments);
if (success && this.getMethod(request).toUpperCase() == 'GET'){
requestCache[this.createCacheKeyFromRequest(request)] = response;
}
}
});
})();
您就像使用RestProxy一样使用它
proxy: {
type: 'cachingrest',
url: '/compose/api/v1/vocabularies',
...
}