http-summoner
Version:
Http service
214 lines (213 loc) • 9.6 kB
JavaScript
;
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpSummoner = exports.initConfig = void 0;
var _types_1 = require("./_types");
exports.initConfig = {
baseUrl: '/',
headers: {},
timeout: 10000,
lsHeaders: [],
};
var HttpSummoner = (function () {
function HttpSummoner(_a) {
var _b = _a === void 0 ? exports.initConfig : _a, _c = _b.baseUrl, baseUrl = _c === void 0 ? '/' : _c, _d = _b.headers, headers = _d === void 0 ? {} : _d, _e = _b.timeout, timeout = _e === void 0 ? 10000 : _e, _f = _b.lsHeaders, lsHeaders = _f === void 0 ? [] : _f;
this.config = exports.initConfig;
this.subscribedOnLocalStorage = false;
this.beforeRequestInterceptor = function (requestConfig) { };
this.afterRequestInterceptor = function (successResponse) { };
if (typeof baseUrl !== 'string') {
throw new Error("Expected baseUrl as string but got " + typeof baseUrl);
}
if (typeof headers !== 'object') {
throw new Error("Expected header as object but got " + typeof headers);
}
if (!Array.isArray(lsHeaders)) {
throw new Error("Expected lsHeaders as array but got " + typeof headers);
}
if (typeof timeout !== 'number') {
throw new Error("Expected timeout as number but got " + typeof timeout);
}
this.config = {
baseUrl: baseUrl || exports.initConfig.baseUrl,
headers: headers || exports.initConfig.headers,
timeout: timeout || exports.initConfig.timeout,
lsHeaders: lsHeaders || exports.initConfig.lsHeaders,
};
}
HttpSummoner.prototype.createInstance = function (options) {
return new HttpSummoner(options);
};
HttpSummoner.prototype.getConfig = function () {
return this.config;
};
HttpSummoner.prototype.setBaseUrl = function (url) {
if (url[url.length - 1] !== '/') {
url += '/';
}
this.config.baseUrl = url;
};
HttpSummoner.prototype.addHeaders = function (headers) {
if (typeof headers !== 'object') {
throw new Error("Expected headers as object but got " + typeof headers);
}
for (var _i = 0, _a = Object.entries(headers); _i < _a.length; _i++) {
var _b = _a[_i], key = _b[0], value = _b[1];
this.config.headers[key] = value;
}
};
HttpSummoner.prototype.getHeaders = function () {
return this.config.headers;
};
HttpSummoner.prototype.removeHeader = function (key) {
delete this.config.headers[key];
};
HttpSummoner.prototype.addLsHeaders = function (key) {
if (typeof key !== 'string' && !Array.isArray(key)) {
throw new Error("Expected key as string or array but got " + typeof key);
}
if (typeof key === 'string') {
this.config.lsHeaders.push(key);
}
else {
this.config.lsHeaders = this.config.lsHeaders.concat(key);
}
};
HttpSummoner.prototype.getLsHeaders = function () {
return this.config.lsHeaders;
};
HttpSummoner.prototype.buildUrl = function (path) {
if (path[0] === '/') {
path = path.substring(1, path.length);
}
return this.config.baseUrl + path;
};
HttpSummoner.prototype.withQuery = function (url, params) {
if (params === void 0) { params = {}; }
if (Object.entries(params).length === 0) {
return url;
}
var finalUrl = url + '?';
for (var _i = 0, _a = Object.entries(params); _i < _a.length; _i++) {
var _b = _a[_i], key = _b[0], value = _b[1];
if (finalUrl[finalUrl.length - 1] === '?') {
finalUrl += key + "=" + value;
}
else {
finalUrl += "&" + key + "=" + value;
}
}
return finalUrl;
};
HttpSummoner.prototype.parseResponseText = function (xhr) {
var headers = xhr.getAllResponseHeaders();
return headers.includes('json') ? JSON.parse(xhr.responseText) : xhr.responseText;
};
HttpSummoner.prototype.parseXHRResult = function (xhr) {
return {
ok: xhr.status >= 200 && xhr.status < 300,
status: xhr.status,
statusText: xhr.statusText,
headers: xhr.getAllResponseHeaders(),
data: this.parseResponseText(xhr),
};
};
HttpSummoner.prototype.errorResponse = function (xhr, message) {
if (message === void 0) { message = ''; }
console.log('Error response: ', message, xhr.statusText);
return {
ok: false,
status: xhr.status,
statusText: xhr.statusText,
headers: xhr.getAllResponseHeaders(),
message: message,
data: this.parseResponseText(xhr),
};
};
HttpSummoner.prototype.createFinalConfig = function (_a) {
var _b = _a.url, url = _b === void 0 ? '' : _b, _c = _a.method, method = _c === void 0 ? _types_1.REQUEST_METHODS.GET : _c, _d = _a.headers, headers = _d === void 0 ? {} : _d, _e = _a.query, query = _e === void 0 ? {} : _e, _f = _a.timeout, timeout = _f === void 0 ? this.config.timeout || 10000 : _f, _g = _a.body, body = _g === void 0 ? {} : _g;
var finalUrl = this.withQuery(this.buildUrl(url), query);
var lsHeaders = {};
this.config.lsHeaders.forEach(function (key) {
lsHeaders[key] = JSON.parse(localStorage.getItem(key) || '');
});
return {
method: method,
timeout: timeout,
body: body,
url: finalUrl,
headers: __assign(__assign(__assign({}, this.config.headers), lsHeaders), headers),
};
};
HttpSummoner.prototype.setAfterRequestInterceptor = function (afterRequestInterceptor) {
this.afterRequestInterceptor = afterRequestInterceptor;
};
HttpSummoner.prototype.setBeforeRequestInterceptor = function (beforeRequestInterceptor) {
this.beforeRequestInterceptor = beforeRequestInterceptor;
};
HttpSummoner.prototype.request = function (requestConfig) {
var _this = this;
var finalConfig = this.createFinalConfig(requestConfig);
this.beforeRequestInterceptor(finalConfig);
var method = finalConfig.method, url = finalConfig.url, headers = finalConfig.headers, timeout = finalConfig.timeout, body = finalConfig.body;
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.parseXHRResult(xhr);
_this.afterRequestInterceptor(result);
return resolve(result);
}
reject(_this.errorResponse(xhr));
}
};
xhr.onerror = function (evt) {
reject(_this.errorResponse(xhr, 'Failed to make request.'));
};
xhr.ontimeout = function (evt) {
reject(_this.errorResponse(xhr, 'Request took longer than expected.'));
};
if ([_types_1.REQUEST_METHODS.POST, _types_1.REQUEST_METHODS.PATCH].includes(method)) {
xhr.setRequestHeader('Content-Type', 'application/json');
}
if (!!body) {
return xhr.send(JSON.stringify(body));
}
xhr.send();
});
};
HttpSummoner.prototype.get = function (url, requestConfig) {
if (requestConfig === void 0) { requestConfig = {}; }
return this.request(__assign(__assign({}, requestConfig), { url: url, method: _types_1.REQUEST_METHODS.GET }));
};
HttpSummoner.prototype.post = function (url, requestConfig) {
if (requestConfig === void 0) { requestConfig = {}; }
return this.request(__assign(__assign({}, requestConfig), { url: url, method: _types_1.REQUEST_METHODS.POST }));
};
HttpSummoner.prototype.patch = function (url, requestConfig) {
if (requestConfig === void 0) { requestConfig = {}; }
return this.request(__assign(__assign({}, requestConfig), { url: url, method: _types_1.REQUEST_METHODS.PATCH }));
};
HttpSummoner.prototype.delete = function (url, requestConfig) {
if (requestConfig === void 0) { requestConfig = {}; }
return this.request(__assign(__assign({}, requestConfig), { url: url, method: _types_1.REQUEST_METHODS.DELETE }));
};
return HttpSummoner;
}());
exports.HttpSummoner = HttpSummoner;