debian-mirror-gitlab/app/assets/javascripts/lib/utils/ajax_cache.js

49 lines
1.3 KiB
JavaScript
Raw Normal View History

2017-09-10 17:25:29 +05:30
import Cache from './cache';
class AjaxCache extends Cache {
constructor() {
super();
this.pendingRequests = { };
}
override(endpoint, data) {
this.internalStorage[endpoint] = data;
}
retrieve(endpoint, forceRetrieve) {
if (this.hasData(endpoint) && !forceRetrieve) {
return Promise.resolve(this.get(endpoint));
}
let pendingRequest = this.pendingRequests[endpoint];
if (!pendingRequest) {
pendingRequest = new Promise((resolve, reject) => {
// jQuery 2 is not Promises/A+ compatible (missing catch)
$.ajax(endpoint) // eslint-disable-line promise/catch-or-return
.then(data => resolve(data),
(jqXHR, textStatus, errorThrown) => {
const error = new Error(`${endpoint}: ${errorThrown}`);
error.textStatus = textStatus;
reject(error);
},
);
})
.then((data) => {
this.internalStorage[endpoint] = data;
delete this.pendingRequests[endpoint];
})
.catch((error) => {
delete this.pendingRequests[endpoint];
throw error;
});
this.pendingRequests[endpoint] = pendingRequest;
2017-08-17 22:00:37 +05:30
}
2017-09-10 17:25:29 +05:30
return pendingRequest.then(() => this.get(endpoint));
}
}
export default new AjaxCache();