mappersmith
Advanced tools
Comparing version 2.35.0 to 2.36.0
@@ -10,5 +10,5 @@ // 1) Import mappersmith | ||
Status: { | ||
lastMessage: { path: '/api/last-message.json' } | ||
} | ||
} | ||
lastMessage: { path: '/api/last-message.json' }, | ||
}, | ||
}, | ||
}) | ||
@@ -15,0 +15,0 @@ |
@@ -25,5 +25,9 @@ "use strict"; | ||
this.successCallback = function () {}; | ||
this.successCallback = function () { | ||
return undefined; | ||
}; | ||
this.failCallback = function () {}; | ||
this.failCallback = function () { | ||
return undefined; | ||
}; | ||
} | ||
@@ -30,0 +34,0 @@ |
@@ -34,3 +34,3 @@ "use strict"; | ||
function Fetch(request) { | ||
function Fetch() { | ||
_gateway["default"].apply(this, arguments); | ||
@@ -37,0 +37,0 @@ } |
@@ -24,3 +24,3 @@ "use strict"; | ||
function HTTP(request) { | ||
function HTTP() { | ||
_gateway["default"].apply(this, arguments); | ||
@@ -51,3 +51,4 @@ } | ||
var headers = {}; // eslint-disable-next-line node/no-deprecated-api | ||
var headers = {}; // FIXME: Deprecated API | ||
// eslint-disable-next-line node/no-deprecated-api | ||
@@ -54,0 +55,0 @@ var defaults = _url["default"].parse(this.request.url()); |
@@ -14,3 +14,3 @@ "use strict"; | ||
function Mock(request) { | ||
function Mock() { | ||
_gateway["default"].apply(this, arguments); | ||
@@ -38,3 +38,3 @@ } | ||
}, | ||
callMock: function callMock(httpMethod) { | ||
callMock: function callMock() { | ||
var _this = this; | ||
@@ -41,0 +41,0 @@ |
@@ -20,3 +20,3 @@ "use strict"; | ||
function XHR(request) { | ||
function XHR() { | ||
_gateway["default"].apply(this, arguments); | ||
@@ -153,4 +153,3 @@ } | ||
createXHR: function createXHR() { | ||
var xmlHttpRequest = new XMLHttpRequest(); // eslint-disable-line no-undef | ||
var xmlHttpRequest = new XMLHttpRequest(); | ||
this.configureCallbacks(xmlHttpRequest); | ||
@@ -157,0 +156,0 @@ return xmlHttpRequest; |
"use strict"; | ||
/* eslint-disable @typescript-eslint/no-var-requires */ | ||
var lib = require('./mappersmith'); | ||
@@ -9,4 +10,5 @@ | ||
try { | ||
// eslint-disable-next-line no-eval | ||
_process = eval('typeof process === "object" ? process : undefined'); | ||
} catch (e) {} // eslint-disable-line no-eval | ||
} catch (e) {} // eslint-disable-line no-empty | ||
@@ -13,0 +15,0 @@ |
250
manifest.js
@@ -6,10 +6,8 @@ "use strict"; | ||
}); | ||
exports["default"] = void 0; | ||
exports["default"] = exports.Manifest = void 0; | ||
var _methodDescriptor = _interopRequireDefault(require("./method-descriptor")); | ||
var _methodDescriptor = require("./method-descriptor"); | ||
var _utils = require("./utils"); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } | ||
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } | ||
@@ -27,7 +25,13 @@ | ||
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; } | ||
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; } | ||
/** | ||
* @typedef Manifest | ||
* @param {Object} obj | ||
* @param {String} obj.host | ||
* @param {boolean} obj.allowResourceHostOverride - default: false | ||
* @param {Object} obj.gatewayConfigs - default: base values from mappersmith | ||
@@ -39,112 +43,158 @@ * @param {Object} obj.ignoreGlobalMiddleware - default: false | ||
*/ | ||
function Manifest(obj, _ref) { | ||
var _ref$gatewayConfigs = _ref.gatewayConfigs, | ||
gatewayConfigs = _ref$gatewayConfigs === void 0 ? null : _ref$gatewayConfigs, | ||
_ref$middleware = _ref.middleware, | ||
middleware = _ref$middleware === void 0 ? [] : _ref$middleware, | ||
_ref$context = _ref.context, | ||
context = _ref$context === void 0 ? {} : _ref$context; | ||
this.host = obj.host; | ||
this.allowResourceHostOverride = obj.allowResourceHostOverride || false; | ||
this.bodyAttr = obj.bodyAttr; | ||
this.headersAttr = obj.headersAttr; | ||
this.authAttr = obj.authAttr; | ||
this.timeoutAttr = obj.timeoutAttr; | ||
this.hostAttr = obj.hostAttr; | ||
this.clientId = obj.clientId || null; | ||
this.gatewayConfigs = (0, _utils.assign)({}, gatewayConfigs, obj.gatewayConfigs); | ||
this.resources = obj.resources || {}; | ||
this.context = context; | ||
var clientMiddleware = obj.middleware || obj.middlewares || []; // TODO: deprecate obj.middlewares in favor of obj.middleware | ||
var Manifest = /*#__PURE__*/function () { | ||
function Manifest(options, _ref) { | ||
var gatewayConfigs = _ref.gatewayConfigs, | ||
_ref$middleware = _ref.middleware, | ||
middleware = _ref$middleware === void 0 ? [] : _ref$middleware, | ||
_ref$context = _ref.context, | ||
context = _ref$context === void 0 ? {} : _ref$context; | ||
if (obj.ignoreGlobalMiddleware) { | ||
this.middleware = clientMiddleware; | ||
} else { | ||
this.middleware = [].concat(_toConsumableArray(clientMiddleware), _toConsumableArray(middleware)); | ||
_classCallCheck(this, Manifest); | ||
_defineProperty(this, "host", void 0); | ||
_defineProperty(this, "allowResourceHostOverride", void 0); | ||
_defineProperty(this, "parameterEncoder", void 0); | ||
_defineProperty(this, "bodyAttr", void 0); | ||
_defineProperty(this, "headersAttr", void 0); | ||
_defineProperty(this, "authAttr", void 0); | ||
_defineProperty(this, "timeoutAttr", void 0); | ||
_defineProperty(this, "hostAttr", void 0); | ||
_defineProperty(this, "clientId", void 0); | ||
_defineProperty(this, "gatewayConfigs", void 0); | ||
_defineProperty(this, "resources", void 0); | ||
_defineProperty(this, "context", void 0); | ||
_defineProperty(this, "middleware", void 0); | ||
this.host = options.host; | ||
this.allowResourceHostOverride = options.allowResourceHostOverride || false; | ||
this.parameterEncoder = options.parameterEncoder || encodeURIComponent; | ||
this.bodyAttr = options.bodyAttr; | ||
this.headersAttr = options.headersAttr; | ||
this.authAttr = options.authAttr; | ||
this.timeoutAttr = options.timeoutAttr; | ||
this.hostAttr = options.hostAttr; | ||
this.clientId = options.clientId || null; | ||
this.gatewayConfigs = (0, _utils.assign)({}, gatewayConfigs, options.gatewayConfigs); | ||
this.resources = options.resources || {}; | ||
this.context = context; // TODO: deprecate obj.middlewares in favor of obj.middleware | ||
var clientMiddleware = options.middleware || options.middlewares || []; | ||
if (options.ignoreGlobalMiddleware) { | ||
this.middleware = clientMiddleware; | ||
} else { | ||
this.middleware = [].concat(_toConsumableArray(clientMiddleware), _toConsumableArray(middleware)); | ||
} | ||
} | ||
} | ||
Manifest.prototype = { | ||
eachResource: function eachResource(callback) { | ||
var _this = this; | ||
_createClass(Manifest, [{ | ||
key: "eachResource", | ||
value: function eachResource(callback) { | ||
var _this = this; | ||
Object.keys(this.resources).forEach(function (resourceName) { | ||
var methods = _this.eachMethod(resourceName, function (methodName) { | ||
return { | ||
name: methodName, | ||
descriptor: _this.createMethodDescriptor(resourceName, methodName) | ||
}; | ||
Object.keys(this.resources).forEach(function (resourceName) { | ||
var methods = _this.eachMethod(resourceName, function (methodName) { | ||
return { | ||
name: methodName, | ||
descriptor: _this.createMethodDescriptor(resourceName, methodName) | ||
}; | ||
}); | ||
callback(resourceName, methods); | ||
}); | ||
} | ||
}, { | ||
key: "eachMethod", | ||
value: function eachMethod(resourceName, callback) { | ||
return Object.keys(this.resources[resourceName]).map(callback); | ||
} | ||
}, { | ||
key: "createMethodDescriptor", | ||
value: function createMethodDescriptor(resourceName, methodName) { | ||
var definition = this.resources[resourceName][methodName]; | ||
callback(resourceName, methods); | ||
}); | ||
}, | ||
eachMethod: function eachMethod(resourceName, callback) { | ||
return Object.keys(this.resources[resourceName]).map(callback); | ||
}, | ||
createMethodDescriptor: function createMethodDescriptor(resourceName, methodName) { | ||
var definition = this.resources[resourceName][methodName]; | ||
if (!definition || !definition.path) { | ||
throw new Error("[Mappersmith] path is undefined for resource \"".concat(resourceName, "\" method \"").concat(methodName, "\"")); | ||
} | ||
if (!definition || !definition.path) { | ||
throw new Error("[Mappersmith] path is undefined for resource \"".concat(resourceName, "\" method \"").concat(methodName, "\"")); | ||
return new _methodDescriptor.MethodDescriptor((0, _utils.assign)({ | ||
host: this.host, | ||
allowResourceHostOverride: this.allowResourceHostOverride, | ||
parameterEncoder: this.parameterEncoder, | ||
bodyAttr: this.bodyAttr, | ||
headersAttr: this.headersAttr, | ||
authAttr: this.authAttr, | ||
timeoutAttr: this.timeoutAttr, | ||
hostAttr: this.hostAttr | ||
}, definition)); | ||
} | ||
/** | ||
* @param {Object} args | ||
* @param {String|Null} args.clientId | ||
* @param {String} args.resourceName | ||
* @param {String} args.resourceMethod | ||
* @param {Object} args.context | ||
* @param {Boolean} args.mockRequest | ||
* | ||
* @return {Array<Object>} | ||
*/ | ||
return new _methodDescriptor["default"]((0, _utils.assign)({ | ||
host: this.host, | ||
allowResourceHostOverride: this.allowResourceHostOverride, | ||
bodyAttr: this.bodyAttr, | ||
headersAttr: this.headersAttr, | ||
authAttr: this.authAttr, | ||
timeoutAttr: this.timeoutAttr, | ||
hostAttr: this.hostAttr | ||
}, definition)); | ||
}, | ||
}, { | ||
key: "createMiddleware", | ||
value: function createMiddleware(args) { | ||
var _this2 = this; | ||
/** | ||
* @param {Object} args | ||
* @param {String|Null} args.clientId | ||
* @param {String} args.resourceName | ||
* @param {String} args.resourceMethod | ||
* @param {Object} args.context | ||
* @param {Boolean} args.mockRequest | ||
* | ||
* @return {Array<Object>} | ||
*/ | ||
createMiddleware: function createMiddleware() { | ||
var _this2 = this; | ||
var createInstance = function createInstance(middlewareFactory) { | ||
var defaultDescriptor = { | ||
__name: middlewareFactory.name || middlewareFactory.toString(), | ||
response: function response(next) { | ||
return next(); | ||
}, | ||
var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
/** | ||
* @since 2.27.0 | ||
* Replaced the request method | ||
*/ | ||
prepareRequest: function prepareRequest(next) { | ||
var _this3 = this; | ||
var createInstance = function createInstance(middlewareFactory) { | ||
return (0, _utils.assign)({ | ||
__name: middlewareFactory.name || middlewareFactory.toString(), | ||
response: function response(next) { | ||
return next(); | ||
}, | ||
return this.request ? next().then(function (req) { | ||
var _this3$request; | ||
/** | ||
* @since 2.27.0 | ||
* Replaced the request method | ||
*/ | ||
prepareRequest: function prepareRequest(next) { | ||
var _this3 = this; | ||
return (_this3$request = _this3.request) === null || _this3$request === void 0 ? void 0 : _this3$request.call(_this3, req); | ||
}) : next(); | ||
} | ||
}; | ||
var middlewareParams = (0, _utils.assign)(args, { | ||
clientId: _this2.clientId, | ||
context: (0, _utils.assign)({}, _this2.context) | ||
}); | ||
return (0, _utils.assign)(defaultDescriptor, middlewareFactory(middlewareParams)); | ||
}; | ||
return this.request ? next().then(function (req) { | ||
return _this3.request(req); | ||
}) : next(); | ||
} | ||
}, middlewareFactory((0, _utils.assign)(args, { | ||
clientId: _this2.clientId, | ||
context: (0, _utils.assign)({}, _this2.context) | ||
}))); | ||
}; | ||
var name = args.resourceName, | ||
method = args.resourceMethod; | ||
var resourceMiddleware = this.createMethodDescriptor(name, method).middleware; | ||
var middlewares = [].concat(_toConsumableArray(resourceMiddleware), _toConsumableArray(this.middleware)); | ||
return middlewares.map(createInstance); | ||
} | ||
}]); | ||
var name = args.resourceName, | ||
method = args.resourceMethod; | ||
var resourceMiddleware = this.createMethodDescriptor(name, method).middleware; | ||
var middlewares = [].concat(_toConsumableArray(resourceMiddleware), _toConsumableArray(this.middleware)); | ||
return middlewares.map(createInstance); | ||
} | ||
}; | ||
return Manifest; | ||
}(); | ||
exports.Manifest = Manifest; | ||
var _default = Manifest; | ||
exports["default"] = _default; |
@@ -16,3 +16,3 @@ "use strict"; | ||
/* global VERSION */ | ||
var version = "2.35.0"; | ||
var version = "2.36.0"; | ||
exports.version = version; | ||
@@ -24,3 +24,2 @@ var configs = { | ||
fetch: typeof fetch === 'function' ? fetch : null, | ||
// eslint-disable-line no-undef | ||
@@ -27,0 +26,0 @@ /** |
@@ -6,36 +6,81 @@ "use strict"; | ||
}); | ||
exports["default"] = MethodDescriptor; | ||
exports["default"] = exports.MethodDescriptor = void 0; | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
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; } | ||
/** | ||
* @typedef MethodDescriptor | ||
* @param {Object} obj | ||
* @param {String} obj.host | ||
* @param {boolean} obj.allowResourceHostOverride | ||
* @param {String|Function} obj.path | ||
* @param {String} obj.method | ||
* @param {Object} obj.headers | ||
* @param {Object} obj.params | ||
* @param {Object} obj.queryParamAlias | ||
* @param {String} obj.bodyAttr - body attribute name. Default: 'body' | ||
* @param {String} obj.headersAttr - headers attribute name. Default: 'headers' | ||
* @param {String} obj.authAttr - auth attribute name. Default: 'auth' | ||
* @param {Number} obj.timeoutAttr - timeout attribute name. Default: 'timeout' | ||
* @param {String} obj.hostAttr - host attribute name. Default: 'host' | ||
* @param {MethodDescriptorParams} params | ||
* @param {boolean} params.allowResourceHostOverride | ||
* @param {Function} params.parameterEncoder | ||
* @param {String} params.authAttr - auth attribute name. Default: 'auth' | ||
* @param {boolean} params.binary | ||
* @param {String} params.bodyAttr - body attribute name. Default: 'body' | ||
* @param {Headers} params.headers | ||
* @param {String} params.headersAttr - headers attribute name. Default: 'headers' | ||
* @param {String} params.host | ||
* @param {String} params.hostAttr - host attribute name. Default: 'host' | ||
* @param {String} params.method | ||
* @param {Middleware[]} params.middleware | ||
* @param {Middleware[]} params.middlewares - alias for middleware | ||
* @param {RequestParams} params.params | ||
* @param {String|Function} params.path | ||
* @param {Object} params.queryParamAlias | ||
* @param {Number} params.timeoutAttr - timeout attribute name. Default: 'timeout' | ||
*/ | ||
function MethodDescriptor(obj) { | ||
this.host = obj.host; | ||
this.allowResourceHostOverride = obj.allowResourceHostOverride || false; | ||
this.path = obj.path; | ||
this.method = obj.method || 'get'; | ||
this.headers = obj.headers; | ||
this.params = obj.params; | ||
this.queryParamAlias = obj.queryParamAlias || {}; | ||
this.binary = obj.binary || false; | ||
this.bodyAttr = obj.bodyAttr || 'body'; | ||
this.headersAttr = obj.headersAttr || 'headers'; | ||
this.authAttr = obj.authAttr || 'auth'; | ||
this.timeoutAttr = obj.timeoutAttr || 'timeout'; | ||
this.hostAttr = obj.hostAttr || 'host'; | ||
var resourceMiddleware = obj.middleware || obj.middlewares || []; | ||
var MethodDescriptor = function MethodDescriptor(params) { | ||
_classCallCheck(this, MethodDescriptor); | ||
_defineProperty(this, "allowResourceHostOverride", void 0); | ||
_defineProperty(this, "parameterEncoder", void 0); | ||
_defineProperty(this, "authAttr", void 0); | ||
_defineProperty(this, "binary", void 0); | ||
_defineProperty(this, "bodyAttr", void 0); | ||
_defineProperty(this, "headers", void 0); | ||
_defineProperty(this, "headersAttr", void 0); | ||
_defineProperty(this, "host", void 0); | ||
_defineProperty(this, "hostAttr", void 0); | ||
_defineProperty(this, "method", void 0); | ||
_defineProperty(this, "middleware", void 0); | ||
_defineProperty(this, "params", void 0); | ||
_defineProperty(this, "path", void 0); | ||
_defineProperty(this, "queryParamAlias", void 0); | ||
_defineProperty(this, "timeoutAttr", void 0); | ||
this.allowResourceHostOverride = params.allowResourceHostOverride || false; | ||
this.parameterEncoder = params.parameterEncoder || encodeURIComponent; | ||
this.binary = params.binary || false; | ||
this.headers = params.headers; | ||
this.host = params.host; | ||
this.method = params.method || 'get'; | ||
this.params = params.params; | ||
this.path = params.path; | ||
this.queryParamAlias = params.queryParamAlias || {}; | ||
this.authAttr = params.authAttr || 'auth'; | ||
this.bodyAttr = params.bodyAttr || 'body'; | ||
this.headersAttr = params.headersAttr || 'headers'; | ||
this.hostAttr = params.hostAttr || 'host'; | ||
this.timeoutAttr = params.timeoutAttr || 'timeout'; | ||
var resourceMiddleware = params.middleware || params.middlewares || []; | ||
this.middleware = resourceMiddleware; | ||
} | ||
}; | ||
exports.MethodDescriptor = MethodDescriptor; | ||
var _default = MethodDescriptor; | ||
exports["default"] = _default; |
@@ -12,4 +12,11 @@ "use strict"; | ||
var DurationMiddleware = function DurationMiddleware() { | ||
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, | ||
mockRequest = _ref.mockRequest; | ||
return { | ||
prepareRequest: function prepareRequest(next) { | ||
if (mockRequest) { | ||
return next(); | ||
} | ||
return next().then(function (request) { | ||
@@ -16,0 +23,0 @@ return request.enhance({ |
@@ -47,4 +47,5 @@ "use strict"; | ||
} | ||
} catch (e) {} | ||
} catch (e) {} // eslint-disable-line no-empty | ||
return request; | ||
@@ -51,0 +52,0 @@ }); |
@@ -40,8 +40,8 @@ "use strict"; | ||
/** | ||
* Filters an `object` by keeping only the keys fulfilling the `predicate` | ||
* | ||
* @param {Object} object - An object | ||
* @param {Function} predicate - A function of type (key: string) => boolean | ||
* @returns {Object} The filtered object | ||
*/ | ||
* Filters an `object` by keeping only the keys fulfilling the `predicate` | ||
* | ||
* @param {Object} object - An object | ||
* @param {Function} predicate - A function of type (key: string) => boolean | ||
* @returns {Object} The filtered object | ||
*/ | ||
@@ -48,0 +48,0 @@ |
{ | ||
"name": "mappersmith", | ||
"version": "2.35.0", | ||
"version": "2.36.0", | ||
"description": "It is a lightweight rest client for node.js and the browser", | ||
@@ -21,11 +21,11 @@ "author": "Tulio Ornelas <ornelas.tulio@gmail.com>", | ||
"test:node:watch": "yarn jest --config jestSetup/configs/config.node.json --watchAll", | ||
"test:typings": "yarn tsc --noEmit", | ||
"test:types": "yarn tsc --noEmit", | ||
"test:types:watch": "yarn test:types --watch", | ||
"test:unit": "concurrently --success first --names \"test,server\" --kill-others \"node scripts/ci.js\" \"yarn integration-server\"", | ||
"test": "yarn test:typings && yarn test:unit", | ||
"build:types": "yarn tsc --emitDeclarationOnly", | ||
"build:node": "rm -rf lib/* && yarn babel src -d lib --extensions '.js,.ts'", | ||
"test": "yarn test:types && yarn prettier --check . && yarn lint && yarn test:unit", | ||
"build:node": "rm -rf lib/* && yarn babel src -d lib --extensions '.js,.ts' --ignore '**/*.spec.ts'", | ||
"build:browser": "rm -rf dist/* && yarn webpack --config webpack.conf.js", | ||
"build": "yarn build:types && yarn build:node && yarn build:browser", | ||
"build": "yarn build:node && yarn build:browser", | ||
"release": "./scripts/release.sh", | ||
"lint": "yarn eslint \"{src,spec}/**/*.js\"" | ||
"lint": "yarn eslint \"{src,spec,typings}/**/*.[j|t]s\"" | ||
}, | ||
@@ -56,2 +56,6 @@ "repository": { | ||
}, | ||
"volta": { | ||
"node": "12.22.7", | ||
"yarn": "1.22.11" | ||
}, | ||
"devDependencies": { | ||
@@ -67,3 +71,6 @@ "@babel/cli": "^7.0.0", | ||
"@chiragrupani/karma-chromium-edge-launcher": "^2.1.1", | ||
"@types/jest": "^23.3.14", | ||
"@types/node": "^16.10.3", | ||
"@typescript-eslint/eslint-plugin": "^5.4.0", | ||
"@typescript-eslint/parser": "^5.4.0", | ||
"babel-core": "^7.0.0-bridge.0", | ||
@@ -78,2 +85,3 @@ "babel-jest": "^23.6.0", | ||
"eslint": "^7.32.0", | ||
"eslint-config-prettier": "^8.3.0", | ||
"eslint-config-standard": "^12.0.0", | ||
@@ -95,6 +103,6 @@ "eslint-plugin-import": "^2.24.2", | ||
"karma-spec-reporter": "^0.0.32", | ||
"karma-typescript": "5.5.2", | ||
"karma-webpack": "^4.0.0", | ||
"mockdate": "^3.0.5", | ||
"multer": "^1.4.3", | ||
"prettier": "2.5.0", | ||
"puppeteer": "^1.20.0", | ||
@@ -101,0 +109,0 @@ "ts-jest": "^23.0.0", |
@@ -179,2 +179,12 @@ [![npm version](https://badge.fury.io/js/mappersmith.svg)](http://badge.fury.io/js/mappersmith) | ||
You can optionally set `parameterEncoder: yourEncodingFunction` to change the default encoding function for parameters. This is useful when you are calling an endpoint which for example requires not encoded characters like `:` that are otherwise encoded by the default behaviour of the `encodeURIComponent` function ([external documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent?retiredLocale=it#description)). | ||
```javascript | ||
const client = forge({ | ||
host: 'https://custom-host.com', | ||
parameterEncoder: yourEncodingFunction, | ||
resources: { ... } | ||
}) | ||
``` | ||
### <a name="default-parameters"></a> Default Parameters | ||
@@ -1317,2 +1327,6 @@ | ||
### Volta | ||
This project uses [Volta](https://docs.volta.sh/guide/getting-started) to manage the node/npm and yarn versions used via package.json. | ||
### Running unit tests: | ||
@@ -1345,2 +1359,6 @@ | ||
## Linting | ||
This project uses prettier and eslint, it is recommended to install extensions in your browser to format on save. | ||
## Contributors | ||
@@ -1347,0 +1365,0 @@ |
413
request.js
@@ -6,6 +6,20 @@ "use strict"; | ||
}); | ||
exports["default"] = void 0; | ||
exports["default"] = exports.Request = void 0; | ||
var _utils = require("./utils"); | ||
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 _typeof(obj) { "@babel/helpers - typeof"; 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 _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; } | ||
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; } | ||
var REGEXP_DYNAMIC_SEGMENT = /{([^}?]+)\??}/; | ||
@@ -17,216 +31,259 @@ var REGEXP_OPTIONAL_DYNAMIC_SEGMENT = /\/?{([^}?]+)\?}/g; | ||
* @param {MethodDescriptor} methodDescriptor | ||
* @param {Object} requestParams, defaults to an empty object ({}) | ||
* @param {RequestParams} requestParams, defaults to an empty object ({}) | ||
*/ | ||
function Request(methodDescriptor, requestParams) { | ||
this.methodDescriptor = methodDescriptor; | ||
this.requestParams = requestParams || {}; | ||
} | ||
var Request = /*#__PURE__*/function () { | ||
function Request(methodDescriptor) { | ||
var requestParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
Request.prototype = { | ||
/** | ||
* @return {Object} | ||
*/ | ||
params: function params() { | ||
var _this = this; | ||
_classCallCheck(this, Request); | ||
var params = (0, _utils.assign)({}, this.methodDescriptor.params, this.requestParams); | ||
_defineProperty(this, "methodDescriptor", void 0); | ||
var isParam = function isParam(key) { | ||
return key !== _this.methodDescriptor.headersAttr && key !== _this.methodDescriptor.bodyAttr && key !== _this.methodDescriptor.authAttr && key !== _this.methodDescriptor.timeoutAttr && key !== _this.methodDescriptor.hostAttr; | ||
}; | ||
_defineProperty(this, "requestParams", void 0); | ||
return Object.keys(params).reduce(function (obj, key) { | ||
if (isParam(key)) { | ||
obj[key] = params[key]; | ||
} | ||
this.methodDescriptor = methodDescriptor; | ||
this.requestParams = requestParams; | ||
} | ||
return obj; | ||
}, {}); | ||
}, | ||
_createClass(Request, [{ | ||
key: "isParam", | ||
value: function isParam(key) { | ||
return key !== this.methodDescriptor.headersAttr && key !== this.methodDescriptor.bodyAttr && key !== this.methodDescriptor.authAttr && key !== this.methodDescriptor.timeoutAttr && key !== this.methodDescriptor.hostAttr; | ||
} | ||
}, { | ||
key: "params", | ||
value: function params() { | ||
var _this = this; | ||
/** | ||
* Returns the HTTP method in lowercase | ||
* | ||
* @return {String} | ||
*/ | ||
method: function method() { | ||
return this.methodDescriptor.method.toLowerCase(); | ||
}, | ||
var params = (0, _utils.assign)({}, this.methodDescriptor.params, this.requestParams); | ||
return Object.keys(params).reduce(function (obj, key) { | ||
if (_this.isParam(key)) { | ||
obj[key] = params[key]; | ||
} | ||
/** | ||
* Returns host name without trailing slash | ||
* Example: http://example.org | ||
* | ||
* @return {String} | ||
*/ | ||
host: function host() { | ||
var _this$methodDescripto = this.methodDescriptor, | ||
allowResourceHostOverride = _this$methodDescripto.allowResourceHostOverride, | ||
hostAttr = _this$methodDescripto.hostAttr, | ||
host = _this$methodDescripto.host; | ||
var originalHost = allowResourceHostOverride ? this.requestParams[hostAttr] || host || '' : host || ''; | ||
return originalHost.replace(REGEXP_TRAILING_SLASH, ''); | ||
}, | ||
return obj; | ||
}, {}); | ||
} | ||
/** | ||
* Returns the HTTP method in lowercase | ||
*/ | ||
/** | ||
* Returns path with parameters and leading slash. | ||
* Example: /some/path?param1=true | ||
* | ||
* @throws {Error} if any dynamic segment is missing. | ||
* Example: | ||
* Imagine the path '/some/{name}', the error will be similar to: | ||
* '[Mappersmith] required parameter missing (name), "/some/{name}" cannot be resolved' | ||
* | ||
* @return {String} | ||
*/ | ||
path: function path() { | ||
var _this2 = this; | ||
}, { | ||
key: "method", | ||
value: function method() { | ||
return this.methodDescriptor.method.toLowerCase(); | ||
} | ||
/** | ||
* Returns host name without trailing slash | ||
* Example: 'http://example.org' | ||
*/ | ||
var params = this.params(); | ||
var path; | ||
}, { | ||
key: "host", | ||
value: function host() { | ||
var _this$methodDescripto = this.methodDescriptor, | ||
allowResourceHostOverride = _this$methodDescripto.allowResourceHostOverride, | ||
hostAttr = _this$methodDescripto.hostAttr, | ||
host = _this$methodDescripto.host; | ||
var originalHost = allowResourceHostOverride ? this.requestParams[hostAttr] || host || '' : host || ''; | ||
if (typeof this.methodDescriptor.path === 'function') { | ||
path = this.methodDescriptor.path(params); | ||
} else { | ||
path = this.methodDescriptor.path; | ||
if (typeof originalHost === 'string') { | ||
return originalHost.replace(REGEXP_TRAILING_SLASH, ''); | ||
} | ||
return ''; | ||
} | ||
/** | ||
* Returns path with parameters and leading slash. | ||
* Example: '/some/path?param1=true' | ||
* | ||
* @throws {Error} if any dynamic segment is missing. | ||
* Example: | ||
* Imagine the path '/some/{name}', the error will be similar to: | ||
* '[Mappersmith] required parameter missing (name), "/some/{name}" cannot be resolved' | ||
*/ | ||
if (path[0] !== '/') { | ||
path = "/".concat(path); | ||
} // RegExp with 'g'-flag is stateful, therefore defining it locally | ||
}, { | ||
key: "path", | ||
value: function path() { | ||
var _this2 = this; | ||
var params = this.params(); | ||
var path; | ||
var regexp = new RegExp(REGEXP_DYNAMIC_SEGMENT, 'g'); | ||
var dynamicSegmentKeys = []; | ||
var match; | ||
if (typeof this.methodDescriptor.path === 'function') { | ||
path = this.methodDescriptor.path(params); | ||
} else { | ||
path = this.methodDescriptor.path; | ||
} | ||
while ((match = regexp.exec(path)) !== null) { | ||
dynamicSegmentKeys.push(match[1]); | ||
} | ||
if (path[0] !== '/') { | ||
path = "/".concat(path); | ||
} // RegExp with 'g'-flag is stateful, therefore defining it locally | ||
for (var _i = 0, _dynamicSegmentKeys = dynamicSegmentKeys; _i < _dynamicSegmentKeys.length; _i++) { | ||
var key = _dynamicSegmentKeys[_i]; | ||
var pattern = new RegExp("{".concat(key, "\\??}"), 'g'); | ||
if (params[key] != null) { | ||
path = path.replace(pattern, encodeURIComponent(params[key])); | ||
delete params[key]; | ||
var regexp = new RegExp(REGEXP_DYNAMIC_SEGMENT, 'g'); | ||
var dynamicSegmentKeys = []; | ||
var match; | ||
while ((match = regexp.exec(path)) !== null) { | ||
dynamicSegmentKeys.push(match[1]); | ||
} | ||
} | ||
path = path.replace(REGEXP_OPTIONAL_DYNAMIC_SEGMENT, ''); | ||
var missingDynamicSegmentMatch = path.match(REGEXP_DYNAMIC_SEGMENT); | ||
for (var _i = 0, _dynamicSegmentKeys = dynamicSegmentKeys; _i < _dynamicSegmentKeys.length; _i++) { | ||
var key = _dynamicSegmentKeys[_i]; | ||
var pattern = new RegExp("{".concat(key, "\\??}"), 'g'); | ||
var value = params[key]; | ||
if (missingDynamicSegmentMatch) { | ||
throw new Error("[Mappersmith] required parameter missing (".concat(missingDynamicSegmentMatch[1], "), \"").concat(path, "\" cannot be resolved")); | ||
if (value != null && _typeof(value) !== 'object') { | ||
path = path.replace(pattern, this.methodDescriptor.parameterEncoder(value)); | ||
delete params[key]; | ||
} | ||
} | ||
path = path.replace(REGEXP_OPTIONAL_DYNAMIC_SEGMENT, ''); | ||
var missingDynamicSegmentMatch = path.match(REGEXP_DYNAMIC_SEGMENT); | ||
if (missingDynamicSegmentMatch) { | ||
throw new Error("[Mappersmith] required parameter missing (".concat(missingDynamicSegmentMatch[1], "), \"").concat(path, "\" cannot be resolved")); | ||
} | ||
var aliasedParams = Object.keys(params).reduce(function (aliased, key) { | ||
var aliasedKey = _this2.methodDescriptor.queryParamAlias[key] || key; | ||
var value = params[key]; | ||
if (value != null && _typeof(value) !== 'object') { | ||
aliased[aliasedKey] = value; | ||
} | ||
return aliased; | ||
}, {}); | ||
var queryString = (0, _utils.toQueryString)(aliasedParams); | ||
if (typeof queryString === 'string' && queryString.length !== 0) { | ||
var hasQuery = path.includes('?'); | ||
path += "".concat(hasQuery ? '&' : '?').concat(queryString); | ||
} | ||
return path; | ||
} | ||
/** | ||
* Returns the template path, without params, before interpolation. | ||
* If path is a function, returns the result of request.path() | ||
* Example: '/some/{param}/path' | ||
*/ | ||
var aliasedParams = Object.keys(params).reduce(function (aliased, key) { | ||
var aliasedKey = _this2.methodDescriptor.queryParamAlias[key] || key; | ||
aliased[aliasedKey] = params[key]; | ||
return aliased; | ||
}, {}); | ||
var queryString = (0, _utils.toQueryString)(aliasedParams); | ||
}, { | ||
key: "pathTemplate", | ||
value: function pathTemplate() { | ||
var path = this.methodDescriptor.path; | ||
if (queryString.length !== 0) { | ||
var hasQuery = path.includes('?'); | ||
path += "".concat(hasQuery ? '&' : '?').concat(queryString); | ||
var prependSlash = function prependSlash(str) { | ||
return str[0] !== '/' ? "/".concat(str) : str; | ||
}; | ||
if (typeof path === 'function') { | ||
return prependSlash(path(this.params())); | ||
} | ||
return prependSlash(path); | ||
} | ||
/** | ||
* Returns the full URL | ||
* Example: http://example.org/some/path?param1=true | ||
* | ||
*/ | ||
return path; | ||
}, | ||
}, { | ||
key: "url", | ||
value: function url() { | ||
return "".concat(this.host()).concat(this.path()); | ||
} | ||
/** | ||
* Returns an object with the headers. Header names are converted to | ||
* lowercase | ||
*/ | ||
/** | ||
* Returns the template path, without params, before interpolation. | ||
* If path is a function, returns the result of request.path() | ||
* Example: /some/{param}/path | ||
* | ||
* @return {String|Function} | ||
*/ | ||
pathTemplate: function pathTemplate() { | ||
var path = this.methodDescriptor.path; | ||
}, { | ||
key: "headers", | ||
value: function headers() { | ||
var headerAttr = this.methodDescriptor.headersAttr; | ||
var headers = this.requestParams[headerAttr] || {}; | ||
if (typeof this.methodDescriptor.path !== 'function' && path[0] !== '/') { | ||
path = "/".concat(path); | ||
var mergedHeaders = _objectSpread(_objectSpread({}, this.methodDescriptor.headers), headers); | ||
return (0, _utils.lowerCaseObjectKeys)(mergedHeaders); | ||
} | ||
/** | ||
* Utility method to get a header value by name | ||
*/ | ||
return path; | ||
}, | ||
}, { | ||
key: "header", | ||
value: function header(name) { | ||
return this.headers()[name.toLowerCase()]; | ||
} | ||
}, { | ||
key: "body", | ||
value: function body() { | ||
return this.requestParams[this.methodDescriptor.bodyAttr]; | ||
} | ||
}, { | ||
key: "auth", | ||
value: function auth() { | ||
return this.requestParams[this.methodDescriptor.authAttr]; | ||
} | ||
}, { | ||
key: "timeout", | ||
value: function timeout() { | ||
return this.requestParams[this.methodDescriptor.timeoutAttr]; | ||
} | ||
/** | ||
* Enhances current request returning a new Request | ||
* @param {RequestParams} extras | ||
* @param {Object} extras.auth - it will replace the current auth | ||
* @param {String|Object} extras.body - it will replace the current body | ||
* @param {Headers} extras.headers - it will be merged with current headers | ||
* @param {String} extras.host - it will replace the current timeout | ||
* @param {RequestParams} extras.params - it will be merged with current params | ||
* @param {Number} extras.timeout - it will replace the current timeout | ||
*/ | ||
/** | ||
* Returns the full URL | ||
* Example: http://example.org/some/path?param1=true | ||
* | ||
* @return {String} | ||
*/ | ||
url: function url() { | ||
return "".concat(this.host()).concat(this.path()); | ||
}, | ||
}, { | ||
key: "enhance", | ||
value: function enhance(extras) { | ||
var authKey = this.methodDescriptor.authAttr; | ||
var bodyKey = this.methodDescriptor.bodyAttr; | ||
var headerKey = this.methodDescriptor.headersAttr; | ||
var hostKey = this.methodDescriptor.hostAttr; | ||
var timeoutKey = this.methodDescriptor.timeoutAttr; // Note: The result of merging an instance of RequestParams with instance of Params | ||
// is simply a RequestParams with even more [param: string]'s on it. | ||
/** | ||
* Returns an object with the headers. Header names are converted to | ||
* lowercase | ||
* | ||
* @return {Object} | ||
*/ | ||
headers: function headers() { | ||
return (0, _utils.lowerCaseObjectKeys)((0, _utils.assign)({}, this.methodDescriptor.headers, this.requestParams[this.methodDescriptor.headersAttr])); | ||
}, | ||
var requestParams = (0, _utils.assign)({}, this.requestParams, extras.params); | ||
var headers = this.requestParams[headerKey]; | ||
var mergedHeaders = (0, _utils.assign)({}, headers, extras.headers); | ||
requestParams[headerKey] = mergedHeaders; | ||
extras.auth && (requestParams[authKey] = extras.auth); | ||
extras.body && (requestParams[bodyKey] = extras.body); | ||
extras.host && (requestParams[hostKey] = extras.host); | ||
extras.timeout && (requestParams[timeoutKey] = extras.timeout); | ||
return new Request(this.methodDescriptor, requestParams); | ||
} | ||
/** | ||
* Is the request expecting a binary response? | ||
*/ | ||
/** | ||
* Utility method to get a header value by name | ||
* | ||
* @param {String} name | ||
* | ||
* @return {String|Undefined} | ||
*/ | ||
header: function header(name) { | ||
return this.headers()[name.toLowerCase()]; | ||
}, | ||
body: function body() { | ||
return this.requestParams[this.methodDescriptor.bodyAttr]; | ||
}, | ||
auth: function auth() { | ||
return this.requestParams[this.methodDescriptor.authAttr]; | ||
}, | ||
timeout: function timeout() { | ||
return this.requestParams[this.methodDescriptor.timeoutAttr]; | ||
}, | ||
}, { | ||
key: "isBinary", | ||
value: function isBinary() { | ||
return this.methodDescriptor.binary; | ||
} | ||
}]); | ||
/** | ||
* Enhances current request returning a new Request | ||
* @param {Object} extras | ||
* @param {Object} extras.params - it will be merged with current params | ||
* @param {Object} extras.headers - it will be merged with current headers | ||
* @param {String|Object} extras.body - it will replace the current body | ||
* @param {Object} extras.auth - it will replace the current auth | ||
* @param {Number} extras.timeout - it will replace the current timeout | ||
* @param {String} extras.host - it will replace the current timeout | ||
*/ | ||
enhance: function enhance(extras) { | ||
var headerKey = this.methodDescriptor.headersAttr; | ||
var bodyKey = this.methodDescriptor.bodyAttr; | ||
var authKey = this.methodDescriptor.authAttr; | ||
var timeoutKey = this.methodDescriptor.timeoutAttr; | ||
var hostKey = this.methodDescriptor.hostAttr; | ||
var requestParams = (0, _utils.assign)({}, this.requestParams, extras.params); | ||
requestParams[headerKey] = (0, _utils.assign)({}, this.requestParams[headerKey], extras.headers); | ||
extras.body && (requestParams[bodyKey] = extras.body); | ||
extras.auth && (requestParams[authKey] = extras.auth); | ||
extras.timeout && (requestParams[timeoutKey] = extras.timeout); | ||
extras.host && (requestParams[hostKey] = extras.host); | ||
return new Request(this.methodDescriptor, requestParams); | ||
}, | ||
return Request; | ||
}(); | ||
/** | ||
* Is the request expecting a binary response? | ||
* | ||
* @return {Boolean} | ||
*/ | ||
isBinary: function isBinary() { | ||
return this.methodDescriptor.binary; | ||
} | ||
}; | ||
exports.Request = Request; | ||
var _default = Request; | ||
exports["default"] = _default; |
272
response.js
@@ -6,3 +6,3 @@ "use strict"; | ||
}); | ||
exports["default"] = void 0; | ||
exports["default"] = exports.Response = void 0; | ||
@@ -23,3 +23,16 @@ var _utils = require("./utils"); | ||
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 _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; } | ||
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; } | ||
var REGEXP_CONTENT_TYPE_JSON = /^application\/(json|.*\+json)/; | ||
/** | ||
@@ -33,134 +46,169 @@ * @typedef Response | ||
*/ | ||
var Response = /*#__PURE__*/function () { | ||
function Response(originalRequest, responseStatus, responseData, responseHeaders, errors) { | ||
_classCallCheck(this, Response); | ||
function Response(originalRequest, responseStatus, responseData, responseHeaders, errors) { | ||
if (originalRequest.requestParams && originalRequest.requestParams.auth) { | ||
var maskedAuth = (0, _utils.assign)({}, originalRequest.requestParams.auth, { | ||
password: '***' | ||
}); | ||
this.originalRequest = originalRequest.enhance({ | ||
auth: maskedAuth | ||
}); | ||
} else { | ||
this.originalRequest = originalRequest; | ||
_defineProperty(this, "originalRequest", void 0); | ||
_defineProperty(this, "responseStatus", void 0); | ||
_defineProperty(this, "responseData", void 0); | ||
_defineProperty(this, "responseHeaders", void 0); | ||
_defineProperty(this, "errors", void 0); | ||
_defineProperty(this, "timeElapsed", void 0); | ||
var auth = originalRequest.requestParams && originalRequest.requestParams.auth; | ||
if (auth) { | ||
var maskedAuth = _objectSpread(_objectSpread({}, auth), {}, { | ||
password: '***' | ||
}); | ||
this.originalRequest = originalRequest.enhance({ | ||
auth: maskedAuth | ||
}); | ||
} else { | ||
this.originalRequest = originalRequest; | ||
} | ||
this.responseStatus = responseStatus; | ||
this.responseData = responseData !== undefined ? responseData : null; | ||
this.responseHeaders = responseHeaders || {}; | ||
this.errors = errors || []; | ||
this.timeElapsed = null; | ||
} | ||
this.responseStatus = responseStatus; | ||
this.responseData = responseData !== undefined ? responseData : null; | ||
this.responseHeaders = responseHeaders || {}; | ||
this.errors = errors || []; | ||
this.timeElapsed = null; | ||
} | ||
_createClass(Response, [{ | ||
key: "request", | ||
value: function request() { | ||
return this.originalRequest; | ||
} | ||
}, { | ||
key: "status", | ||
value: function status() { | ||
// IE sends 1223 instead of 204 | ||
if (this.responseStatus === 1223) { | ||
return 204; | ||
} | ||
Response.prototype = { | ||
/** | ||
* @return {Request} | ||
*/ | ||
request: function request() { | ||
return this.originalRequest; | ||
}, | ||
return this.responseStatus; | ||
} | ||
/** | ||
* Returns true if status is greater or equal 200 or lower than 400 | ||
*/ | ||
/** | ||
* @return {Integer} | ||
*/ | ||
status: function status() { | ||
// IE sends 1223 instead of 204 | ||
if (this.responseStatus === 1223) { | ||
return 204; | ||
}, { | ||
key: "success", | ||
value: function success() { | ||
var status = this.status(); | ||
return status >= 200 && status < 400; | ||
} | ||
/** | ||
* Returns an object with the headers. Header names are converted to | ||
* lowercase | ||
*/ | ||
return this.responseStatus; | ||
}, | ||
}, { | ||
key: "headers", | ||
value: function headers() { | ||
return (0, _utils.lowerCaseObjectKeys)(this.responseHeaders); | ||
} | ||
/** | ||
* Utility method to get a header value by name | ||
*/ | ||
/** | ||
* Returns true if status is greater or equal 200 or lower than 400 | ||
* | ||
* @return {Boolean} | ||
*/ | ||
success: function success() { | ||
var status = this.status(); | ||
return status >= 200 && status < 400; | ||
}, | ||
}, { | ||
key: "header", | ||
value: function header(name) { | ||
var key = name.toLowerCase(); | ||
/** | ||
* Returns an object with the headers. Header names are converted to | ||
* lowercase | ||
* | ||
* @return {Object} | ||
*/ | ||
headers: function headers() { | ||
return (0, _utils.lowerCaseObjectKeys)(this.responseHeaders); | ||
}, | ||
if (key in this.headers()) { | ||
return this.headers()[key]; | ||
} | ||
/** | ||
* Utility method to get a header value by name | ||
* | ||
* @param {String} name | ||
* | ||
* @return {String|Undefined} | ||
*/ | ||
header: function header(name) { | ||
return this.headers()[name.toLowerCase()]; | ||
}, | ||
return undefined; | ||
} | ||
/** | ||
* Returns the original response data | ||
*/ | ||
/** | ||
* Returns the original response data | ||
*/ | ||
rawData: function rawData() { | ||
return this.responseData; | ||
}, | ||
}, { | ||
key: "rawData", | ||
value: function rawData() { | ||
return this.responseData; | ||
} | ||
/** | ||
* Returns the response data, if "Content-Type" is "application/json" | ||
* it parses the response and returns an object. | ||
* Friendly reminder: | ||
* - JSON.parse() can return null, an Array or an object. | ||
*/ | ||
/** | ||
* Returns the response data, if "Content-Type" is "application/json" | ||
* it parses the response and returns an object | ||
* | ||
* @return {String|Object} | ||
*/ | ||
data: function data() { | ||
var data = this.responseData; | ||
}, { | ||
key: "data", | ||
value: function data() { | ||
if (this.isContentTypeJSON() && this.responseData !== null) { | ||
try { | ||
return JSON.parse(this.responseData); | ||
} catch (e) {} // eslint-disable-line no-empty | ||
if (this.isContentTypeJSON()) { | ||
try { | ||
data = JSON.parse(this.responseData); | ||
} catch (e) {} | ||
} | ||
return this.responseData; | ||
} | ||
}, { | ||
key: "isContentTypeJSON", | ||
value: function isContentTypeJSON() { | ||
var contentType = this.header('content-type'); | ||
return data; | ||
}, | ||
isContentTypeJSON: function isContentTypeJSON() { | ||
return REGEXP_CONTENT_TYPE_JSON.test(this.headers()['content-type']); | ||
}, | ||
if (contentType === undefined) { | ||
return false; | ||
} | ||
/** | ||
* Returns the last error instance that caused the request to fail | ||
* | ||
* @return {Error|null} | ||
*/ | ||
error: function error() { | ||
var lastError = this.errors[this.errors.length - 1] || null; | ||
return REGEXP_CONTENT_TYPE_JSON.test(contentType); | ||
} | ||
/** | ||
* Returns the last error instance that caused the request to fail | ||
*/ | ||
if (typeof lastError === 'string') { | ||
return new Error(lastError); | ||
}, { | ||
key: "error", | ||
value: function error() { | ||
var lastError = this.errors[this.errors.length - 1] || null; | ||
if (typeof lastError === 'string') { | ||
return new Error(lastError); | ||
} | ||
return lastError; | ||
} | ||
/** | ||
* Enhances current Response returning a new Response | ||
* | ||
* @param {Object} extras | ||
* @param {Integer} extras.status - it will replace the current status | ||
* @param {String} extras.rawData - it will replace the current rawData | ||
* @param {Object} extras.headers - it will be merged with current headers | ||
* @param {Error} extras.error - it will be added to the list of errors | ||
*/ | ||
return lastError; | ||
}, | ||
}, { | ||
key: "enhance", | ||
value: function enhance(extras) { | ||
var mergedHeaders = _objectSpread(_objectSpread({}, this.headers()), extras.headers || {}); | ||
/** | ||
* Enhances current Response returning a new Response | ||
* | ||
* @param {Object} extras | ||
* @param {Integer} extras.status - it will replace the current status | ||
* @param {String} extras.rawData - it will replace the current rawData | ||
* @param {Object} extras.headers - it will be merged with current headers | ||
* @param {Error} extras.error - it will be added to the list of errors | ||
* | ||
* @return {Response} | ||
*/ | ||
enhance: function enhance(extras) { | ||
var enhancedResponse = new Response(this.request(), extras.status || this.status(), extras.rawData || this.rawData(), (0, _utils.assign)({}, this.headers(), extras.headers), extras.error ? [].concat(_toConsumableArray(this.errors), [extras.error]) : _toConsumableArray(this.errors)); | ||
enhancedResponse.timeElapsed = this.timeElapsed; | ||
return enhancedResponse; | ||
} | ||
}; | ||
var enhancedResponse = new Response(this.request(), extras.status || this.status(), extras.rawData || this.rawData() || undefined, mergedHeaders, extras.error ? [].concat(_toConsumableArray(this.errors), [extras.error]) : _toConsumableArray(this.errors)); | ||
enhancedResponse.timeElapsed = this.timeElapsed; | ||
return enhancedResponse; | ||
} | ||
}]); | ||
return Response; | ||
}(); | ||
exports.Response = Response; | ||
var _default = Response; | ||
exports["default"] = _default; |
declare module 'mappersmith/gateway/fetch' { | ||
import {FetchGateway} from 'mappersmith' | ||
import { FetchGateway } from 'mappersmith' | ||
@@ -4,0 +4,0 @@ const Fetch: FetchGateway |
@@ -0,1 +1,2 @@ | ||
/* eslint-disable @typescript-eslint/triple-slash-reference */ | ||
/// <reference path="./middleware/basic-auth.d.ts" /> | ||
@@ -13,90 +14,24 @@ /// <reference path="./middleware/csrf.d.ts" /> | ||
declare module 'mappersmith' { | ||
export type Request = import('../src/request').Request | ||
export type Headers = import('../src/types').Headers | ||
export type Parameters = import('../src/types').Params | ||
export type Gateway = import('../src/types').Gateway | ||
type NetworkGateway = import('../src/types').NetworkGateway | ||
export type XhrGateway = import('../src/types').XhrGateway | ||
export type HTTPRequestParams = import('../src/types').HTTPRequestParams | ||
export type HTTPGatewayConfiguration = import('../src/types').HTTPGatewayConfiguration | ||
export type GatewayConfiguration = import('../src/types').GatewayConfiguration | ||
export type Response = import('../src/response').Response | ||
export interface Headers { | ||
readonly [header: string]: string | ||
} | ||
export type AbortFn = import('../src/middleware').AbortFn | ||
export type Authorization = import('../src/middleware').Authorization | ||
export type Context = import('../src/middleware').Context | ||
export type Middleware = import('../src/middleware').Middleware | ||
export type MiddlewareDescriptor = import('../src/middleware').MiddlewareDescriptor | ||
export type MiddlewareParams = import('../src/middleware').MiddlewareParams | ||
export type RenewFn = import('../src/middleware').RenewFn | ||
export type RequestGetter = import('../src/middleware').RequestGetter | ||
export type ResponseGetter = import('../src/middleware').ResponseGetter | ||
type ParameterEncoderFn = import('../src/types').ParameterEncoderFn | ||
export interface Authorization { | ||
readonly username: string | ||
readonly password: string | ||
} | ||
export interface Parameters { | ||
readonly auth?: Authorization | ||
readonly timeout?: number | ||
[param: string]: object | string | number | boolean | undefined | ||
} | ||
export type Context = object | ||
export interface RequestParams { | ||
readonly params: Parameters | ||
readonly headers: Headers | ||
readonly body: object | string | ||
readonly auth: object | ||
readonly timeout: number | ||
readonly host: string | ||
} | ||
export interface ResponseParams { | ||
readonly status: number | ||
readonly rawData: string | ||
readonly headers: Headers | ||
readonly error: Error | ||
} | ||
export interface Request { | ||
params(): Parameters | ||
method(): string | ||
host(): string | ||
path(): string | ||
pathTemplate(): string | Function | ||
url(): string | ||
headers(): Headers | ||
header(name: string): string | undefined | ||
body(): object | string | ||
auth(): object | ||
timeout(): number | ||
enhance(extras: Partial<RequestParams>): Request | ||
isBinary(): boolean | ||
} | ||
export interface Response { | ||
readonly responseStatus: number | ||
request(): Request | ||
status(): number | ||
success(): boolean | ||
headers(): Headers | ||
header(name: string): string | undefined | ||
rawData(): string | null | ||
data<DataType = object | string>(): DataType | ||
isContentTypeJSON(): boolean | ||
error(): Error | null | ||
enhance(extras: Partial<ResponseParams>): Response | ||
} | ||
export type RequestGetter = () => Promise<Request> | ||
export type ResponseGetter = () => Promise<Response> | ||
export type AbortFn = (error: Error) => void | ||
export type RenewFn = () => Promise<object> | ||
export interface MiddlewareDescriptor { | ||
// @deprecated: Please use prepareRequest instead | ||
request?(request: Request): Promise<Request> | Request | ||
prepareRequest?(next: RequestGetter, abort: AbortFn): Promise<Request | void> | ||
response?(next: ResponseGetter, renew: RenewFn): Promise<Response | object> | ||
} | ||
export interface MiddlewareParams { | ||
readonly resourceName: string | ||
readonly resourceMethod: string | ||
readonly clientId: string | ||
readonly context: Context | ||
} | ||
export type Middleware = (params: MiddlewareParams) => MiddlewareDescriptor | ||
export type AsyncFunctions<HashType> = { | ||
@@ -110,35 +45,4 @@ [Key in keyof HashType]: (params?: Parameters) => Promise<Response> | ||
export interface Options<ResourcesType> { | ||
readonly clientId?: string | ||
readonly host?: string | ||
readonly allowResourceHostOverride?: boolean | ||
readonly ignoreGlobalMiddleware?: boolean | ||
readonly middleware?: Middleware[] | ||
readonly gatewayConfigs?: Partial<GatewayConfiguration> | ||
// @alias middleware | ||
readonly middlewares?: Middleware[] | ||
readonly resources: ResourcesType | ||
} | ||
export type FetchGateway = Gateway | ||
export interface Gateway { | ||
call(): void | ||
dispatchClientError(message: string, error: Error): void | ||
dispatchResponse(response: Response): void | ||
extends(methods: {[fn: string]: Function}): void | ||
options(): object | ||
prepareBody(method: string, headers: Headers): string | ||
shouldEmulateHTTP(): boolean | ||
} | ||
interface NetworkGateway { | ||
delete?(): void | ||
get(): void | ||
head(): void | ||
patch(): void | ||
post(): void | ||
put(): void | ||
} | ||
export interface FetchGateway extends Gateway {} | ||
export interface HTTPGateway extends Gateway, NetworkGateway { | ||
@@ -155,39 +59,2 @@ createResponse(response: Response, rawData: string): Response | ||
export interface XhrGateway extends Gateway, NetworkGateway { | ||
readonly withCredentials: boolean | ||
configure(xmlHttpRequest: XMLHttpRequest): void | ||
configureBinary(xmlHttpRequest: XMLHttpRequest): void | ||
configureCallbacks(xmlHttpRequest: XMLHttpRequest): void | ||
configureTimeout(xmlHttpRequest: XMLHttpRequest): void | ||
createResponse(xmlHttpRequest: XMLHttpRequest): void | ||
createXHR(): XMLHttpRequest | ||
performRequest(method: string): void | ||
setHeaders(xmlHttpRequest: XMLHttpRequest, headers: Headers): void | ||
} | ||
export interface HTTPRequestParams { | ||
[key: string]: any | ||
} | ||
export interface HTTPGatewayConfiguration { | ||
configure?(requestParams: HTTPRequestParams): HTTPRequestParams | ||
onRequestWillStart?(requestParams: HTTPRequestParams): void | ||
onRequestSocketAssigned?(requestParams: HTTPRequestParams): void | ||
onSocketLookup?(requestParams: HTTPRequestParams): void | ||
onSocketConnect?(requestParams: HTTPRequestParams): void | ||
onSocketSecureConnect?(requestParams: HTTPRequestParams): void | ||
onResponseReadable?(requestParams: HTTPRequestParams): void | ||
onResponseEnd?(requestParams: HTTPRequestParams): void | ||
useSocketConnectionTimeout?: boolean | ||
} | ||
export interface GatewayConfiguration { | ||
Fetch: object | ||
HTTP: HTTPGatewayConfiguration | ||
Mock: object | ||
XHR: Partial<XhrGateway> | ||
enableHTTP408OnTimeouts?: boolean | ||
emulateHTTP?: boolean | ||
} | ||
export interface Configuration { | ||
@@ -199,10 +66,28 @@ fetch: typeof fetch | ||
middleware: Middleware[] | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
Promise: Promise<any> | ||
} | ||
export var configs: Configuration | ||
export interface Options<ResourcesType> { | ||
readonly clientId?: string | ||
readonly host?: string | ||
readonly allowResourceHostOverride?: boolean | ||
readonly parameterEncoder?: ParameterEncoderFn | ||
readonly ignoreGlobalMiddleware?: boolean | ||
readonly middleware?: Middleware[] | ||
readonly gatewayConfigs?: Partial<GatewayConfiguration> | ||
/** | ||
* @alias middleware | ||
*/ | ||
readonly middlewares?: Middleware[] | ||
readonly resources: ResourcesType | ||
} | ||
export const configs: Configuration | ||
export function setContext(context: Context): void | ||
export default function forge<ResourcesType>(options: Options<ResourcesType>): Client<ResourcesType> | ||
export default function forge<ResourcesType>( | ||
options: Options<ResourcesType> | ||
): Client<ResourcesType> | ||
} |
declare module 'mappersmith/middleware/basic-auth' { | ||
import {Middleware, Authorization} from 'mappersmith' | ||
import { Middleware, Authorization } from 'mappersmith' | ||
export default function BasicAuthMiddleware(authConfig: Authorization): Middleware | ||
} |
declare module 'mappersmith/middleware/csrf' { | ||
import {Middleware} from 'mappersmith' | ||
import { Middleware } from 'mappersmith' | ||
export default function CSRF(...headers: string[]): Middleware | ||
} |
declare module 'mappersmith/middleware/duration' { | ||
import {Middleware} from 'mappersmith' | ||
import { Middleware } from 'mappersmith' | ||
@@ -4,0 +4,0 @@ const Duration: Middleware |
declare module 'mappersmith/middleware/encode-json' { | ||
import {Middleware} from 'mappersmith' | ||
import { Middleware } from 'mappersmith' | ||
const EncodeJson: Middleware | ||
export var CONTENT_TYPE_JSON: string | ||
export const CONTENT_TYPE_JSON: string | ||
export default EncodeJson | ||
} |
declare module 'mappersmith/middleware/global-error-handler' { | ||
import {Middleware, Response} from 'mappersmith' | ||
import { Middleware, Response } from 'mappersmith' | ||
@@ -4,0 +4,0 @@ const GlobalErrorHandler: Middleware |
declare module 'mappersmith/middleware/log' { | ||
import {Middleware} from 'mappersmith' | ||
import { Middleware } from 'mappersmith' | ||
@@ -4,0 +4,0 @@ const Log: Middleware |
// @deprecated: Version 1 of retry is deprecated and should not be used anymore | ||
declare module 'mappersmith/middleware/retry' { | ||
import {Middleware} from 'mappersmith' | ||
import { Middleware } from 'mappersmith' | ||
@@ -8,18 +8,1 @@ const Retry: Middleware | ||
} | ||
declare module 'mappersmith/middleware/retry/v2' { | ||
import {Middleware, Response} from 'mappersmith' | ||
export interface RetryMiddlewareOptions { | ||
readonly headerRetryCount: string | ||
readonly headerRetryTime: string | ||
readonly maxRetryTimeInSecs: number | ||
readonly initialRetryTimeInSecs: number | ||
readonly factor: number | ||
readonly multiplier: number | ||
readonly retries: number | ||
validateRetry(response: Response): boolean | ||
} | ||
export default function Retry(config?: Partial<RetryMiddlewareOptions>): Middleware | ||
} |
declare module 'mappersmith/middleware/timeout' { | ||
import {Middleware} from 'mappersmith' | ||
import { Middleware } from 'mappersmith' | ||
@@ -4,0 +4,0 @@ export type Milliseconds = number |
@@ -14,14 +14,13 @@ declare module 'mappersmith/test' { | ||
export interface MockClient< | ||
ResourcesType, | ||
ResourceName extends keyof ResourcesType | ||
> { | ||
resource<ResourceName extends keyof ResourcesType>(name: ResourceName): MockClient<ResourcesType, ResourceName>; | ||
method(name: keyof ResourcesType[ResourceName]): this; | ||
with(args: Partial<Parameters>): this; | ||
status(responder: StatusHandler | number): this; | ||
headers(responseHeaders: Headers): this; | ||
response(responder: ResponseHandler | object | string): this; | ||
assertObject(): MockAssert; | ||
assertObjectAsync(): Promise<MockAssert>; | ||
export interface MockClient<ResourcesType, ResourceName extends keyof ResourcesType> { | ||
resource<ResourceName extends keyof ResourcesType>( | ||
name: ResourceName | ||
): MockClient<ResourcesType, ResourceName> | ||
method(name: keyof ResourcesType[ResourceName]): this | ||
with(args: Partial<Parameters>): this | ||
status(responder: StatusHandler | number): this | ||
headers(responseHeaders: Headers): this | ||
response(responder: ResponseHandler | object | string): this | ||
assertObject(): MockAssert | ||
assertObjectAsync(): Promise<MockAssert> | ||
} | ||
@@ -32,3 +31,6 @@ | ||
export function uninstall(): void | ||
export function mockClient<ResourcesType, ResourceName extends keyof ResourcesType = keyof ResourcesType>(client: Client<ResourcesType>): MockClient<ResourcesType, ResourceName> | ||
export function mockClient< | ||
ResourcesType, | ||
ResourceName extends keyof ResourcesType = keyof ResourcesType | ||
>(client: Client<ResourcesType>): MockClient<ResourcesType, ResourceName> | ||
@@ -39,3 +41,15 @@ export type MockRequestUrlFunction = (requestUrl: string, params: object) => string | ||
export type MockRequestHeaders = Headers | ||
export type MockRequestHeadersFunction = (requestHeaders: MockRequestHeaders) => MockRequestHeaders | ||
export type MockRequestHeadersFunction = ( | ||
requestHeaders: MockRequestHeaders | ||
) => MockRequestHeaders | ||
export type TestMatchPredicate = (value: string) => boolean | ||
export interface TestMatchFunctions { | ||
stringMatching(value: RegExp): TestMatchPredicate | ||
stringContaining(value: string): TestMatchPredicate | ||
uuid4(): TestMatchPredicate | ||
anything(): TestMatchPredicate | ||
} | ||
export interface MockRequestArgs { | ||
@@ -55,12 +69,3 @@ method: string | ||
export type TestMatchPredicate = (value: string) => boolean; | ||
export interface TestMatchFunctions { | ||
stringMatching(value: RegExp): TestMatchPredicate | ||
stringContaining(value: string): TestMatchPredicate | ||
uuid4(): TestMatchPredicate | ||
anything(): TestMatchPredicate | ||
} | ||
export var m: TestMatchFunctions | ||
export const m: TestMatchFunctions | ||
} | ||
@@ -13,4 +13,5 @@ "use strict"; | ||
try { | ||
// eslint-disable-next-line no-eval | ||
_process = eval('typeof __TEST_WEB__ === "undefined" && typeof process === "object" ? process : undefined'); | ||
} catch (e) {} // eslint-disable-line no-eval | ||
} catch (e) {} // eslint-disable-line no-empty | ||
@@ -76,3 +77,3 @@ | ||
/** | ||
* Gives time in miliseconds, but with sub-milisecond precision for Browser | ||
* Gives time in milliseconds, but with sub-millisecond precision for Browser | ||
* and Nodejs | ||
@@ -145,2 +146,3 @@ */ | ||
for (var i = 1; i < arguments.length; i++) { | ||
// eslint-disable-next-line prefer-rest-params | ||
var source = arguments[i]; | ||
@@ -185,3 +187,3 @@ | ||
if (charCode > 0xFF) { | ||
if (charCode > 0xff) { | ||
throw new Error("[Mappersmith] 'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."); | ||
@@ -188,0 +190,0 @@ } |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Deprecated
MaintenanceThe maintainer of the package marked it as deprecated. This could indicate that a single version should not be used, or that the package is no longer maintained and any new vulnerabilities will not be fixed.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
56
3063
1370
177257
51
1