Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

api-reach

Package Overview
Dependencies
Maintainers
1
Versions
38
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

api-reach - npm Package Compare versions

Comparing version 0.1.1 to 0.2.0

7

CHANGELOG.md

@@ -6,2 +6,9 @@ All notable changes to this project will be documented in this file.

## [0.2.0] - 2019-02-16
### Fixed
- `base` parameter not working, probably other unnoticed bugs
### Changed
- babel settings, making it much more less compatible with old browsers (requires es6 + async/await)
## [0.1.1] - 2019-02-16

@@ -8,0 +15,0 @@ ### Added

14

dist/errors.js

@@ -12,15 +12,15 @@ "use strict";

var createError = _dist.default.default || _dist.default; // to let it work as bare es modules and common js with babel
const createError = _dist.default.default || _dist.default; // to let it work as bare es modules and common js with babel
var HttpError = createError("HttpError");
const HttpError = createError("HttpError");
exports.HttpError = HttpError;
var ClientHttpError = createError("ClientHttpError", HttpError);
const ClientHttpError = createError("ClientHttpError", HttpError);
exports.ClientHttpError = ClientHttpError;
var ServerHttpError = createError("ServerHttpError", HttpError);
const ServerHttpError = createError("ServerHttpError", HttpError);
exports.ServerHttpError = ServerHttpError;
var TimeoutHttpError = createError("TimeoutHttpError", ServerHttpError);
const TimeoutHttpError = createError("TimeoutHttpError", ServerHttpError);
exports.TimeoutHttpError = TimeoutHttpError;
var AbortedHttpError = createError("AbortedHttpError", ClientHttpError);
const AbortedHttpError = createError("AbortedHttpError", ClientHttpError);
exports.AbortedHttpError = AbortedHttpError;
var ResponseDataTypeMismatchError = createError("ResponseDataTypeMismatchError");
const ResponseDataTypeMismatchError = createError("ResponseDataTypeMismatchError");
exports.ResponseDataTypeMismatchError = ResponseDataTypeMismatchError;

@@ -24,21 +24,8 @@ "use strict";

var _request3 = _interopRequireDefault(require("./request"));
var _request = _interopRequireDefault(require("./request"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var stringify = _qs.default.stringify;
// eslint-disable-line max-lines
const stringify = _qs.default.stringify;
// Types:

@@ -53,3 +40,3 @@ // text

*/
var contentTypeMap = {
const contentTypeMap = {
json: "application/json; charset=utf-8",

@@ -68,5 +55,5 @@ text: "application/x-www-form-urlencoded"

var URLParser = URL;
let URLParser = URL;
var safeUrlParse = function safeUrlParse(url) {
const safeUrlParse = url => {
try {

@@ -80,13 +67,17 @@ return new URLParser(url);

var globalOptions = {
const globalOptions = {
// eslint-disable-line object-shorthand
retry: 1,
retryInterval: 100,
retryPolicy: function retryPolicy(_ref) {
var count = _ref.count;
retryPolicy({
count
}) {
return count <= this.retry;
},
retryWaitPolicy: function retryWaitPolicy() {
retryWaitPolicy() {
return this.retryInterval;
},
timeout: 30000,

@@ -96,7 +87,3 @@ totalTimeout: 60000

var wait = function wait(time) {
return new Promise(function (resolve) {
return setTimeout(resolve, time);
});
};
const wait = time => new Promise(resolve => setTimeout(resolve, time));
/**

@@ -107,11 +94,7 @@ * @class ApiClient

var ApiClient =
/*#__PURE__*/
function () {
class ApiClient {
/**
* @param {ApiOptions} options
*/
function ApiClient(options) {
_classCallCheck(this, ApiClient);
constructor(options) {
// @todo validate them?

@@ -121,350 +104,248 @@ this._options = options || {};

_createClass(ApiClient, [{
key: "_getType",
value: function _getType(options) {
return options.type || this._options.type || "json"; // @todo do not hardcode type here
}
}, {
key: "_getContentType",
value: function _getContentType(options) {
var type = this._getType(options);
_getType(options) {
return options.type || this._options.type || "json"; // @todo do not hardcode type here
}
return contentTypeMap[type]; // @todo handle unknown type
}
}, {
key: "_getBody",
value: function _getBody(options, body) {
var type = this._getType(options);
_getContentType(options) {
const type = this._getType(options);
if (type === "json") {
return JSON.stringify(body);
}
return contentTypeMap[type]; // @todo handle unknown type
}
if (type === "text") {
if (typeof body === "string") {
return body;
}
_getBody(options, body) {
const type = this._getType(options);
return stringify(body);
}
return ""; // @todo throw?
if (type === "json") {
return JSON.stringify(body);
}
}, {
key: "_buildFetchOptions",
value: function _buildFetchOptions(options, body) {
var globalHeaders = this._options.headers;
var localHeaders = options.headers;
var contentType = {};
var bodyOptions = {};
if (body != null) {
contentType["Content-Type"] = this._getContentType(options);
bodyOptions.body = this._getBody(options, body);
if (type === "text") {
if (typeof body === "string") {
return body;
}
return _objectSpread({}, globalOptions, this._options, options, bodyOptions, {
headers: _objectSpread({}, globalHeaders, localHeaders, contentType)
});
return stringify(body);
}
}, {
key: "_buildUrlBase",
value: function _buildUrlBase(url, base) {
var parsedBase = safeUrlParse(base);
if (!parsedBase || !parsedBase.host) {
// @todo throw an Error ?
return url;
}
return ""; // @todo throw?
}
var parsedUrl = safeUrlParse(url);
_buildFetchOptions(options, body) {
const globalHeaders = this._options.headers;
const localHeaders = options.headers;
const contentType = {};
const bodyOptions = {};
if (parsedUrl && parsedUrl.base) {
// base is valid full url and given url is also full url
throw new Error("Cannot use absolute url with base url."); // @todo throw custom type?
}
return (0, _urlJoin.default)(base, url);
if (body != null) {
contentType["Content-Type"] = this._getContentType(options);
bodyOptions.body = this._getBody(options, body);
}
}, {
key: "_buildUrl",
value: function _buildUrl(originalUrl, queryParams, fetchOptions) {
var url = this._buildUrlBase(originalUrl, fetchOptions.base);
if (!queryParams) {
return url;
return { // @todo filter only known options
...globalOptions,
...this._options,
...options,
...bodyOptions,
headers: { ...globalHeaders,
// @todo handle same header but with different case
...localHeaders,
// @todo handle multiple headers
...contentType
}
};
}
var hasQS = url.includes("?");
var appendChar = hasQS ? "&" : "?"; // @todo extract existing query params from string and include for stringify ?
_buildUrlBase(url, base) {
const parsedBase = safeUrlParse(base);
return url + appendChar + stringify(queryParams);
if (!parsedBase || !parsedBase.host) {
// @todo throw an Error ?
return url;
}
}, {
key: "get",
value: function get(url, queryParams, options) {
return this.request("GET", url, queryParams, null, options);
}
}, {
key: "post",
value: function post(url, queryParams, body, options) {
return this.request("POST", url, queryParams, body, options);
}
}, {
key: "patch",
value: function patch(url, queryParams, body, options) {
return this.request("PATCH", url, queryParams, body, options);
}
}, {
key: "delete",
value: function _delete(url, queryParams, body, options) {
return this.request("DELETE", url, queryParams, body, options);
}
}, {
key: "request",
value: function request(method, originalUrl, queryParams, body) {
var _this = this;
var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
// eslint-disable-line max-lines-per-function
var start = Date.now();
const parsedUrl = safeUrlParse(url);
var fineOptions = this._buildFetchOptions(options || {}, body);
if (parsedUrl && parsedUrl.base) {
// base is valid full url and given url is also full url
throw new Error("Cannot use absolute url with base url."); // @todo throw custom type?
}
var currentController,
globalTimeout,
aborted = false,
isGlobalTimeouted = false;
return (0, _urlJoin.default)(base, url);
}
var globalBreak = function globalBreak() {
isGlobalTimeouted = true;
future.abort(); // eslint-disable-line no-use-before-define
};
_buildUrl(originalUrl, queryParams, fetchOptions) {
const url = this._buildUrlBase(originalUrl, fetchOptions.base);
var future = new Promise(function (resolve, reject) {
// eslint-disable-line max-lines-per-function
var count = 0,
lastError = null;
return _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee() {
var isTimeouted, singleTimeout, waitTime, errorDetails, msg, _errorDetails, _msg;
if (!queryParams) {
return url;
}
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!fineOptions.retryPolicy({
count: ++count
})) {
_context.next = 40;
break;
}
const hasQS = url.includes("?");
const appendChar = hasQS ? "&" : "?"; // @todo extract existing query params from string and include for stringify ?
isTimeouted = false;
currentController = new _abortController.default();
singleTimeout = new _Timeout.default(function () {
// eslint-disable-line no-loop-func
isTimeouted = true;
currentController.abort();
}, fineOptions.timeout);
_context.prev = 4;
return url + appendChar + stringify(queryParams);
}
if (!(count > 1)) {
_context.next = 14;
break;
}
get(url, queryParams, options) {
return this.request("GET", url, queryParams, null, options);
}
waitTime = fineOptions.retryWaitPolicy({
count: count
});
post(url, queryParams, body, options) {
return this.request("POST", url, queryParams, body, options);
}
if (!(!globalTimeout || fineOptions.totalTimeout > Date.now() - start + waitTime)) {
_context.next = 12;
break;
}
patch(url, queryParams, body, options) {
return this.request("PATCH", url, queryParams, body, options);
}
_context.next = 10;
return wait(waitTime);
delete(url, queryParams, body, options) {
return this.request("DELETE", url, queryParams, body, options);
}
case 10:
_context.next = 14;
break;
request(method, originalUrl, queryParams, body, options = {}) {
// eslint-disable-line max-lines-per-function
const start = Date.now();
case 12:
globalTimeout.stop();
globalBreak();
const fineOptions = this._buildFetchOptions(options || {}, body);
case 14:
if (!aborted) {
_context.next = 19;
break;
}
let currentController,
globalTimeout,
aborted = false,
isGlobalTimeouted = false;
errorDetails = {
tries: count - 1,
while: "waiting",
timeout: isTimeouted,
globalTimeout: isGlobalTimeouted
};
msg = "Request aborted " + JSON.stringify(errorDetails);
lastError = new _errors.AbortedHttpError(msg, lastError, errorDetails);
return _context.abrupt("break", 40);
const globalBreak = () => {
isGlobalTimeouted = true;
future.abort(); // eslint-disable-line no-use-before-define
};
case 19:
singleTimeout.start();
_context.next = 22;
return _this._request(method, originalUrl, queryParams, body, options, currentController.signal);
const future = new Promise((resolve, reject) => {
// eslint-disable-line max-lines-per-function
let count = 0,
lastError = null;
return (async () => {
// eslint-disable-line max-statements, max-lines-per-function
while (fineOptions.retryPolicy({
count: ++count
})) {
let isTimeouted = false;
currentController = new _abortController.default();
const singleTimeout = new _Timeout.default(() => {
// eslint-disable-line no-loop-func
isTimeouted = true;
currentController.abort();
}, fineOptions.timeout);
case 22:
return _context.abrupt("return", _context.sent);
try {
if (count > 1) {
const waitTime = fineOptions.retryWaitPolicy({
count
});
case 25:
_context.prev = 25;
_context.t0 = _context["catch"](4);
if (!globalTimeout || fineOptions.totalTimeout > Date.now() - start + waitTime) {
await wait(waitTime);
} else {
globalTimeout.stop();
globalBreak();
}
}
if (!(_context.t0.name === "AbortError")) {
_context.next = 34;
break;
}
if (aborted) {
const errorDetails = {
tries: count - 1,
while: "waiting",
timeout: isTimeouted,
globalTimeout: isGlobalTimeouted
};
const msg = `Request aborted ` + JSON.stringify(errorDetails);
lastError = new _errors.AbortedHttpError(msg, lastError, errorDetails);
break;
}
_errorDetails = {
tries: count,
while: "connection",
timeout: isTimeouted,
globalTimeout: isGlobalTimeouted
};
_msg = "Request aborted " + JSON.stringify(_errorDetails);
lastError = new _errors.AbortedHttpError(_msg, lastError, _errorDetails); // it should not try again if:
// globally timeouted
// aborted by user (abort didn't happened via timeout)
singleTimeout.start();
return await this._request(method, originalUrl, queryParams, body, fineOptions, currentController.signal);
} catch (e) {
if (e.name === "AbortError") {
const errorDetails = {
tries: count,
while: "connection",
timeout: isTimeouted,
globalTimeout: isGlobalTimeouted
};
const msg = `Request aborted ` + JSON.stringify(errorDetails);
lastError = new _errors.AbortedHttpError(msg, lastError, errorDetails); // it should not try again if:
// globally timeouted
// aborted by user (abort didn't happened via timeout)
if (!(isGlobalTimeouted || !isTimeouted)) {
_context.next = 33;
break;
}
if (isGlobalTimeouted || !isTimeouted) {
break;
}
return _context.abrupt("break", 40);
continue;
}
case 33:
return _context.abrupt("continue", 0);
lastError = e;
} finally {
singleTimeout.stop();
}
}
case 34:
lastError = _context.t0;
throw lastError ? lastError : new Error("No error thrown"); // @todo what to do if no error saved?
})().then(resolve, reject);
}).finally(() => {
globalTimeout && globalTimeout.stop(); // eslint-disable-line no-use-before-define
});
case 35:
_context.prev = 35;
singleTimeout.stop();
return _context.finish(35);
future.abort = () => {
aborted = true;
currentController && currentController.abort();
};
case 38:
_context.next = 0;
break;
case 40:
throw lastError ? lastError : new Error("No error thrown");
case 41:
case "end":
return _context.stop();
}
}
}, _callee, this, [[4, 25, 35, 38]]);
}))().then(resolve, reject);
}).finally(function () {
globalTimeout && globalTimeout.stop(); // eslint-disable-line no-use-before-define
});
future.abort = function () {
aborted = true;
currentController && currentController.abort();
};
if (fineOptions.totalTimeout > 0 && Number.isFinite(fineOptions.totalTimeout)) {
globalTimeout = new _Timeout.default(globalBreak, fineOptions.totalTimeout, true);
}
return future;
if (fineOptions.totalTimeout > 0 && Number.isFinite(fineOptions.totalTimeout)) {
globalTimeout = new _Timeout.default(globalBreak, fineOptions.totalTimeout, true);
}
}, {
key: "_request",
value: function () {
var _request2 = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee2(method, originalUrl, queryParams, body, options, signal) {
var fetchOptions, url, request, result, type, response;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
fetchOptions = _objectSpread({}, options, {
method: method.toUpperCase()
});
url = this._buildUrl(originalUrl, queryParams, fetchOptions);
request = new _request3.default(url, fetchOptions, originalUrl, queryParams);
_context2.next = 5;
return (0, _nodeFetch.default)(request.url, _objectSpread({}, request.options, {
signal: signal
}));
case 5:
result = _context2.sent;
type = this._getType(options || {});
_context2.next = 9;
return (0, _response.default)(result, type, request);
return future;
}
case 9:
response = _context2.sent;
async _request(method, originalUrl, queryParams, body, options, signal) {
const fetchOptions = { ...options,
method: method.toUpperCase()
};
if (!("rawBody" in response)) {
_context2.next = 12;
break;
}
const url = this._buildUrl(originalUrl, queryParams, fetchOptions);
throw new _errors.ResponseDataTypeMismatchError("Unexpected type of data received", {
response: response,
expectedType: type
});
const request = new _request.default(url, fetchOptions, originalUrl, queryParams);
const result = await (0, _nodeFetch.default)(request.url, { ...request.options,
signal
});
case 12:
if (!(0, _matchStatus.isClientError)(result.status)) {
_context2.next = 14;
break;
}
const type = this._getType(options || {});
throw new _errors.ClientHttpError(result.statusText, {
response: response
});
const response = await (0, _response.default)(result, type, request);
case 14:
if (!(0, _matchStatus.isServerError)(result.status)) {
_context2.next = 16;
break;
}
if ("rawBody" in response) {
throw new _errors.ResponseDataTypeMismatchError("Unexpected type of data received", {
response: response,
expectedType: type
});
}
throw new _errors.ServerHttpError(result.statusText, {
response: response
});
if ((0, _matchStatus.isClientError)(result.status)) {
throw new _errors.ClientHttpError(result.statusText, {
response
});
}
case 16:
return _context2.abrupt("return", response);
if ((0, _matchStatus.isServerError)(result.status)) {
throw new _errors.ServerHttpError(result.statusText, {
response
});
}
case 17:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
return response;
}
return function _request(_x, _x2, _x3, _x4, _x5, _x6) {
return _request2.apply(this, arguments);
};
}()
}]);
}
return ApiClient;
}();
ApiClient.configure = function (options) {
ApiClient.configure = options => {
URLParser = options.URL;

@@ -471,0 +352,0 @@ };

@@ -8,14 +8,13 @@ "use strict";

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
class Request {
constructor(url, options, originalUrl, queryParams) {
this.options = options;
this.url = url;
this.originalUrl = originalUrl;
this.queryParams = queryParams;
}
var Request = function Request(url, options, originalUrl, queryParams) {
_classCallCheck(this, Request);
}
this.options = options;
this.url = url;
this.originalUrl = originalUrl;
this.queryParams = queryParams;
};
var _default = Request;
exports.default = _default;

@@ -8,80 +8,37 @@ "use strict";

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
const decodeData = async (response, type) => {
if (type === "json") {
// @todo do not hardcode type
const text = await response.text();
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
try {
const body = JSON.parse(text);
return {
body,
type
};
} catch (e) {
// eslint-disable-line no-unused-vars
return {
body: {},
rawBody: text,
type: "text"
};
}
}
var decodeData =
/*#__PURE__*/
function () {
var _ref = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(response, type) {
var text, body;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!(type === "json")) {
_context.next = 12;
break;
}
if (type === "text") {
return {
body: await response.text(),
type: type
};
}
_context.next = 3;
return response.text();
case 3:
text = _context.sent;
_context.prev = 4;
body = JSON.parse(text);
return _context.abrupt("return", {
body: body,
type: type
});
case 9:
_context.prev = 9;
_context.t0 = _context["catch"](4);
return _context.abrupt("return", {
body: {},
rawBody: text,
type: "text"
});
case 12:
if (!(type === "text")) {
_context.next = 18;
break;
}
_context.next = 15;
return response.text();
case 15:
_context.t1 = _context.sent;
_context.t2 = type;
return _context.abrupt("return", {
body: _context.t1,
type: _context.t2
});
case 18:
return _context.abrupt("return", {
body: null,
type: null
});
case 19:
case "end":
return _context.stop();
}
}
}, _callee, this, [[4, 9]]);
}));
return function decodeData(_x, _x2) {
return _ref.apply(this, arguments);
return {
body: null,
type: null
};
}();
};
var _default = decodeData;
exports.default = _default;

@@ -12,169 +12,57 @@ "use strict";

var _statusTypeToResponse;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
class Response {
constructor(result, data, request) {
Object.assign(this, data);
this.status = result.status;
this.statusText = result.statusText;
this.headers = result.headers;
this.request = request;
}
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
}
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 _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Response = function Response(result, data, request) {
_classCallCheck(this, Response);
Object.assign(this, data);
this.status = result.status;
this.statusText = result.statusText;
this.headers = result.headers;
this.request = request;
};
exports.Response = Response;
var AbortedResponse =
/*#__PURE__*/
function (_Response) {
_inherits(AbortedResponse, _Response);
class AbortedResponse extends Response {}
function AbortedResponse() {
_classCallCheck(this, AbortedResponse);
return _possibleConstructorReturn(this, _getPrototypeOf(AbortedResponse).apply(this, arguments));
}
return AbortedResponse;
}(Response);
exports.AbortedResponse = AbortedResponse;
var InformationalResponse =
/*#__PURE__*/
function (_Response2) {
_inherits(InformationalResponse, _Response2);
class InformationalResponse extends Response {}
function InformationalResponse() {
_classCallCheck(this, InformationalResponse);
return _possibleConstructorReturn(this, _getPrototypeOf(InformationalResponse).apply(this, arguments));
}
return InformationalResponse;
}(Response);
exports.InformationalResponse = InformationalResponse;
var SuccessResponse =
/*#__PURE__*/
function (_Response3) {
_inherits(SuccessResponse, _Response3);
class SuccessResponse extends Response {}
function SuccessResponse() {
_classCallCheck(this, SuccessResponse);
return _possibleConstructorReturn(this, _getPrototypeOf(SuccessResponse).apply(this, arguments));
}
return SuccessResponse;
}(Response);
exports.SuccessResponse = SuccessResponse;
var RedirectResponse =
/*#__PURE__*/
function (_Response4) {
_inherits(RedirectResponse, _Response4);
class RedirectResponse extends Response {}
function RedirectResponse() {
_classCallCheck(this, RedirectResponse);
return _possibleConstructorReturn(this, _getPrototypeOf(RedirectResponse).apply(this, arguments));
}
return RedirectResponse;
}(Response);
exports.RedirectResponse = RedirectResponse;
var ClientErrorResponse =
/*#__PURE__*/
function (_Response5) {
_inherits(ClientErrorResponse, _Response5);
class ClientErrorResponse extends Response {}
function ClientErrorResponse() {
_classCallCheck(this, ClientErrorResponse);
return _possibleConstructorReturn(this, _getPrototypeOf(ClientErrorResponse).apply(this, arguments));
}
return ClientErrorResponse;
}(Response);
exports.ClientErrorResponse = ClientErrorResponse;
var ServerErrorResponse =
/*#__PURE__*/
function (_Response6) {
_inherits(ServerErrorResponse, _Response6);
class ServerErrorResponse extends Response {}
function ServerErrorResponse() {
_classCallCheck(this, ServerErrorResponse);
return _possibleConstructorReturn(this, _getPrototypeOf(ServerErrorResponse).apply(this, arguments));
}
return ServerErrorResponse;
}(Response);
exports.ServerErrorResponse = ServerErrorResponse;
var statusTypeToResponse = (_statusTypeToResponse = {}, _defineProperty(_statusTypeToResponse, _matchStatus.TYPE_ABORTED, AbortedResponse), _defineProperty(_statusTypeToResponse, _matchStatus.TYPE_INFORMATIONAL, InformationalResponse), _defineProperty(_statusTypeToResponse, _matchStatus.TYPE_SUCCESS, SuccessResponse), _defineProperty(_statusTypeToResponse, _matchStatus.TYPE_REDIRECT, RedirectResponse), _defineProperty(_statusTypeToResponse, _matchStatus.TYPE_CLIENT_ERROR, ClientErrorResponse), _defineProperty(_statusTypeToResponse, _matchStatus.TYPE_SERVER_ERROR, ServerErrorResponse), _statusTypeToResponse);
const statusTypeToResponse = {
[_matchStatus.TYPE_ABORTED]: AbortedResponse,
[_matchStatus.TYPE_INFORMATIONAL]: InformationalResponse,
[_matchStatus.TYPE_SUCCESS]: SuccessResponse,
[_matchStatus.TYPE_REDIRECT]: RedirectResponse,
[_matchStatus.TYPE_CLIENT_ERROR]: ClientErrorResponse,
[_matchStatus.TYPE_SERVER_ERROR]: ServerErrorResponse
};
var createResponse =
/*#__PURE__*/
function () {
var _ref = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(result, type, request) {
var statusType, ResponseClass, data;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
statusType = (0, _matchStatus.default)(result.status);
ResponseClass = statusTypeToResponse[statusType];
_context.next = 4;
return (0, _decodeData.default)(result, type);
const createResponse = async (result, type, request) => {
const statusType = (0, _matchStatus.default)(result.status);
const ResponseClass = statusTypeToResponse[statusType];
const data = await (0, _decodeData.default)(result, type);
return new ResponseClass(result, data, request);
};
case 4:
data = _context.sent;
return _context.abrupt("return", new ResponseClass(result, data, request));
case 6:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
return function createResponse(_x, _x2, _x3) {
return _ref.apply(this, arguments);
};
}();
var _default = createResponse;
exports.default = _default;

@@ -8,75 +8,55 @@ "use strict";

var _types;
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; }
/* eslint-disable no-magic-numbers */
var TYPE_ABORTED = "aborted";
const TYPE_ABORTED = "aborted";
exports.TYPE_ABORTED = TYPE_ABORTED;
var TYPE_INFORMATIONAL = "informational";
const TYPE_INFORMATIONAL = "informational";
exports.TYPE_INFORMATIONAL = TYPE_INFORMATIONAL;
var TYPE_SUCCESS = "success";
const TYPE_SUCCESS = "success";
exports.TYPE_SUCCESS = TYPE_SUCCESS;
var TYPE_REDIRECT = "redirect";
const TYPE_REDIRECT = "redirect";
exports.TYPE_REDIRECT = TYPE_REDIRECT;
var TYPE_CLIENT_ERROR = "clientError";
const TYPE_CLIENT_ERROR = "clientError";
exports.TYPE_CLIENT_ERROR = TYPE_CLIENT_ERROR;
var TYPE_SERVER_ERROR = "serverError";
const TYPE_SERVER_ERROR = "serverError";
exports.TYPE_SERVER_ERROR = TYPE_SERVER_ERROR;
var types = (_types = {}, _defineProperty(_types, TYPE_ABORTED, function (status) {
return !status || status === 499 || status >= 600;
}), _defineProperty(_types, TYPE_INFORMATIONAL, function (status) {
return status >= 100 && status < 200;
}), _defineProperty(_types, TYPE_SUCCESS, function (status) {
return status >= 200 && status < 300;
}), _defineProperty(_types, TYPE_REDIRECT, function (status) {
return status >= 300 && status < 400;
}), _defineProperty(_types, TYPE_CLIENT_ERROR, function (status) {
return status >= 400 && status < 499;
}), _defineProperty(_types, TYPE_SERVER_ERROR, function (status) {
return status >= 500 && status < 600;
}), _types);
var checkOrder = [TYPE_SUCCESS, TYPE_CLIENT_ERROR, TYPE_SERVER_ERROR, TYPE_REDIRECT, TYPE_ABORTED, TYPE_INFORMATIONAL];
var typesCount = checkOrder.length;
var isAborted = function isAborted(status) {
return types[TYPE_ABORTED](status);
const types = {
// @todo >= 600 as unknown type?
[TYPE_ABORTED]: status => !status || status === 499 || status >= 600,
[TYPE_INFORMATIONAL]: status => status >= 100 && status < 200,
[TYPE_SUCCESS]: status => status >= 200 && status < 300,
[TYPE_REDIRECT]: status => status >= 300 && status < 400,
[TYPE_CLIENT_ERROR]: status => status >= 400 && status < 499,
[TYPE_SERVER_ERROR]: status => status >= 500 && status < 600
};
const checkOrder = [TYPE_SUCCESS, TYPE_CLIENT_ERROR, TYPE_SERVER_ERROR, TYPE_REDIRECT, TYPE_ABORTED, TYPE_INFORMATIONAL];
const typesCount = checkOrder.length;
const isAborted = status => types[TYPE_ABORTED](status);
exports.isAborted = isAborted;
var isInformational = function isInformational(status) {
return types[TYPE_INFORMATIONAL](status);
};
const isInformational = status => types[TYPE_INFORMATIONAL](status);
exports.isInformational = isInformational;
var isSuccess = function isSuccess(status) {
return types[TYPE_SUCCESS](status);
};
const isSuccess = status => types[TYPE_SUCCESS](status);
exports.isSuccess = isSuccess;
var isRedirect = function isRedirect(status) {
return types[TYPE_REDIRECT](status);
};
const isRedirect = status => types[TYPE_REDIRECT](status);
exports.isRedirect = isRedirect;
var isClientError = function isClientError(status) {
return types[TYPE_CLIENT_ERROR](status);
};
const isClientError = status => types[TYPE_CLIENT_ERROR](status);
exports.isClientError = isClientError;
var isServerError = function isServerError(status) {
return types[TYPE_SERVER_ERROR](status);
};
const isServerError = status => types[TYPE_SERVER_ERROR](status);
exports.isServerError = isServerError;
var getStatusType = function getStatusType(status) {
for (var i = 0; i < typesCount; i++) {
var type = checkOrder[i];
var fn = types[type];
const getStatusType = status => {
for (let i = 0; i < typesCount; i++) {
const type = checkOrder[i];
const fn = types[type];

@@ -83,0 +63,0 @@ if (fn(status)) {

{
"name": "api-reach",
"version": "0.1.1",
"version": "0.2.0",
"repository": "https://github.com/dzek69/api-reach.git",

@@ -5,0 +5,0 @@ "author": "Jacek Nowacki @dzek69 <git-public@dzek.eu>",

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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc