js-tinyapi
Advanced tools
Comparing version 0.1.0-alpha.6 to 0.2.0
180
index.js
@@ -1,179 +0,1 @@ | ||
(function webpackUniversalModuleDefinition(root, factory) { | ||
if(typeof exports === 'object' && typeof module === 'object') | ||
module.exports = factory(require("js-cookie")); | ||
else if(typeof define === 'function' && define.amd) | ||
define(["js-cookie"], factory); | ||
else if(typeof exports === 'object') | ||
exports["js-tinyapi"] = factory(require("js-cookie")); | ||
else | ||
root["js-tinyapi"] = factory(root["js-cookie"]); | ||
})(window, function(__WEBPACK_EXTERNAL_MODULE_js_cookie__) { | ||
return /******/ (function(modules) { // webpackBootstrap | ||
/******/ // The module cache | ||
/******/ var installedModules = {}; | ||
/******/ | ||
/******/ // The require function | ||
/******/ function __webpack_require__(moduleId) { | ||
/******/ | ||
/******/ // Check if module is in cache | ||
/******/ if(installedModules[moduleId]) { | ||
/******/ return installedModules[moduleId].exports; | ||
/******/ } | ||
/******/ // Create a new module (and put it into the cache) | ||
/******/ var module = installedModules[moduleId] = { | ||
/******/ i: moduleId, | ||
/******/ l: false, | ||
/******/ exports: {} | ||
/******/ }; | ||
/******/ | ||
/******/ // Execute the module function | ||
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); | ||
/******/ | ||
/******/ // Flag the module as loaded | ||
/******/ module.l = true; | ||
/******/ | ||
/******/ // Return the exports of the module | ||
/******/ return module.exports; | ||
/******/ } | ||
/******/ | ||
/******/ | ||
/******/ // expose the modules object (__webpack_modules__) | ||
/******/ __webpack_require__.m = modules; | ||
/******/ | ||
/******/ // expose the module cache | ||
/******/ __webpack_require__.c = installedModules; | ||
/******/ | ||
/******/ // define getter function for harmony exports | ||
/******/ __webpack_require__.d = function(exports, name, getter) { | ||
/******/ if(!__webpack_require__.o(exports, name)) { | ||
/******/ Object.defineProperty(exports, name, { | ||
/******/ configurable: false, | ||
/******/ enumerable: true, | ||
/******/ get: getter | ||
/******/ }); | ||
/******/ } | ||
/******/ }; | ||
/******/ | ||
/******/ // define __esModule on exports | ||
/******/ __webpack_require__.r = function(exports) { | ||
/******/ Object.defineProperty(exports, '__esModule', { value: true }); | ||
/******/ }; | ||
/******/ | ||
/******/ // getDefaultExport function for compatibility with non-harmony modules | ||
/******/ __webpack_require__.n = function(module) { | ||
/******/ var getter = module && module.__esModule ? | ||
/******/ function getDefault() { return module['default']; } : | ||
/******/ function getModuleExports() { return module; }; | ||
/******/ __webpack_require__.d(getter, 'a', getter); | ||
/******/ return getter; | ||
/******/ }; | ||
/******/ | ||
/******/ // Object.prototype.hasOwnProperty.call | ||
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; | ||
/******/ | ||
/******/ // __webpack_public_path__ | ||
/******/ __webpack_require__.p = ""; | ||
/******/ | ||
/******/ | ||
/******/ // Load entry module and return exports | ||
/******/ return __webpack_require__(__webpack_require__.s = 0); | ||
/******/ }) | ||
/************************************************************************/ | ||
/******/ ({ | ||
/***/ "./src/batch.js": | ||
/*!**********************!*\ | ||
!*** ./src/batch.js ***! | ||
\**********************/ | ||
/*! no static exports found */ | ||
/***/ (function(module, exports, __webpack_require__) { | ||
"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, 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?"); | ||
/***/ }), | ||
/***/ "./src/errors.js": | ||
/*!***********************!*\ | ||
!*** ./src/errors.js ***! | ||
\***********************/ | ||
/*! no static exports found */ | ||
/***/ (function(module, exports, __webpack_require__) { | ||
"use strict"; | ||
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\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\nvar ApiError = function (_Error) {\n _inherits(ApiError, _Error);\n\n function ApiError() {\n var _ref;\n\n _classCallCheck(this, ApiError);\n\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n var _this = _possibleConstructorReturn(this, (_ref = ApiError.__proto__ || Object.getPrototypeOf(ApiError)).call.apply(_ref, [this].concat(args)));\n\n try {\n Error.captureStackTrace(_this, ApiError);\n } catch (e) {}\n return _this;\n }\n\n return ApiError;\n}(Error);\n\nexports.ApiError = ApiError;\n\n//# sourceURL=webpack://js-tinyapi/./src/errors.js?"); | ||
/***/ }), | ||
/***/ "./src/index.js": | ||
/*!**********************!*\ | ||
!*** ./src/index.js ***! | ||
\**********************/ | ||
/*! no static exports found */ | ||
/***/ (function(module, exports, __webpack_require__) { | ||
"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 _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?"); | ||
/***/ }), | ||
/***/ "./src/jsonapi.js": | ||
/*!************************!*\ | ||
!*** ./src/jsonapi.js ***! | ||
\************************/ | ||
/*! no static exports found */ | ||
/***/ (function(module, exports, __webpack_require__) { | ||
"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, 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?"); | ||
/***/ }), | ||
/***/ "./src/middleware.js": | ||
/*!***************************!*\ | ||
!*** ./src/middleware.js ***! | ||
\***************************/ | ||
/*! no static exports found */ | ||
/***/ (function(module, exports, __webpack_require__) { | ||
"use strict"; | ||
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _utils = __webpack_require__(/*! ./utils */ \"./src/utils.js\");\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * Base class for middleware.\n *\n * Middleware allows custom operations to be injected into the flow\n * of making a request. They can either modify the request details,\n * alter how the request is made, or modify the response. There may\n * be at most one middleware that returns a promise, all others must\n * return an object.\n */\nvar Middleware = function Middleware() {\n var _this = this;\n\n _classCallCheck(this, Middleware);\n\n this.process = function (obj) {\n return _this.submit(obj);\n };\n\n this.submit = function (request) {\n return (0, _utils.ajaxWithRequest)(request);\n };\n}\n\n/**\n * Entrypoint for middleware.\n *\n * This method should be overridden in sub-classes, and is used to\n * provide an entrypoint for middleware. \"obj\" can be either the\n * request information before being sent, or it may be the response\n * from a previous middleware sending the request.\n */\n\n\n/**\n * Submit a request.\n */\n;\n\nexports.default = Middleware;\n\n//# sourceURL=webpack://js-tinyapi/./src/middleware.js?"); | ||
/***/ }), | ||
/***/ "./src/utils.js": | ||
/*!**********************!*\ | ||
!*** ./src/utils.js ***! | ||
\**********************/ | ||
/*! no static exports found */ | ||
/***/ (function(module, exports, __webpack_require__) { | ||
"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 = 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?"); | ||
/***/ }), | ||
/***/ 0: | ||
/*!*************************!*\ | ||
!*** multi ./src/index ***! | ||
\*************************/ | ||
/*! no static exports found */ | ||
/***/ (function(module, exports, __webpack_require__) { | ||
eval("module.exports = __webpack_require__(/*! ./src/index */\"./src/index.js\");\n\n\n//# sourceURL=webpack://js-tinyapi/multi_./src/index?"); | ||
/***/ }), | ||
/***/ "js-cookie": | ||
/*!****************************!*\ | ||
!*** external "js-cookie" ***! | ||
\****************************/ | ||
/*! no static exports found */ | ||
/***/ (function(module, exports) { | ||
eval("module.exports = __WEBPACK_EXTERNAL_MODULE_js_cookie__;\n\n//# sourceURL=webpack://js-tinyapi/external_%22js-cookie%22?"); | ||
/***/ }) | ||
/******/ }); | ||
}); | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("js-cookie")):"function"==typeof define&&define.amd?define(["js-cookie"],t):"object"==typeof exports?exports["js-tinyapi"]=t(require("js-cookie")):e["js-tinyapi"]=t(e["js-cookie"])}(window,function(e){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:n})},r.r=function(e){Object.defineProperty(e,"__esModule",{value:!0})},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=0)}({0:function(e,t,r){e.exports=r("tjUo")},"4fRq":function(e,t){var r="undefined"!=typeof crypto&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&msCrypto.getRandomValues.bind(msCrypto);if(r){var n=new Uint8Array(16);e.exports=function(){return r(n),n}}else{var o=new Array(16);e.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),o[t]=e>>>((3&t)<<3)&255;return o}}},Al62:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fetchHeaders=t.makeHeaders=t.ajaxWithRequest=t.makeRequest=t.makeFormData=t.matchContentType=t.contentTypes=t.ajaxSettings=t.postForm=t.postJson=t.ajax=t.addTrailingSlash=void 0;var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t.supplant=function(e,t){return e.replace(/{([^{}]*)}/g,function(e,r){var n=t[r];if(void 0===n)throw new u.ApiError("Missing string template: "+r);return"string"==typeof n||"number"==typeof n?n:e})},t.capitalize=function(e){return e[0].toUpperCase()+e.slice(1)},t.takeFirst=function(){if(arguments){var e=!0,t=!1,r=void 0;try{for(var n,o=arguments[Symbol.iterator]();!(e=(n=o.next()).done);e=!0){var a=n.value;if(void 0!==a)return a}}catch(e){t=!0,r=e}finally{try{!e&&o.return&&o.return()}finally{if(t)throw r}}}};var o,a=r("vmXh"),i=(o=a)&&o.__esModule?o:{default:o},u=r("yMsT");var s={form:"application/x-www-form-urlencoded",multiForm:"multipart/form-data",json:"application/json",jsonApi:"application/vnd.api+json"};var c={csrf:i.default?i.default.get("csrftoken"):void 0,bearer:null};function l(e){var t,r=e||{},o=r.method,a=void 0===o?"get":o,i=r.contentType,u=void 0===i?s.json:i,l=r.extraHeaders,f=r.useBearer,d=void 0===f||f,p=r.bearer,h={"X-Requested-With":"XMLHttpRequest","Content-Type":u};return""===(t=c.csrf)||void 0===t||null===t||/^(GET|HEAD|OPTIONS\TRACE)$/i.test(a)||(h["X-CSRFToken"]=c.csrf),p||(p=c.bearer),d&&p&&(h.Authorization="Bearer "+p),h=n({},h,l)}function f(e){return new Headers(l(e))}function d(e){var t=(e.method||"get").toUpperCase(),r=e||{},n=r.url,o=r.body,a=r.contentType,i=r.extraHeaders,u=r.useBearer,s={method:t,headers:f({method:t,contentType:a,extraHeaders:i,useBearer:void 0===u||u,bearer:r.bearer}),credentials:"same-origin"};"GET"!=t&&"HEAD"!=t&&"OPTIONS"!=t&&(s.body=o);var c=new Request(n,s);return fetch(c).then(function(e){return e.ok?204==e.status?{}:"undefined"!=typeof TINYAPI_NODE&&TINYAPI_NODE?e:e.json?e.json():e:e.json?e.json().catch(function(t){return Object({status:e.status})}).then(function(e){return Promise.reject(e)}):e})}function p(e){var t=new FormData;for(var r in e||{})t.append(r,e[r]);return t}t.addTrailingSlash=function(e){return e+("/"==e[e.length-1]?"":"/")},t.ajax=d,t.postJson=function(e){var t=e.url,r=e.payload,n=e.contentType,o=e.useBearer;return d({url:t,method:"post",body:JSON.stringify(r||{}),contentType:n,useBearer:o})},t.postForm=function(e){var t=e.url,r=e.payload,n=e.useBearer;return d({url:t,body:p(r),method:"post",useBearer:n})},t.ajaxSettings=c,t.contentTypes=s,t.matchContentType=function(e,t){if(!e)return!1;var r=e.indexOf(";");return r>=0&&(e=e.substring(0,r)),e.toLowerCase()==s[t]},t.makeFormData=p,t.makeRequest=function(e){var t=(e.method||"get").toUpperCase(),r=e||{},n=r.url,o=r.body,a=r.contentType,i=r.extraHeaders,u=r.useBearer,s={url:n,method:t,headers:l({method:t,contentType:a,extraHeaders:i,useBearer:void 0===u||u,bearer:r.bearer}),credentials:"same-origin"};return"GET"!=t&&"HEAD"!=t&&"OPTIONS"!=t&&(s.body=o),s},t.ajaxWithRequest=function(e){var t=e.url,r=function(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}(e,["url"]),n=new Request(t,r);return fetch(n).then(function(e){return e.ok?204==e.status?{}:"undefined"!=typeof TINYAPI_NODE&&TINYAPI_NODE?e:e.json?e.json().then(function(t){return{data:t,response:e}}):{response:e}:e.json?{data:e.json().catch(function(t){return Object({status:e.status})}).then(function(e){return Promise.reject(e)}),response:e}:{response:e}})},t.makeHeaders=l,t.fetchHeaders=f},EcEN:function(e,t,r){var n=r("xDdU"),o=r("xk4V"),a=o;a.v1=n,a.v4=o,e.exports=a},I2ZF:function(e,t){for(var r=[],n=0;n<256;++n)r[n]=(n+256).toString(16).substr(1);e.exports=function(e,t){var n=t||0,o=r;return o[e[n++]]+o[e[n++]]+o[e[n++]]+o[e[n++]]+"-"+o[e[n++]]+o[e[n++]]+"-"+o[e[n++]]+o[e[n++]]+"-"+o[e[n++]]+o[e[n++]]+"-"+o[e[n++]]+o[e[n++]]+o[e[n++]]+o[e[n++]]+o[e[n++]]+o[e[n++]]}},KmhG:function(e,t,r){"use strict";function n(e,t){return Array.isArray(e)||(e=[e]),e&&e.length?[t+"="+e.join(",")]:[]}Object.defineProperty(t,"__esModule",{value:!0}),t.jsonApiQuery=function(e){var t,r,o=e||{},a=o.include,i=o.sort,u=o.filter,s=o.fields,c=o.rawFilters,l=(e.initial||[]).concat((t=a,n(t,r||"include")).concat(function(e,t){var r=t||{},n=(r.key,r.raw);if(e&&Object.keys(e).length){var o=n?function(e,t){return e+"="+t}:function(e,t){return"filter["+e+"]="+t};return Object.keys(e).map(function(t){return o(t,e[t])})}return[]}(u,{raw:c}).concat(function(e,t){return n(e,t||"sort")}(i).concat(function(e,t){return e&&Object.keys(e).length?Object.keys(e).map(function(t){return"fields["+t+"]="+e[t]}):[]}(s)))));return l.length>0?"?"+l.join("&"):""}},XyvK:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},o=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),a=s(r("EcEN")),i=r("Al62"),u=s(r("f/LL"));function s(e){return e&&e.__esModule?e:{default:e}}var c=function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var r=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return r.process=function(e,t,o){var a={request:t};if((o=n({},e.batchOptions||{},o)).skipBatching)return r.submit(t);var i=new Promise(function(e,t){a.resolve=e,a.reject=t}),u=o.group||"auto";return r.batch[u]=r.batch[u]||[],r.batch[u].push(a),"auto"==u&&(r.batch[u].length==r.maximum?(clearTimeout(r._to),r.submitBatch()):r._to||(r._to=setTimeout(r.submitBatch,r.timeout))),i},r.submitBatch=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"auto",t=r.batch[e]||[];delete r.batch[e],"auto"==e&&(r._to=null);var n=r.combineRequests(t);return r.submit(n).then(function(e){return r.splitResponses(t,e)})},r.combineRequests=function(e){return{url:r.selectUrl(e),method:"post",body:JSON.stringify({batch:e.map(function(e){return r.transformRequest(e.request)})}),headers:(0,i.fetchHeaders)({method:"post"}),credentials:"same-origin"}},r.selectUrl=function(e){var t=!0,n=!1,o=void 0;try{for(var a,i=e[Symbol.iterator]();!(t=(a=i.next()).done);t=!0){var u=a.value;if(r.mutMethods.has(u.request.method.toLowerCase()))return r.mutableBatchUrl}}catch(e){n=!0,o=e}finally{try{!t&&i.return&&i.return()}finally{if(n)throw o}}return r.batchUrl},r.transformRequest=function(e){var t={url:e.url,method:e.method,headers:e.headers};return e.body&&(t.body=e.body),t},r.splitResponses=function(e,t){for(var r=[],n=0;n<e.length;++n){var o=t.data[n];if(o.status_code&&o.status_code>=300){var a={status_code:o.status_code,reason_phrase:o.reason_phrase,headers:o.headers||{},body:o.body};e[n].reject({response:a,data:a}),r.push(a)}else e[n].resolve({response:o,data:o.body}),r.push(o.body)}return r},r.batchUrl=e.batchUrl,r.mutableBatchUrl=e.mutableBatchUrl||r.batchUrl,r.batch={auto:[]},r.maximum=20,r.timeout=e.timeout,r.mutMethods=new Set(["post","put","patch"]),r._to=null,r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,u.default),o(t,[{key:"contributeToApi",value:function(e){var t=this;e.batch=function(){var r=Object.create(e),n=a.default.v4();return r.batchOptions={group:n},r.send=function(){return t.submitBatch(n)},r.clear=function(){delete t.batch[n]},r}}}]),t}();t.default=c},"f/LL":function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),o=r("Al62");var a=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.preProcess=function(e,t,r){return t},this.postProcess=function(e,t,r){return t},this.process=function(e,t,r){return t},this.submit=function(e){return(0,o.ajaxWithRequest)(e)}}return n(e,[{key:"contributeToApi",value:function(e){}}]),e}();t.default=a},tjUo:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Batch=t.Middleware=t.ApiError=t.ajaxSettings=t.postForm=t.postJson=t.ajax=void 0;var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},o=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),a=r("KmhG"),i=r("Al62"),u=r("yMsT"),s=l(r("f/LL")),c=l(r("XyvK"));function l(e){return e&&e.__esModule?e:{default:e}}var f=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),d.call(this),this.crud={},this.middlewares=[],this.merge(t),this.urlRoot=null,this.defaultType=null}return o(e,[{key:"makeCrudEndpoints",value:function(e,t){var r=t+("/"==t[t.length-1]?"":"/")+e;this.crud[e]={list:this.makeEndpoint(e+"List",r,"GET"),create:this.makeEndpoint(e+"Create",r,"POST",{handler:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return e(n({},r,{payload:t}))}}),detail:this.makeEndpoint(e+"Get",r+"/{id}","GET",{handler:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return e(n({},r,{params:{id:t}}))}}),update:this.makeEndpoint(e+"Update",r+"/{id}","PATCH",{handler:function(e,t,r){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return e(n({},o,{params:{id:t},payload:r}))}}),remove:this.makeEndpoint(e+"Remove",r+"/{id}","DELETE",{handler:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return e(n({},r,{params:{id:t}}))}}),options:this.makeEndpoint(e+"Options",r,"OPTIONS")}}},{key:"request",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.method,o=void 0===n?(e.method||"").toLowerCase():n,u=r.path,s=void 0===u?e.path:u,c=r.params,l=void 0===c?{}:c,f=r.payload,d=r.type,p=void 0===d?e.type||this.defaultType:d,h=r.extraHeaders,v=void 0===h?{}:h,y=r.include,m=void 0===y?e.include||[]:y,b=r.filter,j=void 0===b?e.filter||{}:b,g=r.sort,w=void 0===g?e.sort||[]:g,O=r.fields,T=void 0===O?e.fields||[]:O,x=r.rawFilters,E=function(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}(r,["method","path","params","payload","type","extraHeaders","include","filter","sort","fields","rawFilters"]),_=r.urlRoot,k=void 0===_?this.urlRoot:_,P=r.contentType,A=void 0===P?e.contentType:P;p&&!A&&(A=i.contentTypes[p]);var R=void 0,C=[];if("get"!=o&&"options"!=o)void 0!==f&&(R=(0,i.matchContentType)(A,"form")||(0,i.matchContentType)(A,"multiForm")?(0,i.makeFormData)(f):JSON.stringify(f||{}));else if(void 0!==f)for(var q in f)C.push(q+"="+encodeURIComponent(f[q]));var S=(0,i.supplant)(s,l);S+=(0,a.jsonApiQuery)({initial:C,include:m,filter:j,sort:w,fields:T,rawFilters:(0,i.takeFirst)(x,this.rawFilters,e.rawFilters)}),k&&("/"==k[k.length-1]&&(k=k.substring(0,k.length-1)),S=k+S);var M={url:S,method:o,body:R,contentType:A,extraHeaders:v,bearer:this.bearer},F=void 0;if(this.middlewares.length){M=(0,i.makeRequest)(M);var U=!0,B=!1,D=void 0;try{for(var H,I=this.middlewares[Symbol.iterator]();!(U=(H=I.next()).done);U=!0){M=H.value.preProcess(this,M,E)}}catch(e){B=!0,D=e}finally{try{!U&&I.return&&I.return()}finally{if(B)throw D}}var N=0;for(F=this.middlewares[N++].process(this,M,E);N<this.middlewares.length;++N)if(Promise.resolve(F)==F)for(var L=function(){var e=t.middlewares[N];F=F.then(function(r){return e.process(t,r,E)})};N<this.middlewares.length;++N)L();else F=this.middlewares[N].process(this,F,E);Promise.resolve(F)!=F&&(F=ajaxWithRequest(F));var G=function(e){F=F.then(function(r){return e.postProcess(t,r,E)})},J=!0,X=!1,W=void 0;try{for(var K,V=this.middlewares.reverse()[Symbol.iterator]();!(J=(K=V.next()).done);J=!0){G(K.value)}}catch(e){X=!0,W=e}finally{try{!J&&V.return&&V.return()}finally{if(X)throw W}}}else F=(0,i.ajax)(M);return F.then(function(e){return e.data})}}]),e}(),d=function(){var e=this;this.pushMiddleware=function(t){Array.isArray(t)||(t=[t]),t.forEach(function(t){t.api=e,e.middlewares.push(t),t.contributeToApi(e)})},this.unshiftMiddleware=function(t){Array.isArray(t)||(t=[t]),t.forEach(function(t){t.api=e,e.middlewares.unshift(t)})},this.merge=function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(!t)throw new Error("Empty endpoint data given to Api.merge.");var n=!0,o=!1,a=void 0;try{for(var i,u=Object.keys(t)[Symbol.iterator]();!(n=(i=u.next()).done);n=!0){var s=i.value,c=t[s],l=/^(GET|POST|PUT|PATCH|DELETE|CRUD)$/.exec(s);if(l)if("CRUD"==l[1]){var f=r.lastIndexOf("/")+1,d=r.slice(f),p=r.slice(0,f);e.makeCrudEndpoints(d,p)}else{c instanceof Object||(c={name:c});var h=c,v=h.name,y=h.options,m=void 0===y?{}:y;e.makeEndpoint(v,r+"/",l[1],m)}else"CRUD"==c?e.makeCrudEndpoints(s,r):e.merge(c,r+"/"+s)}}catch(e){o=!0,a=e}finally{try{!n&&u.return&&u.return()}finally{if(o)throw a}}},this.makeEndpoint=function(t,r,o){var a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(void 0!==e[t])throw new Error("Duplicate name in Api: "+t);var u=n({},a,{path:(0,i.addTrailingSlash)(r),method:o}),s=function(e){return this.request(u,e)},c=a.handler;if(void 0!==c){var l=function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return c.apply(void 0,[s.bind(this)].concat(t))};l.context=u,e[t]=l}else s.context=u,e[t]=s;return e[t]}};t.default=f,t.ajax=i.ajax,t.postJson=i.postJson,t.postForm=i.postForm,t.ajaxSettings=i.ajaxSettings,t.ApiError=u.ApiError,t.Middleware=s.default,t.Batch=c.default},vmXh:function(t,r){t.exports=e},xDdU:function(e,t,r){var n,o,a=r("4fRq"),i=r("I2ZF"),u=0,s=0;e.exports=function(e,t,r){var c=t&&r||0,l=t||[],f=(e=e||{}).node||n,d=void 0!==e.clockseq?e.clockseq:o;if(null==f||null==d){var p=a();null==f&&(f=n=[1|p[0],p[1],p[2],p[3],p[4],p[5]]),null==d&&(d=o=16383&(p[6]<<8|p[7]))}var h=void 0!==e.msecs?e.msecs:(new Date).getTime(),v=void 0!==e.nsecs?e.nsecs:s+1,y=h-u+(v-s)/1e4;if(y<0&&void 0===e.clockseq&&(d=d+1&16383),(y<0||h>u)&&void 0===e.nsecs&&(v=0),v>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");u=h,s=v,o=d;var m=(1e4*(268435455&(h+=122192928e5))+v)%4294967296;l[c++]=m>>>24&255,l[c++]=m>>>16&255,l[c++]=m>>>8&255,l[c++]=255&m;var b=h/4294967296*1e4&268435455;l[c++]=b>>>8&255,l[c++]=255&b,l[c++]=b>>>24&15|16,l[c++]=b>>>16&255,l[c++]=d>>>8|128,l[c++]=255&d;for(var j=0;j<6;++j)l[c+j]=f[j];return t||i(l)}},xk4V:function(e,t,r){var n=r("4fRq"),o=r("I2ZF");e.exports=function(e,t,r){var a=t&&r||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var i=(e=e||{}).random||(e.rng||n)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t)for(var u=0;u<16;++u)t[a+u]=i[u];return t||o(i)}},yMsT:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(e){function t(){var e;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);for(var r=arguments.length,n=Array(r),o=0;o<r;o++)n[o]=arguments[o];var a=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(n)));try{Error.captureStackTrace(a,t)}catch(e){}return a}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,Error),t}();t.ApiError=n}})}); |
{ | ||
"name": "js-tinyapi", | ||
"version": "0.1.0-alpha.6", | ||
"version": "0.2.0", | ||
"description": "A simple and lightweight API helper.", | ||
@@ -9,2 +9,3 @@ "repository": { | ||
}, | ||
"esnext": "src/index.js", | ||
"main": "index.js", | ||
@@ -18,7 +19,6 @@ "files": [ | ||
"build:prod": "webpack --mode production --progress --colors --env.production=true", | ||
"prepublish": "npm run build", | ||
"test": "mocha --require babel-polyfill --compilers js:babel-register -R nyan --recursive tests/*.js" | ||
"test": "mocha --require babel-polyfill --require babel-core/register -R nyan --recursive tests/*.test.js" | ||
}, | ||
"author": "Luke Hodkinson", | ||
"license": "ISC", | ||
"license": "MIT", | ||
"devDependencies": { | ||
@@ -46,3 +46,6 @@ "babel-core": "^6.3.26", | ||
"js-cookie": "^2.1.4" | ||
}, | ||
"dependencies": { | ||
"uuid": "^3.2.1" | ||
} | ||
} |
@@ -32,6 +32,8 @@ import { jsonApiQuery } from './jsonapi' | ||
this.merge( endpoints ) | ||
this.urlRoot = null | ||
this.defaultType = null | ||
} | ||
pushMiddleware = middleware => { | ||
if( !Array.isArray( middleware ) ) { | ||
if ( !Array.isArray( middleware ) ) { | ||
middleware = [middleware] | ||
@@ -42,2 +44,3 @@ } | ||
this.middlewares.push( m ) | ||
m.contributeToApi(this) | ||
}) | ||
@@ -130,3 +133,5 @@ } | ||
// Otherwise just use the standard request. | ||
let request = opts => this.request( ctx, opts ) | ||
let request = function(opts) { | ||
return this.request(ctx, opts) | ||
} | ||
const { handler } = opts | ||
@@ -138,3 +143,5 @@ if( handler !== undefined ) { | ||
// the call after modifying any options. | ||
let wrapper = ( ...args ) => handler( request, ...args ) | ||
let wrapper = function(...args) { | ||
return handler(request.bind(this), ...args) | ||
} | ||
wrapper.context = ctx | ||
@@ -201,3 +208,3 @@ this[name] = wrapper | ||
payload, | ||
type = endpoint.type, | ||
type = endpoint.type || this.defaultType, | ||
extraHeaders = {}, | ||
@@ -212,3 +219,3 @@ include = (endpoint.include || []), | ||
let { | ||
urlRoot, | ||
urlRoot = this.urlRoot, | ||
contentType = endpoint.contentType | ||
@@ -281,5 +288,6 @@ } = options | ||
// now. | ||
let obj | ||
if( !this.middlewares.length ) { | ||
console.debug( `API ${method} ${type}: ${finalPath}`, payload ) | ||
return ajax( req ) | ||
obj = ajax( req ) | ||
} | ||
@@ -293,5 +301,12 @@ | ||
else { | ||
req = makeRequest( req ) | ||
req = makeRequest(req) | ||
// Run all preprocess middlewares. | ||
for (const mw of this.middlewares) { | ||
req = mw.preProcess(this, req, otherOptions) | ||
} | ||
// Run the old version 1 middleware stack. | ||
let ii = 0 | ||
let obj = this.middlewares[ii++].process( req, otherOptions ) | ||
obj = this.middlewares[ii++].process(this, req, otherOptions) | ||
for( ; ii < this.middlewares.length; ++ii ) { | ||
@@ -301,11 +316,25 @@ if( Promise.resolve( obj ) == obj ) { | ||
let mw = this.middlewares[ii] | ||
obj = obj.then( r => mw.process( r, otherOptions ) ) | ||
obj = obj.then( r => mw.process( this, r, otherOptions ) ) | ||
} | ||
} | ||
else { | ||
obj = this.middlewares[ii].process( obj, otherOptions ) | ||
obj = this.middlewares[ii].process( this, obj, otherOptions ) | ||
} | ||
} | ||
return obj | ||
// If we didn't end up with a promise then send the request. | ||
if (Promise.resolve(obj) != obj) { | ||
obj = ajaxWithRequest(obj) | ||
} | ||
// Run postprocess middlewares. | ||
for (const mw of this.middlewares.reverse()) { | ||
obj = obj.then(r => mw.postProcess(this, r, otherOptions)) | ||
} | ||
} | ||
// At this point the result will contain a data object and the | ||
// response. Maintain backwards compatibility by only returning | ||
// the data. | ||
return obj.then(r => r.data) | ||
} | ||
@@ -312,0 +341,0 @@ } |
Sorry, the diff of this file is not supported yet
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
Uses eval
Supply chain riskPackage uses dynamic code execution (e.g., eval()), which is a dangerous practice. This can prevent the code from running in certain environments and increases the risk that the code may contain exploits or malicious behavior.
Found 1 instance in 1 package
Copyleft License
License(Experimental) Copyleft license information was found.
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
Mixed license
License(Experimental) Package contains multiple licenses.
Found 1 instance in 1 package
Non-permissive License
License(Experimental) A license not known to be considered permissive was found.
Found 1 instance in 1 package
0
100
0
2
34369
2
308
3
+ Addeduuid@^3.2.1
+ Addeduuid@3.4.0(transitive)