gitlab-org--gitlab-foss/app/assets/javascripts/lib/utils/ajax_cache.js

55 lines
1.4 KiB
JavaScript
Raw Normal View History

2017-05-10 18:01:00 -04:00
class AjaxCache {
constructor() {
this.internalStorage = { };
this.pendingRequests = { };
}
2017-05-05 18:47:32 -04:00
get(endpoint) {
return this.internalStorage[endpoint];
2017-05-10 18:01:00 -04:00
}
2017-05-05 18:47:32 -04:00
hasData(endpoint) {
return Object.prototype.hasOwnProperty.call(this.internalStorage, endpoint);
2017-05-10 18:01:00 -04:00
}
remove(endpoint) {
2017-05-05 18:47:32 -04:00
delete this.internalStorage[endpoint];
2017-05-10 18:01:00 -04:00
}
2017-05-05 18:47:32 -04:00
retrieve(endpoint) {
2017-05-10 18:01:00 -04:00
if (this.hasData(endpoint)) {
return Promise.resolve(this.get(endpoint));
2017-05-05 18:47:32 -04:00
}
2017-05-10 18:01:00 -04:00
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;
}
return pendingRequest.then(() => this.get(endpoint));
}
}
export default new AjaxCache();