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

js-tinyapi

Package Overview
Dependencies
Maintainers
4
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

js-tinyapi - npm Package Compare versions

Comparing version 0.1.0-alpha.5 to 0.1.0-alpha.6

4

index.js

@@ -92,3 +92,3 @@ (function webpackUniversalModuleDefinition(root, factory) {

"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _utils = __webpack_require__(/*! ./utils */ \"./src/utils.js\");\n\nvar _middleware = __webpack_require__(/*! ./middleware */ \"./src/middleware.js\");\n\nvar _middleware2 = _interopRequireDefault(_middleware);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\n/**\n * Automatic batching of requests.\n *\n * TODO\n */\nvar Batch = function (_Middleware) {\n _inherits(Batch, _Middleware);\n\n function Batch(opts) {\n _classCallCheck(this, Batch);\n\n var _this = _possibleConstructorReturn(this, (Batch.__proto__ || Object.getPrototypeOf(Batch)).call(this));\n\n _this.process = function (request) {\n var b = { request: request };\n\n // Note that the promise function argument runs synchronously\n // in order to explicitly support this use-case.\n var promise = new Promise(function (resolve, reject) {\n b.resolve = resolve;\n b.reject = reject;\n });\n _this.batch.push(b);\n if (_this.batch.length == _this.maximum) {\n clearTimeout(_this._to);\n _this.submitBatch();\n } else {\n\n // The first request to come in sets the timer, and we don't\n // reset the timer on any subsequent requests; it will just\n // catch anything that comes in within the timeout.\n if (!_this._to) {\n _this._to = setTimeout(_this.submitBatch, _this.timeout);\n }\n }\n\n return promise;\n };\n\n _this.submitBatch = function () {\n // TODO: Any chance of concurrency issues?\n var batch = _this.batch;\n _this.batch = [];\n _this._to = null;\n\n var request = _this.combineRequests(batch);\n _this.submit(request).then(function (r) {\n return _this.splitResponses(batch, r);\n });\n };\n\n _this.combineRequests = function (batch) {\n return {\n url: _this.batchUrl,\n method: 'post',\n body: JSON.stringify({\n batch: batch.map(function (b) {\n return _this.transformRequest(b.request);\n })\n }),\n headers: (0, _utils.fetchHeaders)({\n method: 'post'\n }),\n credentials: 'same-origin'\n };\n };\n\n _this.transformRequest = function (request) {\n var r = {\n url: request.url,\n method: request.method,\n headers: request.headers\n };\n if (request.body) {\n r.body = request.body;\n }\n if (request.headers) {\n r.headers = request.headers;\n }\n return r;\n };\n\n _this.splitResponses = function (batch, responses) {\n for (var ii = 0; ii < batch.length; ++ii) {\n var r = responses[ii];\n\n // Currently use the presence of \"status_code\" to know that\n // something has gone wrong.\n if (r.status_code && r.status_code >= 300) {\n batch[ii].reject({\n status_code: r.status_code,\n reason_phrase: r.reason_phrase,\n body: r.body\n });\n } else batch[ii].resolve(r.body);\n }\n };\n\n _this.batchUrl = opts.batchUrl;\n _this.batch = [];\n _this.maximum = 20;\n _this.timeout = opts.timeout; // ms\n _this._to = null;\n return _this;\n }\n\n return Batch;\n}(_middleware2.default);\n\nexports.default = Batch;\n\n//# sourceURL=webpack://js-tinyapi/./src/batch.js?");
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _utils = __webpack_require__(/*! ./utils */ \"./src/utils.js\");\n\nvar _middleware = __webpack_require__(/*! ./middleware */ \"./src/middleware.js\");\n\nvar _middleware2 = _interopRequireDefault(_middleware);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\n/**\n * Automatic batching of requests.\n *\n * TODO\n */\nvar Batch = function (_Middleware) {\n _inherits(Batch, _Middleware);\n\n function Batch(opts) {\n _classCallCheck(this, Batch);\n\n var _this = _possibleConstructorReturn(this, (Batch.__proto__ || Object.getPrototypeOf(Batch)).call(this));\n\n _this.process = function (request, options) {\n var b = { request: request };\n\n // Don't try and batch a request specifically flagged to be avoided.\n if (options.skipBatching) {\n return _this.submit(request);\n }\n\n // Note that the promise function argument runs synchronously\n // in order to explicitly support this use-case.\n var promise = new Promise(function (resolve, reject) {\n b.resolve = resolve;\n b.reject = reject;\n });\n _this.batch.push(b);\n if (_this.batch.length == _this.maximum) {\n clearTimeout(_this._to);\n _this.submitBatch();\n } else {\n\n // The first request to come in sets the timer, and we don't\n // reset the timer on any subsequent requests; it will just\n // catch anything that comes in within the timeout.\n if (!_this._to) {\n _this._to = setTimeout(_this.submitBatch, _this.timeout);\n }\n }\n\n return promise;\n };\n\n _this.submitBatch = function () {\n // TODO: Any chance of concurrency issues?\n var batch = _this.batch;\n _this.batch = [];\n _this._to = null;\n\n var request = _this.combineRequests(batch);\n _this.submit(request).then(function (r) {\n return _this.splitResponses(batch, r);\n });\n };\n\n _this.combineRequests = function (batch) {\n return {\n url: _this.batchUrl,\n method: 'post',\n body: JSON.stringify({\n batch: batch.map(function (b) {\n return _this.transformRequest(b.request);\n })\n }),\n headers: (0, _utils.fetchHeaders)({\n method: 'post'\n }),\n credentials: 'same-origin'\n };\n };\n\n _this.transformRequest = function (request) {\n var r = {\n url: request.url,\n method: request.method,\n headers: request.headers\n };\n if (request.body) {\n r.body = request.body;\n }\n if (request.headers) {\n r.headers = request.headers;\n }\n return r;\n };\n\n _this.splitResponses = function (batch, responses) {\n for (var ii = 0; ii < batch.length; ++ii) {\n var r = responses[ii];\n\n // Currently use the presence of \"status_code\" to know that\n // something has gone wrong.\n if (r.status_code && r.status_code >= 300) {\n batch[ii].reject({\n status_code: r.status_code,\n reason_phrase: r.reason_phrase,\n body: r.body\n });\n } else batch[ii].resolve(r.body);\n }\n };\n\n _this.batchUrl = opts.batchUrl;\n _this.batch = [];\n _this.maximum = 20;\n _this.timeout = opts.timeout; // ms\n _this._to = null;\n return _this;\n }\n\n return Batch;\n}(_middleware2.default);\n\nexports.default = Batch;\n\n//# sourceURL=webpack://js-tinyapi/./src/batch.js?");

@@ -117,3 +117,3 @@ /***/ }),

"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.Batch = exports.Middleware = exports.ApiError = exports.ajaxSettings = exports.postForm = exports.postJson = exports.ajax = undefined;\n\nvar _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };\n\nvar _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nvar _jsonapi = __webpack_require__(/*! ./jsonapi */ \"./src/jsonapi.js\");\n\nvar _utils = __webpack_require__(/*! ./utils */ \"./src/utils.js\");\n\nvar _errors = __webpack_require__(/*! ./errors */ \"./src/errors.js\");\n\nvar _middleware = __webpack_require__(/*! ./middleware */ \"./src/middleware.js\");\n\nvar _middleware2 = _interopRequireDefault(_middleware);\n\nvar _batch = __webpack_require__(/*! ./batch */ \"./src/batch.js\");\n\nvar _batch2 = _interopRequireDefault(_batch);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * Describes an API.\n */\nvar Api = function () {\n\n /**\n * Constructs an Api instance. Accepts an endpoint tree.\n */\n function Api() {\n var endpoints = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n _classCallCheck(this, Api);\n\n _initialiseProps.call(this);\n\n this.crud = {};\n this.middlewares = [];\n this.merge(endpoints);\n }\n\n /**\n * Merge an endpoint tree.\n */\n\n\n /**\n * Constructs an endpoint call function and sets it on the object.\n *\n * @param {string} name - The name of the endpoint function.\n * @param {string} path - The URL path to use.\n * @param {string} method - The method to use for this call.\n * @param {func} handler - A custom handler to call.\n */\n\n\n _createClass(Api, [{\n key: 'makeCrudEndpoints',\n\n\n /**\n * Automatically create a set of CRUD endpoint functions.\n */\n value: function makeCrudEndpoints(key, path) {\n var joiner = path[path.length - 1] == '/' ? '' : '/';\n var basePath = path + joiner + key;\n this.crud[key] = {\n list: this.makeEndpoint(key + 'List', basePath, 'GET'),\n create: this.makeEndpoint(key + 'Create', basePath, 'POST', {\n handler: function handler(req, payload) {\n var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n return req(_extends({}, opts, {\n payload: payload\n }));\n }\n }),\n detail: this.makeEndpoint(key + 'Get', basePath + '/{id}', 'GET', {\n handler: function handler(req, id) {\n var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n return req(_extends({}, opts, {\n params: { id: id }\n }));\n }\n }),\n update: this.makeEndpoint(key + 'Update', basePath + '/{id}', 'PATCH', {\n handler: function handler(req, id, payload) {\n var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n\n return req(_extends({}, opts, {\n params: { id: id },\n payload: payload\n }));\n }\n }),\n remove: this.makeEndpoint(key + 'Remove', basePath + '/{id}', 'DELETE', {\n handler: function handler(req, id) {\n var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n return req(_extends({}, opts, {\n params: { id: id }\n }));\n }\n }),\n options: this.makeEndpoint(key + 'Options', basePath, 'OPTIONS')\n };\n }\n\n /**\n * Perform a request call.\n */\n\n }, {\n key: 'request',\n value: function request(endpoint) {\n var _this = this;\n\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var _options$method = options.method,\n method = _options$method === undefined ? (endpoint.method || '').toLowerCase() : _options$method,\n _options$path = options.path,\n path = _options$path === undefined ? endpoint.path : _options$path,\n _options$params = options.params,\n params = _options$params === undefined ? {} : _options$params,\n payload = options.payload,\n _options$type = options.type,\n type = _options$type === undefined ? endpoint.type : _options$type,\n _options$extraHeaders = options.extraHeaders,\n extraHeaders = _options$extraHeaders === undefined ? {} : _options$extraHeaders,\n _options$include = options.include,\n include = _options$include === undefined ? endpoint.include || [] : _options$include,\n _options$filter = options.filter,\n filter = _options$filter === undefined ? endpoint.filter || {} : _options$filter,\n _options$sort = options.sort,\n sort = _options$sort === undefined ? endpoint.sort || [] : _options$sort,\n _options$fields = options.fields,\n fields = _options$fields === undefined ? endpoint.fields || [] : _options$fields;\n var urlRoot = options.urlRoot,\n _options$contentType = options.contentType,\n contentType = _options$contentType === undefined ? endpoint.contentType : _options$contentType;\n\n // \"type\" is used a convenient shorthand for the content type.\n // \"contentType\" still trumps it.\n\n if (!!type && !contentType) {\n contentType = _utils.contentTypes[type];\n }\n\n // Process the body. This can end up being a FormData object\n // or a json string.\n var body = void 0;\n var queryString = [];\n if (method != 'get' && method != 'options') {\n if (payload !== undefined) {\n if ((0, _utils.matchContentType)(contentType, 'form') || (0, _utils.matchContentType)(contentType, 'multiForm')) {\n body = (0, _utils.makeFormData)(payload);\n } else {\n body = JSON.stringify(payload || {});\n }\n }\n } else {\n if (payload !== undefined) {\n for (var k in payload) {\n queryString.push(k + '=' + encodeURIComponent(payload[k]));\n }\n }\n }\n\n // Replace any URL arguments. This is typically just the ID of\n // an object.\n var finalPath = (0, _utils.supplant)(path, params);\n\n // Add any JSONAPI query strings.\n finalPath += (0, _jsonapi.jsonApiQuery)({\n initial: queryString,\n include: include,\n filter: filter,\n sort: sort,\n fields: fields,\n rawFilters: (0, _utils.takeFirst)(options.rawFilters, this.rawFilters, endpoint.rawFilters)\n });\n\n // If we've been given an URL root, add it in here. This is useful\n // for writing Node tests.\n if (urlRoot) {\n if (urlRoot[urlRoot.length - 1] == '/') {\n urlRoot = urlRoot.substring(0, urlRoot.length - 1);\n }\n finalPath = urlRoot + finalPath;\n }\n\n // Prepare the request object. This is passed to either \"ajax\"\n // or the middlewares.\n var req = {\n url: finalPath,\n method: method,\n body: body,\n contentType: contentType,\n extraHeaders: extraHeaders,\n bearer: this.bearer\n };\n\n // If there are no middlewares, we are free to fulfill the request\n // now.\n if (!this.middlewares.length) {\n console.debug('API ' + method + ' ' + type + ': ' + finalPath, payload);\n return (0, _utils.ajax)(req);\n }\n\n // Otherwise, we need to pipe through all the middleware. This works\n // by iterating over middleware in order until one returns a promise.\n // We then chain the remaining middleware after that promise. It's the\n // user's responsibility to ensure only one middleware wants to return\n // a promise.\n else {\n req = (0, _utils.makeRequest)(req);\n var ii = 0;\n var obj = this.middlewares[ii++].process(req);\n for (; ii < this.middlewares.length; ++ii) {\n if (Promise.resolve(obj) == obj) {\n var _loop = function _loop() {\n var mw = _this.middlewares[ii];\n obj = obj.then(function (r) {\n return mw.process(r);\n });\n };\n\n for (; ii < this.middlewares.length; ++ii) {\n _loop();\n }\n } else {\n obj = this.middlewares[ii].process(obj);\n }\n }\n return obj;\n }\n }\n }]);\n\n return Api;\n}();\n\nvar _initialiseProps = function _initialiseProps() {\n var _this2 = this;\n\n this.pushMiddleware = function (middleware) {\n if (!Array.isArray(middleware)) {\n middleware = [middleware];\n }\n middleware.forEach(function (m) {\n m.api = _this2;\n _this2.middlewares.push(m);\n });\n };\n\n this.unshiftMiddleware = function (middleware) {\n if (!Array.isArray(middleware)) {\n middleware = [middleware];\n }\n middleware.forEach(function (m) {\n m.api = _this2;\n _this2.middlewares.unshift(m);\n });\n };\n\n this.merge = function (endpoints) {\n var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n\n if (!endpoints) {\n throw new Error('Empty endpoint data given to Api.merge.');\n }\n\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = Object.keys(endpoints)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var key = _step.value;\n\n var ep = endpoints[key];\n\n // Check if we're looking at an endpoint.\n var match = /^(GET|POST|PUT|PATCH|DELETE|CRUD)$/.exec(key);\n if (match) {\n\n // If we matched a CRUD endpoint, perform the setup.\n if (match[1] == 'CRUD') {\n var ii = path.lastIndexOf('/') + 1;\n var crudKey = path.slice(ii);\n var crudPath = path.slice(0, ii);\n _this2.makeCrudEndpoints(crudKey, crudPath);\n }\n\n // The endpoint can be just the name of the function\n // or it can be an object of details.\n else {\n if (!(ep instanceof Object)) {\n ep = { name: ep };\n }\n var _ep = ep,\n name = _ep.name,\n _ep$options = _ep.options,\n options = _ep$options === undefined ? {} : _ep$options;\n\n // Make the endpoint.\n\n _this2.makeEndpoint(name, path + '/', match[1], options);\n }\n }\n\n // If not an endpoint, check for a CRUD shorthand.\n else if (ep == 'CRUD') {\n _this2.makeCrudEndpoints(key, path);\n }\n\n // If not an endpoint or CRUD, continue down the tree.\n else {\n _this2.merge(ep, path + '/' + key);\n }\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n };\n\n this.makeEndpoint = function (name, path, method) {\n var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n\n\n // Fail loudly if we're overriding names.\n if (_this2[name] !== undefined) {\n throw new Error('Duplicate name in Api: ' + name);\n }\n\n // Prepare the context to be passed to the request method. This\n // will be passed to the each invocation of the endpoint call\n // as a set of defaults.\n var ctx = _extends({}, opts, {\n path: (0, _utils.addTrailingSlash)(path),\n method: method\n });\n\n // If we were given a function to call, bind it appropriately.\n // Otherwise just use the standard request.\n var request = function request(opts) {\n return _this2.request(ctx, opts);\n };\n var handler = opts.handler;\n\n if (handler !== undefined) {\n\n // The first argument to the handler will be a function to call\n // the builtin handler. This allows the handler to easily finalise\n // the call after modifying any options.\n var wrapper = function wrapper() {\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return handler.apply(undefined, [request].concat(args));\n };\n wrapper.context = ctx;\n _this2[name] = wrapper;\n } else {\n request.context = ctx;\n _this2[name] = request;\n }\n\n return _this2[name];\n };\n};\n\nexports.default = Api;\nexports.ajax = _utils.ajax;\nexports.postJson = _utils.postJson;\nexports.postForm = _utils.postForm;\nexports.ajaxSettings = _utils.ajaxSettings;\nexports.ApiError = _errors.ApiError;\nexports.Middleware = _middleware2.default;\nexports.Batch = _batch2.default;\n\n//# sourceURL=webpack://js-tinyapi/./src/index.js?");
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.Batch = exports.Middleware = exports.ApiError = exports.ajaxSettings = exports.postForm = exports.postJson = exports.ajax = undefined;\n\nvar _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };\n\nvar _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nvar _jsonapi = __webpack_require__(/*! ./jsonapi */ \"./src/jsonapi.js\");\n\nvar _utils = __webpack_require__(/*! ./utils */ \"./src/utils.js\");\n\nvar _errors = __webpack_require__(/*! ./errors */ \"./src/errors.js\");\n\nvar _middleware = __webpack_require__(/*! ./middleware */ \"./src/middleware.js\");\n\nvar _middleware2 = _interopRequireDefault(_middleware);\n\nvar _batch = __webpack_require__(/*! ./batch */ \"./src/batch.js\");\n\nvar _batch2 = _interopRequireDefault(_batch);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * Describes an API.\n */\nvar Api = function () {\n\n /**\n * Constructs an Api instance. Accepts an endpoint tree.\n */\n function Api() {\n var endpoints = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n _classCallCheck(this, Api);\n\n _initialiseProps.call(this);\n\n this.crud = {};\n this.middlewares = [];\n this.merge(endpoints);\n }\n\n /**\n * Merge an endpoint tree.\n */\n\n\n /**\n * Constructs an endpoint call function and sets it on the object.\n *\n * @param {string} name - The name of the endpoint function.\n * @param {string} path - The URL path to use.\n * @param {string} method - The method to use for this call.\n * @param {func} handler - A custom handler to call.\n */\n\n\n _createClass(Api, [{\n key: 'makeCrudEndpoints',\n\n\n /**\n * Automatically create a set of CRUD endpoint functions.\n */\n value: function makeCrudEndpoints(key, path) {\n var joiner = path[path.length - 1] == '/' ? '' : '/';\n var basePath = path + joiner + key;\n this.crud[key] = {\n list: this.makeEndpoint(key + 'List', basePath, 'GET'),\n create: this.makeEndpoint(key + 'Create', basePath, 'POST', {\n handler: function handler(req, payload) {\n var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n return req(_extends({}, opts, {\n payload: payload\n }));\n }\n }),\n detail: this.makeEndpoint(key + 'Get', basePath + '/{id}', 'GET', {\n handler: function handler(req, id) {\n var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n return req(_extends({}, opts, {\n params: { id: id }\n }));\n }\n }),\n update: this.makeEndpoint(key + 'Update', basePath + '/{id}', 'PATCH', {\n handler: function handler(req, id, payload) {\n var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n\n return req(_extends({}, opts, {\n params: { id: id },\n payload: payload\n }));\n }\n }),\n remove: this.makeEndpoint(key + 'Remove', basePath + '/{id}', 'DELETE', {\n handler: function handler(req, id) {\n var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n return req(_extends({}, opts, {\n params: { id: id }\n }));\n }\n }),\n options: this.makeEndpoint(key + 'Options', basePath, 'OPTIONS')\n };\n }\n\n /**\n * Perform a request call.\n */\n\n }, {\n key: 'request',\n value: function request(endpoint) {\n var _this = this;\n\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n var _options$method = options.method,\n method = _options$method === undefined ? (endpoint.method || '').toLowerCase() : _options$method,\n _options$path = options.path,\n path = _options$path === undefined ? endpoint.path : _options$path,\n _options$params = options.params,\n params = _options$params === undefined ? {} : _options$params,\n payload = options.payload,\n _options$type = options.type,\n type = _options$type === undefined ? endpoint.type : _options$type,\n _options$extraHeaders = options.extraHeaders,\n extraHeaders = _options$extraHeaders === undefined ? {} : _options$extraHeaders,\n _options$include = options.include,\n include = _options$include === undefined ? endpoint.include || [] : _options$include,\n _options$filter = options.filter,\n filter = _options$filter === undefined ? endpoint.filter || {} : _options$filter,\n _options$sort = options.sort,\n sort = _options$sort === undefined ? endpoint.sort || [] : _options$sort,\n _options$fields = options.fields,\n fields = _options$fields === undefined ? endpoint.fields || [] : _options$fields,\n rawFilters = options.rawFilters,\n otherOptions = _objectWithoutProperties(options, ['method', 'path', 'params', 'payload', 'type', 'extraHeaders', 'include', 'filter', 'sort', 'fields', 'rawFilters']);\n\n var urlRoot = options.urlRoot,\n _options$contentType = options.contentType,\n contentType = _options$contentType === undefined ? endpoint.contentType : _options$contentType;\n\n // \"type\" is used a convenient shorthand for the content type.\n // \"contentType\" still trumps it.\n\n if (!!type && !contentType) {\n contentType = _utils.contentTypes[type];\n }\n\n // Process the body. This can end up being a FormData object\n // or a json string.\n var body = void 0;\n var queryString = [];\n if (method != 'get' && method != 'options') {\n if (payload !== undefined) {\n if ((0, _utils.matchContentType)(contentType, 'form') || (0, _utils.matchContentType)(contentType, 'multiForm')) {\n body = (0, _utils.makeFormData)(payload);\n } else {\n body = JSON.stringify(payload || {});\n }\n }\n } else {\n if (payload !== undefined) {\n for (var k in payload) {\n queryString.push(k + '=' + encodeURIComponent(payload[k]));\n }\n }\n }\n\n // Replace any URL arguments. This is typically just the ID of\n // an object.\n var finalPath = (0, _utils.supplant)(path, params);\n\n // Add any JSONAPI query strings.\n finalPath += (0, _jsonapi.jsonApiQuery)({\n initial: queryString,\n include: include,\n filter: filter,\n sort: sort,\n fields: fields,\n rawFilters: (0, _utils.takeFirst)(rawFilters, this.rawFilters, endpoint.rawFilters)\n });\n\n // If we've been given an URL root, add it in here. This is useful\n // for writing Node tests.\n if (urlRoot) {\n if (urlRoot[urlRoot.length - 1] == '/') {\n urlRoot = urlRoot.substring(0, urlRoot.length - 1);\n }\n finalPath = urlRoot + finalPath;\n }\n\n // Prepare the request object. This is passed to either \"ajax\"\n // or the middlewares.\n var req = {\n url: finalPath,\n method: method,\n body: body,\n contentType: contentType,\n extraHeaders: extraHeaders,\n bearer: this.bearer\n };\n\n // If there are no middlewares, we are free to fulfill the request\n // now.\n if (!this.middlewares.length) {\n console.debug('API ' + method + ' ' + type + ': ' + finalPath, payload);\n return (0, _utils.ajax)(req);\n }\n\n // Otherwise, we need to pipe through all the middleware. This works\n // by iterating over middleware in order until one returns a promise.\n // We then chain the remaining middleware after that promise. It's the\n // user's responsibility to ensure only one middleware wants to return\n // a promise.\n else {\n req = (0, _utils.makeRequest)(req);\n var ii = 0;\n var obj = this.middlewares[ii++].process(req, otherOptions);\n for (; ii < this.middlewares.length; ++ii) {\n if (Promise.resolve(obj) == obj) {\n var _loop = function _loop() {\n var mw = _this.middlewares[ii];\n obj = obj.then(function (r) {\n return mw.process(r, otherOptions);\n });\n };\n\n for (; ii < this.middlewares.length; ++ii) {\n _loop();\n }\n } else {\n obj = this.middlewares[ii].process(obj, otherOptions);\n }\n }\n return obj;\n }\n }\n }]);\n\n return Api;\n}();\n\nvar _initialiseProps = function _initialiseProps() {\n var _this2 = this;\n\n this.pushMiddleware = function (middleware) {\n if (!Array.isArray(middleware)) {\n middleware = [middleware];\n }\n middleware.forEach(function (m) {\n m.api = _this2;\n _this2.middlewares.push(m);\n });\n };\n\n this.unshiftMiddleware = function (middleware) {\n if (!Array.isArray(middleware)) {\n middleware = [middleware];\n }\n middleware.forEach(function (m) {\n m.api = _this2;\n _this2.middlewares.unshift(m);\n });\n };\n\n this.merge = function (endpoints) {\n var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n\n if (!endpoints) {\n throw new Error('Empty endpoint data given to Api.merge.');\n }\n\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = Object.keys(endpoints)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var key = _step.value;\n\n var ep = endpoints[key];\n\n // Check if we're looking at an endpoint.\n var match = /^(GET|POST|PUT|PATCH|DELETE|CRUD)$/.exec(key);\n if (match) {\n\n // If we matched a CRUD endpoint, perform the setup.\n if (match[1] == 'CRUD') {\n var ii = path.lastIndexOf('/') + 1;\n var crudKey = path.slice(ii);\n var crudPath = path.slice(0, ii);\n _this2.makeCrudEndpoints(crudKey, crudPath);\n }\n\n // The endpoint can be just the name of the function\n // or it can be an object of details.\n else {\n if (!(ep instanceof Object)) {\n ep = { name: ep };\n }\n var _ep = ep,\n name = _ep.name,\n _ep$options = _ep.options,\n options = _ep$options === undefined ? {} : _ep$options;\n\n // Make the endpoint.\n\n _this2.makeEndpoint(name, path + '/', match[1], options);\n }\n }\n\n // If not an endpoint, check for a CRUD shorthand.\n else if (ep == 'CRUD') {\n _this2.makeCrudEndpoints(key, path);\n }\n\n // If not an endpoint or CRUD, continue down the tree.\n else {\n _this2.merge(ep, path + '/' + key);\n }\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n };\n\n this.makeEndpoint = function (name, path, method) {\n var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n\n\n // Fail loudly if we're overriding names.\n if (_this2[name] !== undefined) {\n throw new Error('Duplicate name in Api: ' + name);\n }\n\n // Prepare the context to be passed to the request method. This\n // will be passed to the each invocation of the endpoint call\n // as a set of defaults.\n var ctx = _extends({}, opts, {\n path: (0, _utils.addTrailingSlash)(path),\n method: method\n });\n\n // If we were given a function to call, bind it appropriately.\n // Otherwise just use the standard request.\n var request = function request(opts) {\n return _this2.request(ctx, opts);\n };\n var handler = opts.handler;\n\n if (handler !== undefined) {\n\n // The first argument to the handler will be a function to call\n // the builtin handler. This allows the handler to easily finalise\n // the call after modifying any options.\n var wrapper = function wrapper() {\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return handler.apply(undefined, [request].concat(args));\n };\n wrapper.context = ctx;\n _this2[name] = wrapper;\n } else {\n request.context = ctx;\n _this2[name] = request;\n }\n\n return _this2[name];\n };\n};\n\nexports.default = Api;\nexports.ajax = _utils.ajax;\nexports.postJson = _utils.postJson;\nexports.postForm = _utils.postForm;\nexports.ajaxSettings = _utils.ajaxSettings;\nexports.ApiError = _errors.ApiError;\nexports.Middleware = _middleware2.default;\nexports.Batch = _batch2.default;\n\n//# sourceURL=webpack://js-tinyapi/./src/index.js?");

@@ -120,0 +120,0 @@ /***/ }),

{
"name": "js-tinyapi",
"version": "0.1.0-alpha.5",
"version": "0.1.0-alpha.6",
"description": "A simple and lightweight API helper.",

@@ -5,0 +5,0 @@ "repository": {

@@ -202,3 +202,5 @@ import { jsonApiQuery } from './jsonapi'

sort = (endpoint.sort || []),
fields = (endpoint.fields || [])
fields = (endpoint.fields || []),
rawFilters,
...otherOptions
} = options

@@ -249,3 +251,3 @@ let {

fields,
rawFilters: takeFirst(options.rawFilters, this.rawFilters, endpoint.rawFilters)
rawFilters: takeFirst(rawFilters, this.rawFilters, endpoint.rawFilters)
})

@@ -288,3 +290,3 @@

let ii = 0
let obj = this.middlewares[ii++].process( req )
let obj = this.middlewares[ii++].process( req, otherOptions )
for( ; ii < this.middlewares.length; ++ii ) {

@@ -294,7 +296,7 @@ if( Promise.resolve( obj ) == obj ) {

let mw = this.middlewares[ii]
obj = obj.then( r => mw.process( r ) )
obj = obj.then( r => mw.process( r, otherOptions ) )
}
}
else {
obj = this.middlewares[ii].process( obj )
obj = this.middlewares[ii].process( obj, otherOptions )
}

@@ -301,0 +303,0 @@ }

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