@fmal/http-service
Version:
A HTTP service - orignally @cerebral/http
66 lines (53 loc) • 1.99 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.default = void 0;
var _utils = require("./utils");
var _HttpServiceError = _interopRequireDefault(require("./HttpServiceError"));
var _default = {
method: 'get',
baseUrl: '',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
Accept: 'application/json'
},
onRequest: function onRequest(xhr, options) {
if (options.headers['Content-Type'].indexOf('application/x-www-form-urlencoded') >= 0) {
options.body = (0, _utils.urlEncode)(options.body);
} else if (options.headers['Content-Type'].indexOf('application/json') >= 0) {
options.body = JSON.stringify(options.body);
}
if (typeof window !== 'undefined' && window.FormData && options.body instanceof window.FormData) {
delete options.headers['Content-Type'];
}
xhr.withCredentials = Boolean(options.withCredentials);
Object.keys(options.headers).forEach(function (key) {
xhr.setRequestHeader(key, options.headers[key]);
});
if (options.onRequestCallback) {
options.onRequestCallback(xhr);
}
xhr.send(options.body);
},
onResponse: function onResponse(xhr, resolve, reject, options) {
var result = xhr.responseText;
if (result && (xhr.getResponseHeader('Content-Type') || '').indexOf('application/json') >= 0) {
result = JSON.parse(xhr.responseText);
}
var responseHeaders = (0, _utils.getAllResponseHeaders)(xhr);
if (options && options.onRequestCallback) {
options.onResponseCallback(xhr);
}
if (xhr.status >= 200 && xhr.status < 300) {
resolve({
status: xhr.status,
headers: responseHeaders,
result: result
});
} else {
reject(new _HttpServiceError.default(undefined, xhr.status, responseHeaders, result, xhr.responseText));
}
}
};
exports.default = _default;
module.exports = exports.default;