73 lines
1.9 KiB
JavaScript
73 lines
1.9 KiB
JavaScript
(function () {
|
|
'use strict';
|
|
|
|
window.HttpClient = (function() {
|
|
|
|
var _responseInterceptors = [];
|
|
|
|
function addResponseInterceptor(interceptor) {
|
|
if (typeof interceptor === 'function') {
|
|
_responseInterceptors.push(interceptor);
|
|
}
|
|
}
|
|
|
|
function _fetch(options) {
|
|
var requestOptions = {
|
|
credentials: 'same-origin',
|
|
headers: { },
|
|
method: options.method,
|
|
body: options.body,
|
|
};
|
|
|
|
Object.keys(options.headers).forEach(function(headerKey) {
|
|
requestOptions.headers[headerKey] = options.headers[headerKey];
|
|
});
|
|
|
|
return fetch(options.url, requestOptions).then(
|
|
function(response) {
|
|
_responseInterceptors.forEach(function(interceptor) {
|
|
interceptor(response, options);
|
|
});
|
|
return Promise.resolve(response);
|
|
},
|
|
function(error) {
|
|
return Promise.reject(error);
|
|
}
|
|
).catch(function(error) {
|
|
console.error(error);
|
|
});
|
|
}
|
|
|
|
return {
|
|
get: function(args) {
|
|
args.method = 'GET';
|
|
return _fetch(args);
|
|
},
|
|
post: function(args) {
|
|
args.method = 'POST';
|
|
return _fetch(args);
|
|
},
|
|
addResponseInterceptor: addResponseInterceptor,
|
|
ACCEPT: {
|
|
TEXT_HTML: 'text/html',
|
|
JSON: 'application/json',
|
|
},
|
|
}
|
|
})();
|
|
|
|
// HttpClient ships with its own little interceptor to throw an error
|
|
// if the response does not match the expected content-type
|
|
function contentTypeInterceptor(response, options) {
|
|
if (!options || !options.accept) {
|
|
return;
|
|
}
|
|
|
|
var contentType = response.headers.get("content-type");
|
|
if (!contentType.match(options.accept)) {
|
|
throw new Error('Server returned with "' + contentType + '" when "' + options.accept + '" was expected');
|
|
}
|
|
}
|
|
|
|
HttpClient.addResponseInterceptor(contentTypeInterceptor);
|
|
})();
|