50 lines
1.2 KiB
JavaScript
50 lines
1.2 KiB
JavaScript
(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',
|
|
headers: { },
|
|
method: method,
|
|
body: body,
|
|
};
|
|
|
|
Object.keys(additionalHeaders).forEach(function(headerKey) {
|
|
requestOptions.headers[headerKey] = additionalHeaders[headerKey];
|
|
});
|
|
|
|
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 {
|
|
get: function(url, headers) {
|
|
return _fetch(url, 'GET', headers);
|
|
},
|
|
post: function(url, headers, body) {
|
|
return _fetch(url, 'POST', headers, body);
|
|
},
|
|
addResponseInterceptor: addResponseInterceptor,
|
|
}
|
|
})();
|
|
})();
|