http-toolkit
Version:
Well-documented toolkit for making elegant HTTP requests with JavaScript
207 lines (173 loc) • 8.11 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.baseFunctions = void 0;
var _httpMethods = require("../models/http-methods");
var _clientResponse = require("./client-response");
var _errors = require("../errors");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
/**
* Functions to execute requests.
* @name HttpClient.Functions
* @see HttpClientFunctions
* @example const response = myClient.getAsync('/get').bodyToJson().then(data => console.log(data))
*/
/**
* @interface HttpClientFunctions
* @category HttpClient
*/
var prefetches = function prefetches(url, options) {
if (options.prefetchStack && options.prefetchStack.length > 0) {
options.prefetchStack.map(function (func) {
return func(url, options);
});
}
};
var postfetches = function postfetches(url, options, response) {
if (options.postfetchStack && options.postfetchStack.length > 0) {
options.postfetchStack.map(function (func) {
return func(url, options, response);
});
}
return response;
};
var doPromiseUntilTimeout = function doPromiseUntilTimeout(promise, ms) {
return new Promise(function (resolve, reject) {
if (!ms || ms < 1) {
promise.then(function (res) {
return resolve(res);
}, function (err) {
return reject(err);
});
} else {
var timeoutId = setTimeout(function () {
reject(new _errors.ApiError("Timeout reached (".concat(ms, " ms)"), {}, 0, "Timeout reached (".concat(ms, " ms)")));
}, ms);
promise.then(function (res) {
clearTimeout(timeoutId);
resolve(res);
}, function (err) {
clearTimeout(timeoutId);
reject(err);
});
}
});
};
var tryUntil = function tryUntil(originalCaller, retryWhen, maxTries) {
var lastTry = maxTries <= 1;
var retry = function retry() {
return tryUntil(originalCaller, retryWhen, maxTries - 1);
};
return originalCaller().then(function (response) {
return Promise.resolve(Promise.resolve(retryWhen(response)).then(function (shouldRetry) {
if (lastTry || !shouldRetry) {
return response;
}
return retry();
}));
})["catch"](function (e) {
if (lastTry) {
throw e;
}
return retry();
});
};
var base = function base(url, options, method) {
return function () {
var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var _options$method = _objectSpread({}, options, {
method: method
}),
query = _options$method.query,
timeout = _options$method.timeout,
retryWhen = _options$method.retryWhen,
numberOfRetries = _options$method.numberOfRetries,
optionsCopy = _objectWithoutProperties(_options$method, ["query", "timeout", "retryWhen", "numberOfRetries"]);
var fullUrl = path ? url + path : url;
fullUrl += query || '';
prefetches(fullUrl, optionsCopy);
var caller = function caller() {
return doPromiseUntilTimeout(fetch(fullUrl, optionsCopy), timeout);
};
var callerWithRetries = function callerWithRetries() {
return tryUntil(caller, retryWhen, (numberOfRetries || 0) + 1);
};
return (0, _clientResponse.responseFunctions)(callerWithRetries().then(function (response) {
return postfetches(fullUrl, optionsCopy, response);
}));
};
};
var execMethodHelper = function execMethodHelper(url, options) {
return function (method) {
var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
return base(url, options, method)(path);
};
};
var baseFunctions = function baseFunctions(url, options) {
return {
/**
* @function exec
* @description Basic execution of fetch. Requires all options and url to be set beforehand.
* @returns {Promise<Response>}
* @memberOf HttpClientFunctions
*/
exec: function exec() {
return fetch(url, options);
},
/**
* @function execMethod
* @description Executes an arbitrary HttpMethod
* @param {HttpMethods} httpMethod - HTTP method to execute, e.g. 'GET'
* @param {string} [path:''] Path to append at the end of preconfigured url
* @returns {Promise<Response>} a response promise
* @memberOf HttpClientFunctions
*/
execMethod: execMethodHelper(url, options),
/**
* @function getAsync
* @description Executes a GET request and returns the response as a Promise
* @param {string} [path:''] Path to append at the end of preconfigured url
* @returns {Promise<Response>} a response promise
* @memberOf HttpClientFunctions
*/
getAsync: base(url, options, _httpMethods.HttpMethods.GET),
/**
* @function postAsync
* @description Executes a POST request and returns the response as a Promise
* @param {string} [path:''] Path to append at the end of preconfigured url
* @returns {Promise<Response>} a response promise
* @memberOf HttpClientFunctions
*/
postAsync: base(url, options, _httpMethods.HttpMethods.POST),
/**
* @function putAsync
* @description Executes a PUT request and returns the response as a Promise
* @param {string} [path:''] Path to append at the end of preconfigured url
* @returns {Promise<Response>} a response promise
* @memberOf HttpClientFunctions
*/
putAsync: base(url, options, _httpMethods.HttpMethods.PUT),
/**
* @function deleteAsync
* @description Executes a DELETE request and returns the response as a Promise
* @param {string} [path:''] Path to append at the end of preconfigured url
* @returns {Promise<Response>} a response promise
* @memberOf HttpClientFunctions
*/
deleteAsync: base(url, options, _httpMethods.HttpMethods.DELETE),
/**
* @function patchAsync
* @description Executes a PATCH request and returns the response as a Promise
* @param {string} [path:''] Path to append at the end of preconfigured url
* @returns {Promise<Response>} a response promise
* @memberOf HttpClientFunctions
*/
patchAsync: base(url, options, _httpMethods.HttpMethods.PATCH)
};
};
exports.baseFunctions = baseFunctions;
;