add interceptors to http client

This commit is contained in:
Felix Hamann 2019-05-09 21:54:50 +02:00
parent 6a68e1de79
commit 373c8d213d

View File

@ -1,8 +1,16 @@
(function collonadeClosure() {
(function () {
'use strict';
window.HttpClient = (function() {
var _responseInterceptors = [];
function addResponseInterceptor(interceptor) {
if (typeof interceptor === 'function') {
_responseInterceptors.push(interceptor);
}
}
function _fetch(url, method, additionalHeaders, body) {
var requestOptions = {
credentials: 'same-origin',
@ -15,7 +23,17 @@
requestOptions.headers[headerKey] = additionalHeaders[headerKey];
});
return fetch(url, requestOptions);
return fetch(url, requestOptions).then(
function(response) {
_responseInterceptors.forEach(function(interceptor) { interceptor(response); });
return Promise.resolve(response);
},
function(error) {
return Promise.reject(error);
}
).catch(function(error) {
console.error(error);
});
}
return {
@ -25,6 +43,7 @@
post: function(url, headers, body) {
return _fetch(url, 'POST', headers, body);
},
addResponseInterceptor: addResponseInterceptor,
}
})();
})();