kalibri
Version:
http service
89 lines (88 loc) • 3.68 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClientService = void 0;
var __1 = require("..");
var ClientService = (function () {
function ClientService() {
this.beforeRequestInterceptor = function () { };
this.afterRequestInterceptor = function () { };
}
ClientService.prototype.setAfterRequestInterceptor = function (afterRequestInterceptor) {
this.afterRequestInterceptor = afterRequestInterceptor;
};
ClientService.prototype.setBeforeRequestInterceptor = function (beforeRequestInterceptor) {
this.beforeRequestInterceptor = beforeRequestInterceptor;
};
ClientService.prototype.parseResponseText = function (xhr) {
var headers = xhr.getAllResponseHeaders();
return headers.includes('json')
? JSON.parse(xhr.responseText)
: xhr.responseText;
};
ClientService.prototype.successResponse = function (xhr) {
return {
ok: xhr.status >= 200 && xhr.status < 300,
status: xhr.status,
statusText: xhr.statusText,
headers: xhr.getAllResponseHeaders(),
data: this.parseResponseText(xhr),
};
};
ClientService.prototype.errorResponse = function (xhr, message) {
if (message === void 0) { message = ''; }
return {
ok: false,
status: xhr.status,
statusText: xhr.statusText,
headers: xhr.getAllResponseHeaders(),
message: message,
data: this.parseResponseText(xhr),
};
};
ClientService.prototype.request = function (requestConfig) {
var _this = this;
var method = requestConfig.method, url = requestConfig.url, headers = requestConfig.headers, timeout = requestConfig.timeout, body = requestConfig.body;
this.beforeRequestInterceptor(requestConfig);
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
if (headers) {
Object.keys(headers).forEach(function (key) {
return xhr.setRequestHeader(key, headers[key]);
});
}
xhr.timeout = timeout;
xhr.onload = function (evt) {
if (xhr.readyState === xhr.DONE) {
if (xhr.status >= 100 && xhr.status < 400) {
var result = _this.successResponse(xhr);
_this.afterRequestInterceptor(result);
return resolve(result);
}
reject(_this.errorResponse(xhr));
_this.afterRequestInterceptor(_this.errorResponse(xhr));
}
};
xhr.onerror = function () {
reject(_this.errorResponse(xhr, 'Failed to make request.'));
};
xhr.ontimeout = function () {
reject(_this.errorResponse(xhr, 'Request took longer than expected.'));
};
var needsToStringify = body instanceof Object && body !== null && !(body instanceof FormData);
if ([__1.REQUEST_METHODS.POST, __1.REQUEST_METHODS.PATCH].includes(method) &&
needsToStringify) {
xhr.setRequestHeader('Content-Type', 'application/json');
}
if (needsToStringify) {
return xhr.send(JSON.stringify(body));
}
else if (!!body) {
return xhr.send(body);
}
xhr.send();
});
};
return ClientService;
}());
exports.ClientService = ClientService;