🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more
Socket
Book a DemoInstallSign in
Socket

kefetchup

Package Overview
Dependencies
Maintainers
3
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

kefetchup - npm Package Compare versions

Comparing version

to
1.0.3

dist/kefetchup.es.js

376

dist/kefetchup.es5.js

@@ -0,1 +1,5 @@

'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
/*! *****************************************************************************

@@ -35,38 +39,41 @@ Copyright (c) Microsoft Corporation. All rights reserved.

function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
var ResponseException = /** @class */ (function (_super) {
__extends(ResponseException, _super);
function ResponseException(message, status, data) {
var _this = _super.call(this, message) /* istanbul ignore next: because stupid typescript */ || this;
_this.status = status;
_this.data = data;
Object.setPrototypeOf(_this, ResponseException.prototype);
_this.name = 'ResponseException';
return _this;
}
}
ResponseException.prototype.toString = function () {
return this.name + ': ' + this.message;
};
return ResponseException;
}(Error));
(function (ResponseErrors) {
ResponseErrors[ResponseErrors["BadRequest"] = 400] = "BadRequest";
ResponseErrors[ResponseErrors["Unauthorized"] = 401] = "Unauthorized";
ResponseErrors[ResponseErrors["PaymentRequired"] = 402] = "PaymentRequired";
ResponseErrors[ResponseErrors["Forbidden"] = 403] = "Forbidden";
ResponseErrors[ResponseErrors["NotFound"] = 404] = "NotFound";
ResponseErrors[ResponseErrors["MethodNotAllowed"] = 405] = "MethodNotAllowed";
ResponseErrors[ResponseErrors["NotAcceptable"] = 406] = "NotAcceptable";
ResponseErrors[ResponseErrors["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
ResponseErrors[ResponseErrors["RequestTimeout"] = 408] = "RequestTimeout";
ResponseErrors[ResponseErrors["Conflict"] = 409] = "Conflict";
ResponseErrors[ResponseErrors["Gone"] = 410] = "Gone";
ResponseErrors[ResponseErrors["LengthRequired"] = 411] = "LengthRequired";
ResponseErrors[ResponseErrors["InvalidMedia"] = 415] = "InvalidMedia";
ResponseErrors[ResponseErrors["I'm a teapot"] = 418] = "I'm a teapot";
ResponseErrors[ResponseErrors["Unprocessable"] = 422] = "Unprocessable";
ResponseErrors[ResponseErrors["TooManyRequests"] = 429] = "TooManyRequests";
ResponseErrors[ResponseErrors["ServerError"] = 500] = "ServerError";
ResponseErrors[ResponseErrors["NotImplemented"] = 501] = "NotImplemented";
ResponseErrors[ResponseErrors["BadGateway"] = 502] = "BadGateway";
ResponseErrors[ResponseErrors["ServiceUnavailable"] = 503] = "ServiceUnavailable";
ResponseErrors[ResponseErrors["GatewayTimeout"] = 504] = "GatewayTimeout";
ResponseErrors[ResponseErrors["UnknownError"] = -1] = "UnknownError";
})(exports.ResponseErrors || (exports.ResponseErrors = {}));

@@ -82,18 +89,7 @@ /**

function defaultFetch(url, options) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, new Response(JSON.stringify(defaultFetchHandlerResponseBody(url, options)), defaultFetchHandlerResponseOptions)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
return Promise.resolve(new Response(JSON.stringify(defaultFetchHandlerResponseBody(url, options)), defaultFetchHandlerResponseOptions));
}
var defaultFetchHandlerResponseBody = function (url, options) { return ({
error: 'Default fetch handler response.',
to: url,
options: options
}); };
var defaultFetchHandlerResponseBody = function (url, options) { return (__assign({ error: 'Default-fetch-handler response.' }, (url === undefined ? {} : { to: url }), (options === undefined ? {} : { options: options }))); };
var defaultFetchHandlerResponseOptions = {
status: 418,
status: exports.ResponseErrors["I'm a teapot"],
statusText: '`fetch` missing in `window`'

@@ -103,186 +99,114 @@ };

/**
* Generic API client with default request
* Generic API client with default request.
* Inherit from this class to create a custom extendable api client.
*
* @export
* @class GenericAPIClient
* Can be instantiated on its own for simple singular requests.
*/
var GenericAPIClient = /** @class */ (function () {
function GenericAPIClient(baseURL, clientConfig, handlers) {
/**
* Creates an instance of GenericAPIClient.
* @param {string} [baseURL=''] a base url to prepend to all request urls except for the ones with root urls
* @param {RequestInit} [clientConfig={}] a default config for requests
*/
function GenericAPIClient(baseURL, clientConfig) {
if (baseURL === void 0) { baseURL = ''; }
if (clientConfig === void 0) { clientConfig = {}; }
this.baseURL = baseURL;
this.clientConfig = clientConfig;
var defaultHandlers = {
fetchHandler: window.fetch || defaultFetch,
errorHandler: function (resp) {
throw new ResponseException(handleStatus(resp.status), resp.status, resp);
},
responseHandler: function (resp) { return resp; }
};
this.handlers = handlers ? __assign({}, defaultHandlers, handlers) : defaultHandlers;
this.fetchHandler = window.fetch ? window.fetch.bind(window) : defaultFetch;
this.get = this.alias('get');
this.put = this.alias('put');
this.post = this.alias('post');
this.patch = this.alias('patch');
this.delete = this.alias('delete');
}
/**
* Request method for making requests (duh)
* Makes requests using request factory and resolves config merge conflicts.
*
* @param {string} url Url to make request
* @param {RequestInit} [fetchConfig] Default fetch config
* @param {boolean} [overrideDefaultConfig] Should override client base fetch config or not
* @returns {(Promise<Response | any>)}
* @memberof GenericAPIClient
* @private
*/
GenericAPIClient.prototype.request = function (url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
var response, _a, _b, e_1;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
if (!url.match(/^(\w+:)?\/\//)) {
url = this.baseURL ? new URL(url, this.baseURL).href : url;
}
_c.label = 1;
case 1:
_c.trys.push([1, 3, , 4]);
_b = (_a = this.handlers).responseHandler;
return [4 /*yield*/, this.handlers.fetchHandler(url, overrideDefaultConfig ? fetchConfig : __assign({}, this.clientConfig, fetchConfig))];
case 2:
response = _b.apply(_a, [_c.sent()]);
if (!response.ok) {
return [2 /*return*/, this.handlers.errorHandler(response) || response];
}
return [2 /*return*/, response];
case 3:
e_1 = _c.sent();
throw e_1;
case 4: return [2 /*return*/];
}
});
});
if (overrideDefaultConfig === void 0) { overrideDefaultConfig = false; }
if (!url.match(/^(\w+:)?\/\//)) {
url = this.baseURL ? new URL(url, this.baseURL).href : url;
}
return this.requestFactory(url, overrideDefaultConfig ? fetchConfig : __assign({}, this.clientConfig, fetchConfig), this.fetchHandler);
};
/**
* Fast alias method for request
* Processes the response before allowing to return its value from request function.
* Override this function to provide custom response interception.
* Keep in mind that this function does not have to return a promise.
*
* @protected
* @param {string} method HTTP method (GET, PUT, POST, etc)
* @param {string} url Url to make request
* @param {RequestInit} [fetchConfig] Default fetch config
* @param {boolean} [overrideDefaultConfig] Should override client base fetch config or not
* @returns {(Promise<Response | any>)}
* @param {Response} response the response returned from fetchHandler
* @returns {*} default: the same response
* @memberof GenericAPIClient
*/
GenericAPIClient.prototype.alias = function (method, url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
fetchConfig = fetchConfig || {};
fetchConfig.method = method;
return [4 /*yield*/, this.request(url, fetchConfig, overrideDefaultConfig)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
GenericAPIClient.prototype.responseHandler = function (response) {
if (response.ok) {
return response;
}
else {
throw new ResponseException(GenericAPIClient.handleStatus(response.status), response.status, response);
}
};
GenericAPIClient.prototype.get = function (url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.alias('get', url, fetchConfig, overrideDefaultConfig)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
/**
* Processes the request error before allowing to throw it upstack.
* Override this function to provide custom response error handling.
* Return value instead of throwing for soft error handling.
*
* @protected
* @param e the error catched from the request promise
* @memberof GenericAPIClient
*/
GenericAPIClient.prototype.errorHandler = function (e) {
if (e instanceof ResponseException)
throw e;
else
throw new ResponseException('Unkown Error: ', exports.ResponseErrors.UnknownError, e);
};
GenericAPIClient.prototype.put = function (url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.alias('put', url, fetchConfig, overrideDefaultConfig)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
/**
* A general request factory function.
* Calls request and error handlers, can be used for pre-processing the url and request config before sending.
* Override for a completely custom request & response handling behaviour.
*
* @protected
* @param url a url string that would be passed into the request function
* @param config a request config that would be passed into the request function
* @param requestFunction
*/
GenericAPIClient.prototype.requestFactory = function (url, config, requestFunction) {
var _this = this;
return new Promise(function (resolve, _) { return requestFunction(url, config)
.then(function (r) { return resolve(_this.responseHandler(r)); })
.catch(_this.errorHandler); });
};
GenericAPIClient.prototype.post = function (url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.alias('post', url, fetchConfig, overrideDefaultConfig)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
/**
* Request method alias factory.
* Used to quickly produce alias function for class' decendants.
* Override at your own risk.
*
* @protected
* @param {string} method HTTP method (GET, PUT, POST, etc) to alias
* @returns an alias function for request
* @memberof GenericAPIClient
*/
GenericAPIClient.prototype.alias = function (method) {
return function (url, fetchConfig, overrideDefaultConfig) {
if (fetchConfig === void 0) { fetchConfig = this.clientConfig; }
fetchConfig = fetchConfig;
fetchConfig.method = method ? method.toUpperCase() : (fetchConfig.method || 'GET').toUpperCase();
return this.request(url, fetchConfig, overrideDefaultConfig);
};
};
GenericAPIClient.prototype.patch = function (url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.alias('patch', url, fetchConfig, overrideDefaultConfig)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
GenericAPIClient.handleStatus = function (status) {
if (status === void 0) { status = -1; }
return exports.ResponseErrors[status] || exports.ResponseErrors[-1];
};
GenericAPIClient.prototype.delete = function (url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.alias('delete', url, fetchConfig, overrideDefaultConfig)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
return GenericAPIClient;
}());
var ResponseException = /** @class */ (function (_super) {
__extends(ResponseException, _super);
function ResponseException(message, status, data) {
var _this = _super.call(this, message) /* istanbul ignore next: I DON'T KNOW WHY!!!!! */ || this;
_this.status = status;
_this.data = data;
Object.setPrototypeOf(_this, ResponseException.prototype);
_this.name = 'ResponseExcpetion';
return _this;
}
ResponseException.prototype.toString = function () {
return this.name + ': ' + this.message;
};
return ResponseException;
}(Error));
/**
* Retrieve string from response status
*
* @export
* @param {number} [status=-1] Response status (200, 404, 500, etc)
* @returns {string}
* @inheritdoc
*/
function handleStatus(status) {
if (status === void 0) { status = -1; }
return ResponseErrors[status] || ResponseErrors[-1];
}
var ResponseErrors;
(function (ResponseErrors) {
ResponseErrors[ResponseErrors["BadRequest"] = 400] = "BadRequest";
ResponseErrors[ResponseErrors["Unauthorized"] = 401] = "Unauthorized";
ResponseErrors[ResponseErrors["PaymentRequired"] = 402] = "PaymentRequired";
ResponseErrors[ResponseErrors["Forbidden"] = 403] = "Forbidden";
ResponseErrors[ResponseErrors["NotFound"] = 404] = "NotFound";
ResponseErrors[ResponseErrors["MethodNotAllowed"] = 405] = "MethodNotAllowed";
ResponseErrors[ResponseErrors["NotAcceptable"] = 406] = "NotAcceptable";
ResponseErrors[ResponseErrors["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
ResponseErrors[ResponseErrors["RequestTimeout"] = 408] = "RequestTimeout";
ResponseErrors[ResponseErrors["Conflict"] = 409] = "Conflict";
ResponseErrors[ResponseErrors["Gone"] = 410] = "Gone";
ResponseErrors[ResponseErrors["LengthRequired"] = 411] = "LengthRequired";
ResponseErrors[ResponseErrors["InvalidMedia"] = 415] = "InvalidMedia";
ResponseErrors[ResponseErrors["I'm a teapot"] = 418] = "I'm a teapot";
ResponseErrors[ResponseErrors["Unprocessable"] = 422] = "Unprocessable";
ResponseErrors[ResponseErrors["TooManyRequests"] = 429] = "TooManyRequests";
ResponseErrors[ResponseErrors["ServerError"] = 500] = "ServerError";
ResponseErrors[ResponseErrors["NotImplemented"] = 501] = "NotImplemented";
ResponseErrors[ResponseErrors["BadGateway"] = 502] = "BadGateway";
ResponseErrors[ResponseErrors["ServiceUnavailable"] = 503] = "ServiceUnavailable";
ResponseErrors[ResponseErrors["GatewayTimeout"] = 504] = "GatewayTimeout";
ResponseErrors[ResponseErrors["UnknownError"] = -1] = "UnknownError";
})(ResponseErrors || (ResponseErrors = {}));
var JsonAPIClient = /** @class */ (function (_super) {

@@ -293,15 +217,13 @@ __extends(JsonAPIClient, _super);

}
JsonAPIClient.prototype.request = function (url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.request.call(this, url, fetchConfig, overrideDefaultConfig)];
case 1: return [4 /*yield*/, (_a.sent()).json()];
case 2: return [2 /*return*/, _a.sent()];
}
});
});
/**
* @inheritdoc
*/
JsonAPIClient.prototype.responseHandler = function (resp) {
return resp.json();
};
return JsonAPIClient;
}(GenericAPIClient));
/**
* @inheritdoc
*/
var TextAPIClient = /** @class */ (function (_super) {

@@ -312,12 +234,7 @@ __extends(TextAPIClient, _super);

}
TextAPIClient.prototype.request = function (url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.request.call(this, url, fetchConfig, overrideDefaultConfig)];
case 1: return [4 /*yield*/, (_a.sent()).text()];
case 2: return [2 /*return*/, _a.sent()];
}
});
});
/**
* @inheritdoc
*/
TextAPIClient.prototype.responseHandler = function (resp) {
return resp.text();
};

@@ -327,3 +244,6 @@ return TextAPIClient;

export { JsonAPIClient, TextAPIClient, GenericAPIClient, ResponseException, handleStatus, ResponseErrors };
exports.JsonAPIClient = JsonAPIClient;
exports.TextAPIClient = TextAPIClient;
exports.GenericAPIClient = GenericAPIClient;
exports.ResponseException = ResponseException;
//# sourceMappingURL=kefetchup.es5.js.map

@@ -41,38 +41,41 @@ (function (global, factory) {

function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
var ResponseException = /** @class */ (function (_super) {
__extends(ResponseException, _super);
function ResponseException(message, status, data) {
var _this = _super.call(this, message) /* istanbul ignore next: because stupid typescript */ || this;
_this.status = status;
_this.data = data;
Object.setPrototypeOf(_this, ResponseException.prototype);
_this.name = 'ResponseException';
return _this;
}
}
ResponseException.prototype.toString = function () {
return this.name + ': ' + this.message;
};
return ResponseException;
}(Error));
(function (ResponseErrors) {
ResponseErrors[ResponseErrors["BadRequest"] = 400] = "BadRequest";
ResponseErrors[ResponseErrors["Unauthorized"] = 401] = "Unauthorized";
ResponseErrors[ResponseErrors["PaymentRequired"] = 402] = "PaymentRequired";
ResponseErrors[ResponseErrors["Forbidden"] = 403] = "Forbidden";
ResponseErrors[ResponseErrors["NotFound"] = 404] = "NotFound";
ResponseErrors[ResponseErrors["MethodNotAllowed"] = 405] = "MethodNotAllowed";
ResponseErrors[ResponseErrors["NotAcceptable"] = 406] = "NotAcceptable";
ResponseErrors[ResponseErrors["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
ResponseErrors[ResponseErrors["RequestTimeout"] = 408] = "RequestTimeout";
ResponseErrors[ResponseErrors["Conflict"] = 409] = "Conflict";
ResponseErrors[ResponseErrors["Gone"] = 410] = "Gone";
ResponseErrors[ResponseErrors["LengthRequired"] = 411] = "LengthRequired";
ResponseErrors[ResponseErrors["InvalidMedia"] = 415] = "InvalidMedia";
ResponseErrors[ResponseErrors["I'm a teapot"] = 418] = "I'm a teapot";
ResponseErrors[ResponseErrors["Unprocessable"] = 422] = "Unprocessable";
ResponseErrors[ResponseErrors["TooManyRequests"] = 429] = "TooManyRequests";
ResponseErrors[ResponseErrors["ServerError"] = 500] = "ServerError";
ResponseErrors[ResponseErrors["NotImplemented"] = 501] = "NotImplemented";
ResponseErrors[ResponseErrors["BadGateway"] = 502] = "BadGateway";
ResponseErrors[ResponseErrors["ServiceUnavailable"] = 503] = "ServiceUnavailable";
ResponseErrors[ResponseErrors["GatewayTimeout"] = 504] = "GatewayTimeout";
ResponseErrors[ResponseErrors["UnknownError"] = -1] = "UnknownError";
})(exports.ResponseErrors || (exports.ResponseErrors = {}));

@@ -88,18 +91,7 @@ /**

function defaultFetch(url, options) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, new Response(JSON.stringify(defaultFetchHandlerResponseBody(url, options)), defaultFetchHandlerResponseOptions)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
return Promise.resolve(new Response(JSON.stringify(defaultFetchHandlerResponseBody(url, options)), defaultFetchHandlerResponseOptions));
}
var defaultFetchHandlerResponseBody = function (url, options) { return ({
error: 'Default fetch handler response.',
to: url,
options: options
}); };
var defaultFetchHandlerResponseBody = function (url, options) { return (__assign({ error: 'Default-fetch-handler response.' }, (url === undefined ? {} : { to: url }), (options === undefined ? {} : { options: options }))); };
var defaultFetchHandlerResponseOptions = {
status: 418,
status: exports.ResponseErrors["I'm a teapot"],
statusText: '`fetch` missing in `window`'

@@ -109,185 +101,114 @@ };

/**
* Generic API client with default request
* Generic API client with default request.
* Inherit from this class to create a custom extendable api client.
*
* @export
* @class GenericAPIClient
* Can be instantiated on its own for simple singular requests.
*/
var GenericAPIClient = /** @class */ (function () {
function GenericAPIClient(baseURL, clientConfig, handlers) {
/**
* Creates an instance of GenericAPIClient.
* @param {string} [baseURL=''] a base url to prepend to all request urls except for the ones with root urls
* @param {RequestInit} [clientConfig={}] a default config for requests
*/
function GenericAPIClient(baseURL, clientConfig) {
if (baseURL === void 0) { baseURL = ''; }
if (clientConfig === void 0) { clientConfig = {}; }
this.baseURL = baseURL;
this.clientConfig = clientConfig;
var defaultHandlers = {
fetchHandler: window.fetch || defaultFetch,
errorHandler: function (resp) {
throw new ResponseException(handleStatus(resp.status), resp.status, resp);
},
responseHandler: function (resp) { return resp; }
};
this.handlers = handlers ? __assign({}, defaultHandlers, handlers) : defaultHandlers;
this.fetchHandler = window.fetch ? window.fetch.bind(window) : defaultFetch;
this.get = this.alias('get');
this.put = this.alias('put');
this.post = this.alias('post');
this.patch = this.alias('patch');
this.delete = this.alias('delete');
}
/**
* Request method for making requests (duh)
* Makes requests using request factory and resolves config merge conflicts.
*
* @param {string} url Url to make request
* @param {RequestInit} [fetchConfig] Default fetch config
* @param {boolean} [overrideDefaultConfig] Should override client base fetch config or not
* @returns {(Promise<Response | any>)}
* @memberof GenericAPIClient
* @private
*/
GenericAPIClient.prototype.request = function (url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
var response, _a, _b, e_1;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
if (!url.match(/^(\w+:)?\/\//)) {
url = this.baseURL ? new URL(url, this.baseURL).href : url;
}
_c.label = 1;
case 1:
_c.trys.push([1, 3, , 4]);
_b = (_a = this.handlers).responseHandler;
return [4 /*yield*/, this.handlers.fetchHandler(url, overrideDefaultConfig ? fetchConfig : __assign({}, this.clientConfig, fetchConfig))];
case 2:
response = _b.apply(_a, [_c.sent()]);
if (!response.ok) {
return [2 /*return*/, this.handlers.errorHandler(response) || response];
}
return [2 /*return*/, response];
case 3:
e_1 = _c.sent();
throw e_1;
case 4: return [2 /*return*/];
}
});
});
if (overrideDefaultConfig === void 0) { overrideDefaultConfig = false; }
if (!url.match(/^(\w+:)?\/\//)) {
url = this.baseURL ? new URL(url, this.baseURL).href : url;
}
return this.requestFactory(url, overrideDefaultConfig ? fetchConfig : __assign({}, this.clientConfig, fetchConfig), this.fetchHandler);
};
/**
* Fast alias method for request
* Processes the response before allowing to return its value from request function.
* Override this function to provide custom response interception.
* Keep in mind that this function does not have to return a promise.
*
* @protected
* @param {string} method HTTP method (GET, PUT, POST, etc)
* @param {string} url Url to make request
* @param {RequestInit} [fetchConfig] Default fetch config
* @param {boolean} [overrideDefaultConfig] Should override client base fetch config or not
* @returns {(Promise<Response | any>)}
* @param {Response} response the response returned from fetchHandler
* @returns {*} default: the same response
* @memberof GenericAPIClient
*/
GenericAPIClient.prototype.alias = function (method, url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
fetchConfig = fetchConfig || {};
fetchConfig.method = method;
return [4 /*yield*/, this.request(url, fetchConfig, overrideDefaultConfig)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
GenericAPIClient.prototype.responseHandler = function (response) {
if (response.ok) {
return response;
}
else {
throw new ResponseException(GenericAPIClient.handleStatus(response.status), response.status, response);
}
};
GenericAPIClient.prototype.get = function (url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.alias('get', url, fetchConfig, overrideDefaultConfig)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
/**
* Processes the request error before allowing to throw it upstack.
* Override this function to provide custom response error handling.
* Return value instead of throwing for soft error handling.
*
* @protected
* @param e the error catched from the request promise
* @memberof GenericAPIClient
*/
GenericAPIClient.prototype.errorHandler = function (e) {
if (e instanceof ResponseException)
throw e;
else
throw new ResponseException('Unkown Error: ', exports.ResponseErrors.UnknownError, e);
};
GenericAPIClient.prototype.put = function (url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.alias('put', url, fetchConfig, overrideDefaultConfig)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
/**
* A general request factory function.
* Calls request and error handlers, can be used for pre-processing the url and request config before sending.
* Override for a completely custom request & response handling behaviour.
*
* @protected
* @param url a url string that would be passed into the request function
* @param config a request config that would be passed into the request function
* @param requestFunction
*/
GenericAPIClient.prototype.requestFactory = function (url, config, requestFunction) {
var _this = this;
return new Promise(function (resolve, _) { return requestFunction(url, config)
.then(function (r) { return resolve(_this.responseHandler(r)); })
.catch(_this.errorHandler); });
};
GenericAPIClient.prototype.post = function (url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.alias('post', url, fetchConfig, overrideDefaultConfig)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
/**
* Request method alias factory.
* Used to quickly produce alias function for class' decendants.
* Override at your own risk.
*
* @protected
* @param {string} method HTTP method (GET, PUT, POST, etc) to alias
* @returns an alias function for request
* @memberof GenericAPIClient
*/
GenericAPIClient.prototype.alias = function (method) {
return function (url, fetchConfig, overrideDefaultConfig) {
if (fetchConfig === void 0) { fetchConfig = this.clientConfig; }
fetchConfig = fetchConfig;
fetchConfig.method = method ? method.toUpperCase() : (fetchConfig.method || 'GET').toUpperCase();
return this.request(url, fetchConfig, overrideDefaultConfig);
};
};
GenericAPIClient.prototype.patch = function (url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.alias('patch', url, fetchConfig, overrideDefaultConfig)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
GenericAPIClient.handleStatus = function (status) {
if (status === void 0) { status = -1; }
return exports.ResponseErrors[status] || exports.ResponseErrors[-1];
};
GenericAPIClient.prototype.delete = function (url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.alias('delete', url, fetchConfig, overrideDefaultConfig)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
return GenericAPIClient;
}());
var ResponseException = /** @class */ (function (_super) {
__extends(ResponseException, _super);
function ResponseException(message, status, data) {
var _this = _super.call(this, message) /* istanbul ignore next: I DON'T KNOW WHY!!!!! */ || this;
_this.status = status;
_this.data = data;
Object.setPrototypeOf(_this, ResponseException.prototype);
_this.name = 'ResponseExcpetion';
return _this;
}
ResponseException.prototype.toString = function () {
return this.name + ': ' + this.message;
};
return ResponseException;
}(Error));
/**
* Retrieve string from response status
*
* @export
* @param {number} [status=-1] Response status (200, 404, 500, etc)
* @returns {string}
* @inheritdoc
*/
function handleStatus(status) {
if (status === void 0) { status = -1; }
return exports.ResponseErrors[status] || exports.ResponseErrors[-1];
}
(function (ResponseErrors) {
ResponseErrors[ResponseErrors["BadRequest"] = 400] = "BadRequest";
ResponseErrors[ResponseErrors["Unauthorized"] = 401] = "Unauthorized";
ResponseErrors[ResponseErrors["PaymentRequired"] = 402] = "PaymentRequired";
ResponseErrors[ResponseErrors["Forbidden"] = 403] = "Forbidden";
ResponseErrors[ResponseErrors["NotFound"] = 404] = "NotFound";
ResponseErrors[ResponseErrors["MethodNotAllowed"] = 405] = "MethodNotAllowed";
ResponseErrors[ResponseErrors["NotAcceptable"] = 406] = "NotAcceptable";
ResponseErrors[ResponseErrors["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
ResponseErrors[ResponseErrors["RequestTimeout"] = 408] = "RequestTimeout";
ResponseErrors[ResponseErrors["Conflict"] = 409] = "Conflict";
ResponseErrors[ResponseErrors["Gone"] = 410] = "Gone";
ResponseErrors[ResponseErrors["LengthRequired"] = 411] = "LengthRequired";
ResponseErrors[ResponseErrors["InvalidMedia"] = 415] = "InvalidMedia";
ResponseErrors[ResponseErrors["I'm a teapot"] = 418] = "I'm a teapot";
ResponseErrors[ResponseErrors["Unprocessable"] = 422] = "Unprocessable";
ResponseErrors[ResponseErrors["TooManyRequests"] = 429] = "TooManyRequests";
ResponseErrors[ResponseErrors["ServerError"] = 500] = "ServerError";
ResponseErrors[ResponseErrors["NotImplemented"] = 501] = "NotImplemented";
ResponseErrors[ResponseErrors["BadGateway"] = 502] = "BadGateway";
ResponseErrors[ResponseErrors["ServiceUnavailable"] = 503] = "ServiceUnavailable";
ResponseErrors[ResponseErrors["GatewayTimeout"] = 504] = "GatewayTimeout";
ResponseErrors[ResponseErrors["UnknownError"] = -1] = "UnknownError";
})(exports.ResponseErrors || (exports.ResponseErrors = {}));
var JsonAPIClient = /** @class */ (function (_super) {

@@ -298,15 +219,13 @@ __extends(JsonAPIClient, _super);

}
JsonAPIClient.prototype.request = function (url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.request.call(this, url, fetchConfig, overrideDefaultConfig)];
case 1: return [4 /*yield*/, (_a.sent()).json()];
case 2: return [2 /*return*/, _a.sent()];
}
});
});
/**
* @inheritdoc
*/
JsonAPIClient.prototype.responseHandler = function (resp) {
return resp.json();
};
return JsonAPIClient;
}(GenericAPIClient));
/**
* @inheritdoc
*/
var TextAPIClient = /** @class */ (function (_super) {

@@ -317,12 +236,7 @@ __extends(TextAPIClient, _super);

}
TextAPIClient.prototype.request = function (url, fetchConfig, overrideDefaultConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.request.call(this, url, fetchConfig, overrideDefaultConfig)];
case 1: return [4 /*yield*/, (_a.sent()).text()];
case 2: return [2 /*return*/, _a.sent()];
}
});
});
/**
* @inheritdoc
*/
TextAPIClient.prototype.responseHandler = function (resp) {
return resp.text();
};

@@ -336,3 +250,2 @@ return TextAPIClient;

exports.ResponseException = ResponseException;
exports.handleStatus = handleStatus;

@@ -339,0 +252,0 @@ Object.defineProperty(exports, '__esModule', { value: true });

"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
function __export(m) {

@@ -6,3 +19,39 @@ for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];

Object.defineProperty(exports, "__esModule", { value: true });
__export(require("./clients"));
var genericClient_1 = require("./genericClient");
__export(require("./genericClient"));
__export(require("./errors"));
/**
* @inheritdoc
*/
var JsonAPIClient = /** @class */ (function (_super) {
__extends(JsonAPIClient, _super);
function JsonAPIClient() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @inheritdoc
*/
JsonAPIClient.prototype.responseHandler = function (resp) {
return resp.json();
};
return JsonAPIClient;
}(genericClient_1.GenericAPIClient));
exports.JsonAPIClient = JsonAPIClient;
/**
* @inheritdoc
*/
var TextAPIClient = /** @class */ (function (_super) {
__extends(TextAPIClient, _super);
function TextAPIClient() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @inheritdoc
*/
TextAPIClient.prototype.responseHandler = function (resp) {
return resp.text();
};
return TextAPIClient;
}(genericClient_1.GenericAPIClient));
exports.TextAPIClient = TextAPIClient;
//# sourceMappingURL=index.js.map

@@ -1,1 +0,21 @@

export * from './clients';
import { GenericAPIClient } from './genericClient';
export * from './genericClient';
export * from './errors';
/**
* @inheritdoc
*/
export declare class JsonAPIClient extends GenericAPIClient {
/**
* @inheritdoc
*/
responseHandler(resp: Response): Promise<unknown>;
}
/**
* @inheritdoc
*/
export declare class TextAPIClient extends GenericAPIClient {
/**
* @inheritdoc
*/
responseHandler(resp: Response): Promise<string>;
}
{
"name": "kefetchup",
"version": "1.0.2",
"version": "1.0.3",
"description": "Simple fetch client API to spice up your application",
"keywords": [],
"main": "dist/kefetchup.umd.js",
"module": "dist/kefetchup.es5.js",
"main": "dist/kefetchup.es5.js",
"module": "dist/kefetchup.es.js",
"unpkg": "dist/kefetchup.iife.js",
"typings": "dist/types/kefetchup.d.ts",

@@ -83,2 +84,3 @@ "files": [

"rollup-plugin-typescript2": "^0.13.0",
"rollup-plugin-uglify": "^6.0.0",
"ts-jest": "^22.0.0",

@@ -85,0 +87,0 @@ "ts-node": "^6.0.0",

# KeFetchUp!
[![Build Status](https://img.shields.io/travis/KazanExpress/kefetchup/master.svg?logo=travis)](https://travis-ci.org/KazanExpress/kefetchup) [![Coverage Status](https://coveralls.io/repos/github/KazanExpress/kefetchup/badge.svg?branch=master)](https://coveralls.io/github/KazanExpress/kefetchup?branch=master) [![npm](https://img.shields.io/npm/v/kefetchup.svg?style=flat)](https://www.npmjs.com/package/kefetchup)
![npm bundle size (minified)](https://img.shields.io/bundlephobia/minzip/kefetchup.svg) ![dependencies (minified)](https://img.shields.io/badge/dependencies-none-yellow.svg)
[![Build Status](https://img.shields.io/travis/KazanExpress/kefetchup/master.svg?logo=travis&style=flat-square)](https://travis-ci.org/KazanExpress/kefetchup) [![Coverage status](https://img.shields.io/coveralls/github/KazanExpress/kefetchup/master.svg?style=flat-square)](https://coveralls.io/github/KazanExpress/kefetchup?branch=master) [![npm](https://img.shields.io/npm/v/kefetchup.svg?style=flat-square)](https://www.npmjs.com/package/kefetchup)
[![npm bundle size (minified)](https://img.shields.io/bundlephobia/minzip/kefetchup.svg?style=flat-square)]() [![dependencies (minified)](https://img.shields.io/badge/dependencies-none-yellow.svg?style=flat-square)]()
> Simple fetch client API to spice up your application
`npm i -S kefetchup`
## What is it?
It's just a small and a very extendable fetch client made for our company's purposes.
Feel free to use it.

@@ -1,1 +0,28 @@

export * from './clients';
import { GenericAPIClient } from './genericClient';
export * from './genericClient';
export * from './errors';
/**
* @inheritdoc
*/
export class JsonAPIClient extends GenericAPIClient {
/**
* @inheritdoc
*/
responseHandler(resp: Response): Promise<unknown> {
return resp.json();
}
}
/**
* @inheritdoc
*/
export class TextAPIClient extends GenericAPIClient {
/**
* @inheritdoc
*/
responseHandler(resp: Response) {
return resp.text();
}
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet