2017-05-16 06:01:23 -04:00
|
|
|
import Cache from './cache';
|
|
|
|
|
|
|
|
class AjaxCache extends Cache {
|
2017-05-10 18:01:00 -04:00
|
|
|
constructor() {
|
2017-05-16 06:01:23 -04:00
|
|
|
super();
|
2017-05-10 18:01:00 -04:00
|
|
|
this.pendingRequests = { };
|
|
|
|
}
|
|
|
|
|
2017-08-02 05:27:24 -04:00
|
|
|
override(endpoint, data) {
|
|
|
|
this.internalStorage[endpoint] = data;
|
|
|
|
}
|
|
|
|
|
2017-06-05 05:12:15 -04:00
|
|
|
retrieve(endpoint, forceRetrieve) {
|
|
|
|
if (this.hasData(endpoint) && !forceRetrieve) {
|
2017-05-10 18:01:00 -04:00
|
|
|
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();
|