js-tinyapi
Advanced tools
Comparing version 0.1.0-alpha.4 to 0.1.0-alpha.5
@@ -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\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 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(r.body);\n } else {\n batch[ii].resolve(r.body);\n }\n }\n };\n\n _this.batchUrl = opts.batchUrl;\n _this.batch = [];\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) {\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?"); | ||
@@ -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)({ initial: queryString, include: include, filter: filter, sort: sort, fields: fields });\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 (0, _utils.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 _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?"); | ||
@@ -130,3 +130,3 @@ /***/ }), | ||
"use strict"; | ||
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nfunction jsonApiList(values, key) {\n if (!Array.isArray(values)) values = [values];\n if (values && values.length) return [key + '=' + values.join(',')];\n return [];\n}\n\nfunction jsonApiInclude(values, key) {\n return jsonApiList(values, key || 'include');\n}\n\nfunction jsonApiSort(values, key) {\n return jsonApiList(values, key || 'sort');\n}\n\nfunction jsonApiFilter(values, key) {\n if (values && Object.keys(values).length) {\n var k = key || 'filter';\n return Object.keys(values).map(function (attr) {\n return 'filter[' + attr + ']=' + values[attr];\n });\n }\n return [];\n}\n\nfunction jsonApiFields(values, key) {\n if (values && Object.keys(values).length) {\n var k = key || 'filter';\n return Object.keys(values).map(function (res) {\n return 'fields[' + res + ']=' + values[res];\n });\n }\n return [];\n}\n\nfunction jsonApiQuery(opts) {\n var _ref = opts || {},\n include = _ref.include,\n sort = _ref.sort,\n filter = _ref.filter,\n fields = _ref.fields;\n\n var parts = (opts.initial || []).concat(jsonApiInclude(include).concat(jsonApiFilter(filter).concat(jsonApiSort(sort).concat(jsonApiFields(fields)))));\n if (parts.length > 0) return '?' + parts.join('&');\n return '';\n}\n\nexports.jsonApiQuery = jsonApiQuery;\n\n//# sourceURL=webpack://js-tinyapi/./src/jsonapi.js?"); | ||
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nfunction jsonApiList(values, key) {\n if (!Array.isArray(values)) values = [values];\n if (values && values.length) return [key + '=' + values.join(',')];\n return [];\n}\n\nfunction jsonApiInclude(values, key) {\n return jsonApiList(values, key || 'include');\n}\n\nfunction jsonApiSort(values, key) {\n return jsonApiList(values, key || 'sort');\n}\n\nfunction jsonApiFilter(values, options) {\n var _ref = options || {},\n key = _ref.key,\n raw = _ref.raw;\n\n if (values && Object.keys(values).length) {\n var k = key || 'filter';\n var tmpl = raw ? function (k, v) {\n return k + '=' + v;\n } : function (k, v) {\n return 'filter[' + k + ']=' + v;\n };\n return Object.keys(values).map(function (attr) {\n return tmpl(attr, values[attr]);\n });\n }\n return [];\n}\n\nfunction jsonApiFields(values, key) {\n if (values && Object.keys(values).length) {\n var k = key || 'filter';\n return Object.keys(values).map(function (res) {\n return 'fields[' + res + ']=' + values[res];\n });\n }\n return [];\n}\n\nfunction jsonApiQuery(opts) {\n var _ref2 = opts || {},\n include = _ref2.include,\n sort = _ref2.sort,\n filter = _ref2.filter,\n fields = _ref2.fields,\n raw = _ref2.rawFilters;\n\n var parts = (opts.initial || []).concat(jsonApiInclude(include).concat(jsonApiFilter(filter, { raw: raw }).concat(jsonApiSort(sort).concat(jsonApiFields(fields)))));\n if (parts.length > 0) return '?' + parts.join('&');\n return '';\n}\n\nexports.jsonApiQuery = jsonApiQuery;\n\n//# sourceURL=webpack://js-tinyapi/./src/jsonapi.js?"); | ||
@@ -155,3 +155,3 @@ /***/ }), | ||
"use strict"; | ||
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.fetchHeaders = exports.ajaxWithRequest = exports.makeRequest = exports.makeFormData = exports.matchContentType = exports.contentTypes = exports.ajaxSettings = exports.postForm = exports.postJson = exports.ajax = exports.addTrailingSlash = exports.debug = undefined;\nexports.supplant = supplant;\nexports.capitalize = capitalize;\n\nvar _jsCookie = __webpack_require__(/*! js-cookie */ \"js-cookie\");\n\nvar _jsCookie2 = _interopRequireDefault(_jsCookie);\n\nvar _errors = __webpack_require__(/*! ./errors */ \"./src/errors.js\");\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\n/**\n * Make it a little easier to use content types.\n */\nvar contentTypes = {\n form: 'application/x-www-form-urlencoded',\n multiForm: 'multipart/form-data',\n json: 'application/json',\n jsonApi: 'application/vnd.api+json'\n};\n\n/**\n * TODO: Get rid of this, we can optimise better without it.\n */\nfunction debug() {\n if (console.debug) console.debug.apply(null, arguments);\n}\n\nfunction matchContentType(src, id) {\n if (!src) return false;\n var ii = src.indexOf(';');\n if (ii >= 0) src = src.substring(0, ii);\n return src.toLowerCase() == contentTypes[id];\n}\n\nfunction addTrailingSlash(path) {\n return path + (path[path.length - 1] == '/' ? '' : '/');\n}\n\n/**\n * Find and replace terms in a string.\n *\n * Terms are identified by being surrounded by curly braces, such as\n * this: \"a string with a {substitution}\". Here, \"substitution\" will\n * be replaced by looking for the same named key in the supplied\n * mapping.\n *\n * @param {string} text - The string with replacements.\n * @param {object} mapping - The mapping.\n */\nfunction supplant(text, mapping) {\n return text.replace(/{([^{}]*)}/g, function (a, b) {\n var r = mapping[b];\n if (r === undefined) {\n throw new _errors.ApiError('Missing string template: ' + b);\n }\n return typeof r === 'string' || typeof r === 'number' ? r : a;\n });\n}\n\n/**\n * Capitalize a string.\n *\n * @param {string} text - The string to capitalize.\n */\nfunction capitalize(text) {\n return text[0].toUpperCase() + text.slice(1);\n}\n\n/**\n * Global storage for authorization and CSRF.\n *\n * Often when making requests the same credentials or CSRF token needs\n * to be used. This is a place to store these details. Currently\n * accepts \"csrf\" and \"bearer\" values. Upon initialisation cookies\n * are examined for a current value for the CSRF token (looks for\n * a cookie called \"csrftoken\").\n */\nvar ajaxSettings = {\n csrf: _jsCookie2.default ? _jsCookie2.default.get('csrftoken') || '' : '',\n bearer: null\n};\n\n/**\n * Construct headers for a fetch request.\n *\n * Uses the HTML5 Headers object to formulate an appropriate set of\n * headers based on the supplied options.\n *\n * @param {string} method - The request method. Defaults to \"get\".\n * @param {string} contentType - The content type of the request. Defaults to \"application/json\".\n * @param {object} extraHeaders - Custom headers to add.\n * @param {boolean} useBearer - Flag indicating whether to include bearer authorization.\n */\nfunction fetchHeaders(opts) {\n var _ref = opts || {},\n _ref$method = _ref.method,\n method = _ref$method === undefined ? 'get' : _ref$method,\n _ref$contentType = _ref.contentType,\n contentType = _ref$contentType === undefined ? contentTypes.json : _ref$contentType,\n extraHeaders = _ref.extraHeaders,\n _ref$useBearer = _ref.useBearer,\n useBearer = _ref$useBearer === undefined ? true : _ref$useBearer,\n bearer = _ref.bearer;\n\n var headers = new Headers({\n 'X-Requested-With': 'XMLHttpRequest'\n });\n headers.set('Content-Type', contentType);\n if (!/^(GET|HEAD|OPTIONS\\TRACE)$/i.test(method)) {\n headers.set('X-CSRFToken', ajaxSettings.csrf);\n }\n if (!bearer) bearer = ajaxSettings.bearer;\n if (useBearer && bearer) {\n headers.set('Authorization', 'Bearer ' + bearer);\n }\n for (var k in extraHeaders || {}) {\n headers.set(k, extraHeaders[k]);\n }\n return headers;\n}\n\nfunction makeRequest(opts) {\n var method = (opts.method || 'get').toUpperCase();\n\n var _ref2 = opts || {},\n url = _ref2.url,\n body = _ref2.body,\n contentType = _ref2.contentType,\n extraHeaders = _ref2.extraHeaders,\n _ref2$useBearer = _ref2.useBearer,\n useBearer = _ref2$useBearer === undefined ? true : _ref2$useBearer,\n bearer = _ref2.bearer;\n\n var request = {\n url: url,\n method: method,\n headers: fetchHeaders({\n method: method,\n contentType: contentType,\n extraHeaders: extraHeaders,\n useBearer: useBearer,\n bearer: bearer\n }),\n credentials: 'same-origin'\n };\n if (method != 'GET' && method != 'HEAD' && method != 'OPTIONS') {\n request.body = body;\n }\n return request;\n}\n\n/**\n * Perform an ajax request.\n *\n * Uses HTML5 fetch to perform an ajax request according to parameters\n * supplied via the options object.\n *\n * @param {string} url - The URL to make the request to.\n * @param {string} method - The request method. Defaults to \"get\".\n * @param {string} body - Data to be sent with the request.\n * @param {string} contentType - The content type of the request. Defaults to \"application/json\".\n * @param {object} extraHeaders - Custom headers to add.\n * @param {boolean} useBearer - Flag indicating whether to include bearer authorization.\n */\nfunction ajax(opts) {\n var method = (opts.method || 'get').toUpperCase();\n\n var _ref3 = opts || {},\n url = _ref3.url,\n body = _ref3.body,\n contentType = _ref3.contentType,\n extraHeaders = _ref3.extraHeaders,\n _ref3$useBearer = _ref3.useBearer,\n useBearer = _ref3$useBearer === undefined ? true : _ref3$useBearer,\n bearer = _ref3.bearer;\n\n var requestInit = {\n method: method,\n headers: fetchHeaders({\n method: method,\n contentType: contentType,\n extraHeaders: extraHeaders,\n useBearer: useBearer,\n bearer: bearer\n }),\n credentials: 'same-origin'\n };\n if (method != 'GET' && method != 'HEAD' && method != 'OPTIONS') {\n requestInit.body = body;\n }\n\n var request = new Request(url, requestInit);\n return fetch(request).then(function (response) {\n if (!!response.ok) {\n if (response.status == 204) {\n return {};\n }\n if (typeof TINYAPI_NODE !== 'undefined' && TINYAPI_NODE) {\n return response;\n }\n if (!!response.json) {\n return response.json();\n } else {\n return response;\n }\n }\n if (!!response.json) {\n return response.json().catch(function (e) {\n return Object({ status: response.status });\n }).then(function (e) {\n return Promise.reject(e);\n });\n } else {\n return response;\n }\n });\n}\n\nfunction ajaxWithRequest(opts) {\n var url = opts.url,\n requestInit = _objectWithoutProperties(opts, ['url']);\n\n var request = new Request(url, requestInit);\n return fetch(request).then(function (response) {\n if (!!response.ok) {\n if (response.status == 204) {\n return {};\n }\n if (typeof TINYAPI_NODE !== 'undefined' && TINYAPI_NODE) {\n return response;\n }\n if (!!response.json) {\n return response.json();\n } else {\n return response;\n }\n }\n if (!!response.json) {\n return response.json().catch(function (e) {\n return Object({ status: response.status });\n }).then(function (e) {\n return Promise.reject(e);\n });\n } else {\n return response;\n }\n });\n}\n\n/**\n * Post JSON data.\n *\n * @param {string} url - The URL to make the request to.\n * @param {object} payload - Data to be sent with the request.\n * @param {string} contentType - The content type of the request. Defaults to \"application/json\".\n * @param {boolean} useBearer - Flag indicating whether to include bearer authorization.\n */\nfunction postJson(_ref4) {\n var url = _ref4.url,\n payload = _ref4.payload,\n contentType = _ref4.contentType,\n useBearer = _ref4.useBearer;\n\n return ajax({\n url: url,\n method: 'post',\n body: JSON.stringify(payload || {}),\n contentType: contentType,\n useBearer: useBearer\n });\n}\n\n/**\n * Convert an object into HTML5 FormData.\n */\nfunction makeFormData(payload) {\n var body = new FormData();\n for (var k in payload || {}) {\n body.append(k, payload[k]);\n }\n return body;\n}\n\n/**\n * Post form data.\n *\n * @param {string} url - The URL to make the request to.\n * @param {object} payload - Data to be sent with the request.\n * @param {boolean} useBearer - Flag indicating whether to include bearer authorization.\n */\nfunction postForm(_ref5) {\n var url = _ref5.url,\n payload = _ref5.payload,\n useBearer = _ref5.useBearer;\n\n return ajax({\n url: url,\n body: makeFormData(payload),\n method: 'post',\n useBearer: useBearer\n });\n}\n\nexports.debug = debug;\nexports.addTrailingSlash = addTrailingSlash;\nexports.ajax = ajax;\nexports.postJson = postJson;\nexports.postForm = postForm;\nexports.ajaxSettings = ajaxSettings;\nexports.contentTypes = contentTypes;\nexports.matchContentType = matchContentType;\nexports.makeFormData = makeFormData;\nexports.makeRequest = makeRequest;\nexports.ajaxWithRequest = ajaxWithRequest;\nexports.fetchHeaders = fetchHeaders;\n\n//# sourceURL=webpack://js-tinyapi/./src/utils.js?"); | ||
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.fetchHeaders = exports.ajaxWithRequest = exports.makeRequest = exports.makeFormData = exports.matchContentType = exports.contentTypes = exports.ajaxSettings = exports.postForm = exports.postJson = exports.ajax = exports.addTrailingSlash = undefined;\nexports.supplant = supplant;\nexports.capitalize = capitalize;\nexports.takeFirst = takeFirst;\n\nvar _jsCookie = __webpack_require__(/*! js-cookie */ \"js-cookie\");\n\nvar _jsCookie2 = _interopRequireDefault(_jsCookie);\n\nvar _errors = __webpack_require__(/*! ./errors */ \"./src/errors.js\");\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\n/**\n * Make it a little easier to use content types.\n */\nvar contentTypes = {\n form: 'application/x-www-form-urlencoded',\n multiForm: 'multipart/form-data',\n json: 'application/json',\n jsonApi: 'application/vnd.api+json'\n};\n\nfunction matchContentType(src, id) {\n if (!src) return false;\n var ii = src.indexOf(';');\n if (ii >= 0) src = src.substring(0, ii);\n return src.toLowerCase() == contentTypes[id];\n}\n\nfunction addTrailingSlash(path) {\n return path + (path[path.length - 1] == '/' ? '' : '/');\n}\n\n/**\n * Find and replace terms in a string.\n *\n * Terms are identified by being surrounded by curly braces, such as\n * this: \"a string with a {substitution}\". Here, \"substitution\" will\n * be replaced by looking for the same named key in the supplied\n * mapping.\n *\n * @param {string} text - The string with replacements.\n * @param {object} mapping - The mapping.\n */\nfunction supplant(text, mapping) {\n return text.replace(/{([^{}]*)}/g, function (a, b) {\n var r = mapping[b];\n if (r === undefined) {\n throw new _errors.ApiError('Missing string template: ' + b);\n }\n return typeof r === 'string' || typeof r === 'number' ? r : a;\n });\n}\n\n/**\n * Capitalize a string.\n *\n * @param {string} text - The string to capitalize.\n */\nfunction capitalize(text) {\n return text[0].toUpperCase() + text.slice(1);\n}\n\nfunction isEmpty(value) {\n return value === '' || value === undefined || value === null;\n}\n\n/**\n * Global storage for authorization and CSRF.\n *\n * Often when making requests the same credentials or CSRF token needs\n * to be used. This is a place to store these details. Currently\n * accepts \"csrf\" and \"bearer\" values. Upon initialisation cookies\n * are examined for a current value for the CSRF token (looks for\n * a cookie called \"csrftoken\").\n */\nvar ajaxSettings = {\n csrf: _jsCookie2.default ? _jsCookie2.default.get('csrftoken') : undefined,\n bearer: null\n};\n\n/**\n * Construct headers for a fetch request.\n *\n * Uses the HTML5 Headers object to formulate an appropriate set of\n * headers based on the supplied options.\n *\n * @param {string} method - The request method. Defaults to \"get\".\n * @param {string} contentType - The content type of the request. Defaults to \"application/json\".\n * @param {object} extraHeaders - Custom headers to add.\n * @param {boolean} useBearer - Flag indicating whether to include bearer authorization.\n */\nfunction fetchHeaders(opts) {\n var _ref = opts || {},\n _ref$method = _ref.method,\n method = _ref$method === undefined ? 'get' : _ref$method,\n _ref$contentType = _ref.contentType,\n contentType = _ref$contentType === undefined ? contentTypes.json : _ref$contentType,\n extraHeaders = _ref.extraHeaders,\n _ref$useBearer = _ref.useBearer,\n useBearer = _ref$useBearer === undefined ? true : _ref$useBearer,\n bearer = _ref.bearer;\n\n var headers = new Headers({ 'X-Requested-With': 'XMLHttpRequest' });\n headers.set('Content-Type', contentType);\n if (!isEmpty(ajaxSettings.csrf) && !/^(GET|HEAD|OPTIONS\\TRACE)$/i.test(method)) headers.set('X-CSRFToken', ajaxSettings.csrf);\n if (!bearer) bearer = ajaxSettings.bearer;\n if (useBearer && bearer) headers.set('Authorization', 'Bearer ' + bearer);\n for (var k in extraHeaders || {}) {\n headers.set(k, extraHeaders[k]);\n }return headers;\n}\n\nfunction makeRequest(opts) {\n var method = (opts.method || 'get').toUpperCase();\n\n var _ref2 = opts || {},\n url = _ref2.url,\n body = _ref2.body,\n contentType = _ref2.contentType,\n extraHeaders = _ref2.extraHeaders,\n _ref2$useBearer = _ref2.useBearer,\n useBearer = _ref2$useBearer === undefined ? true : _ref2$useBearer,\n bearer = _ref2.bearer;\n\n var request = {\n url: url,\n method: method,\n headers: fetchHeaders({\n method: method,\n contentType: contentType,\n extraHeaders: extraHeaders,\n useBearer: useBearer,\n bearer: bearer\n }),\n credentials: 'same-origin'\n };\n if (method != 'GET' && method != 'HEAD' && method != 'OPTIONS') {\n request.body = body;\n }\n return request;\n}\n\n/**\n * Perform an ajax request.\n *\n * Uses HTML5 fetch to perform an ajax request according to parameters\n * supplied via the options object.\n *\n * @param {string} url - The URL to make the request to.\n * @param {string} method - The request method. Defaults to \"get\".\n * @param {string} body - Data to be sent with the request.\n * @param {string} contentType - The content type of the request. Defaults to \"application/json\".\n * @param {object} extraHeaders - Custom headers to add.\n * @param {boolean} useBearer - Flag indicating whether to include bearer authorization.\n */\nfunction ajax(opts) {\n var method = (opts.method || 'get').toUpperCase();\n\n var _ref3 = opts || {},\n url = _ref3.url,\n body = _ref3.body,\n contentType = _ref3.contentType,\n extraHeaders = _ref3.extraHeaders,\n _ref3$useBearer = _ref3.useBearer,\n useBearer = _ref3$useBearer === undefined ? true : _ref3$useBearer,\n bearer = _ref3.bearer;\n\n var requestInit = {\n method: method,\n headers: fetchHeaders({\n method: method,\n contentType: contentType,\n extraHeaders: extraHeaders,\n useBearer: useBearer,\n bearer: bearer\n }),\n credentials: 'same-origin'\n };\n if (method != 'GET' && method != 'HEAD' && method != 'OPTIONS') {\n requestInit.body = body;\n }\n\n var request = new Request(url, requestInit);\n return fetch(request).then(function (response) {\n if (!!response.ok) {\n if (response.status == 204) {\n return {};\n }\n if (typeof TINYAPI_NODE !== 'undefined' && TINYAPI_NODE) {\n return response;\n }\n if (!!response.json) {\n return response.json();\n } else {\n return response;\n }\n }\n if (!!response.json) {\n return response.json().catch(function (e) {\n return Object({ status: response.status });\n }).then(function (e) {\n return Promise.reject(e);\n });\n } else {\n return response;\n }\n });\n}\n\nfunction ajaxWithRequest(opts) {\n var url = opts.url,\n requestInit = _objectWithoutProperties(opts, ['url']);\n\n var request = new Request(url, requestInit);\n return fetch(request).then(function (response) {\n if (!!response.ok) {\n if (response.status == 204) {\n return {};\n }\n if (typeof TINYAPI_NODE !== 'undefined' && TINYAPI_NODE) {\n return response;\n }\n if (!!response.json) {\n return response.json();\n } else {\n return response;\n }\n }\n if (!!response.json) {\n return response.json().catch(function (e) {\n return Object({ status: response.status });\n }).then(function (e) {\n return Promise.reject(e);\n });\n } else {\n return response;\n }\n });\n}\n\n/**\n * Post JSON data.\n *\n * @param {string} url - The URL to make the request to.\n * @param {object} payload - Data to be sent with the request.\n * @param {string} contentType - The content type of the request. Defaults to \"application/json\".\n * @param {boolean} useBearer - Flag indicating whether to include bearer authorization.\n */\nfunction postJson(_ref4) {\n var url = _ref4.url,\n payload = _ref4.payload,\n contentType = _ref4.contentType,\n useBearer = _ref4.useBearer;\n\n return ajax({\n url: url,\n method: 'post',\n body: JSON.stringify(payload || {}),\n contentType: contentType,\n useBearer: useBearer\n });\n}\n\n/**\n * Convert an object into HTML5 FormData.\n */\nfunction makeFormData(payload) {\n var body = new FormData();\n for (var k in payload || {}) {\n body.append(k, payload[k]);\n }\n return body;\n}\n\n/**\n * Post form data.\n *\n * @param {string} url - The URL to make the request to.\n * @param {object} payload - Data to be sent with the request.\n * @param {boolean} useBearer - Flag indicating whether to include bearer authorization.\n */\nfunction postForm(_ref5) {\n var url = _ref5.url,\n payload = _ref5.payload,\n useBearer = _ref5.useBearer;\n\n return ajax({\n url: url,\n body: makeFormData(payload),\n method: 'post',\n useBearer: useBearer\n });\n}\n\nfunction takeFirst() {\n if (arguments) {\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = arguments[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var v = _step.value;\n\n if (v !== undefined) return v;\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\nexports.addTrailingSlash = addTrailingSlash;\nexports.ajax = ajax;\nexports.postJson = postJson;\nexports.postForm = postForm;\nexports.ajaxSettings = ajaxSettings;\nexports.contentTypes = contentTypes;\nexports.matchContentType = matchContentType;\nexports.makeFormData = makeFormData;\nexports.makeRequest = makeRequest;\nexports.ajaxWithRequest = ajaxWithRequest;\nexports.fetchHeaders = fetchHeaders;\n\n//# sourceURL=webpack://js-tinyapi/./src/utils.js?"); | ||
@@ -158,0 +158,0 @@ /***/ }), |
{ | ||
"name": "js-tinyapi", | ||
"version": "0.1.0-alpha.4", | ||
"version": "0.1.0-alpha.5", | ||
"description": "A simple and lightweight API helper.", | ||
@@ -16,3 +16,3 @@ "repository": { | ||
"watch": "webpack --config webpack.config.js --mode development --watch", | ||
"build:prod": "webpack --config webpack.config.js --mode production", | ||
"build:prod": "webpack --mode production --progress --colors --env.production=true", | ||
"prepublish": "npm run build", | ||
@@ -32,2 +32,3 @@ "test": "mocha --require babel-polyfill --compilers js:babel-register -R nyan --recursive tests/*.js" | ||
"babel-register": "^6.6.5", | ||
"clean-webpack-plugin": "^0.1.19", | ||
"code": "^5.2.0", | ||
@@ -34,0 +35,0 @@ "form-data": "^2.3.2", |
import { jsonApiQuery } from './jsonapi' | ||
import { | ||
debug, | ||
ajax, | ||
@@ -14,3 +13,4 @@ contentTypes, | ||
makeFormData, | ||
makeRequest | ||
makeRequest, | ||
takeFirst | ||
} from './utils' | ||
@@ -192,3 +192,3 @@ import { ApiError } from './errors' | ||
*/ | ||
request( endpoint, options = {} ) { | ||
request(endpoint, options = {}) { | ||
const { | ||
@@ -244,3 +244,10 @@ method = (endpoint.method || '').toLowerCase(), | ||
// Add any JSONAPI query strings. | ||
finalPath += jsonApiQuery({initial: queryString, include, filter, sort, fields}) | ||
finalPath += jsonApiQuery({ | ||
initial: queryString, | ||
include, | ||
filter, | ||
sort, | ||
fields, | ||
rawFilters: takeFirst(options.rawFilters, this.rawFilters, endpoint.rawFilters) | ||
}) | ||
@@ -270,3 +277,3 @@ // If we've been given an URL root, add it in here. This is useful | ||
if( !this.middlewares.length ) { | ||
debug( `API ${method} ${type}: ${finalPath}`, payload ) | ||
console.debug( `API ${method} ${type}: ${finalPath}`, payload ) | ||
return ajax( req ) | ||
@@ -273,0 +280,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
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
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
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
88514
537
18