From 5448ef55ea4f5841d499774e991872d48edbf83b Mon Sep 17 00:00:00 2001 From: Federico Dainelli Date: Sun, 8 Jul 2018 19:45:02 +0200 Subject: [PATCH] Add axios http adapter --- build/configs.js | 2 + dist/vuex-orm.common.js | 1323 ++++++++++++++++++++++++++++++++---- dist/vuex-orm.esm.js | 1323 ++++++++++++++++++++++++++++++++---- dist/vuex-orm.js | 1323 ++++++++++++++++++++++++++++++++---- dist/vuex-orm.min.js | 2 +- lib/http/Http.d.ts | 21 +- lib/http/Http.js | 90 ++- lib/http/Http.js.map | 2 +- lib/model/Model.d.ts | 30 +- lib/model/Model.js | 47 +- lib/model/Model.js.map | 2 +- lib/model/ModelConf.d.ts | 6 +- lib/model/ModelConf.js | 10 +- lib/options/Options.d.ts | 16 +- lib/options/Options.js | 45 +- lib/options/Options.js.map | 2 +- package-lock.json | 56 ++ package.json | 2 + src/http/Http.ts | 130 ++-- src/model/Model.ts | 69 +- src/model/ModelConf.ts | 12 +- src/options/Options.ts | 64 +- 22 files changed, 3998 insertions(+), 579 deletions(-) diff --git a/build/configs.js b/build/configs.js index d3fbd962..0361b29d 100644 --- a/build/configs.js +++ b/build/configs.js @@ -1,5 +1,6 @@ const path = require('path') const nodeResolve = require('rollup-plugin-node-resolve') +const nodeGlobals = require('rollup-plugin-node-globals') const commonjs = require('rollup-plugin-commonjs') const resolve = _path => path.resolve(__dirname, '../', _path) @@ -36,6 +37,7 @@ function genConfig (opts) { plugins: [ nodeResolve(), + nodeGlobals(), commonjs() ], diff --git a/dist/vuex-orm.common.js b/dist/vuex-orm.common.js index a09c9baf..c8e0cb0d 100644 --- a/dist/vuex-orm.common.js +++ b/dist/vuex-orm.common.js @@ -118,6 +118,1115 @@ var Container = /** @class */ (function () { return Container; }()); +var bind = function bind(fn, thisArg) { + return function wrap() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + return fn.apply(thisArg, args); + }; +}; + +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +var isBuffer_1 = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +}; + +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} + +/*global toString:true*/ + +// utils is a library of generic helper functions non-specific to axios + +var toString = Object.prototype.toString; + +/** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Array, otherwise false + */ +function isArray(val) { + return toString.call(val) === '[object Array]'; +} + +/** + * Determine if a value is an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +function isArrayBuffer(val) { + return toString.call(val) === '[object ArrayBuffer]'; +} + +/** + * Determine if a value is a FormData + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an FormData, otherwise false + */ +function isFormData(val) { + return (typeof FormData !== 'undefined') && (val instanceof FormData); +} + +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + var result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); + } + return result; +} + +/** + * Determine if a value is a String + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a String, otherwise false + */ +function isString(val) { + return typeof val === 'string'; +} + +/** + * Determine if a value is a Number + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Number, otherwise false + */ +function isNumber(val) { + return typeof val === 'number'; +} + +/** + * Determine if a value is undefined + * + * @param {Object} val The value to test + * @returns {boolean} True if the value is undefined, otherwise false + */ +function isUndefined(val) { + return typeof val === 'undefined'; +} + +/** + * Determine if a value is an Object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Object, otherwise false + */ +function isObject(val) { + return val !== null && typeof val === 'object'; +} + +/** + * Determine if a value is a Date + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Date, otherwise false + */ +function isDate(val) { + return toString.call(val) === '[object Date]'; +} + +/** + * Determine if a value is a File + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a File, otherwise false + */ +function isFile(val) { + return toString.call(val) === '[object File]'; +} + +/** + * Determine if a value is a Blob + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Blob, otherwise false + */ +function isBlob(val) { + return toString.call(val) === '[object Blob]'; +} + +/** + * Determine if a value is a Function + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ +function isFunction(val) { + return toString.call(val) === '[object Function]'; +} + +/** + * Determine if a value is a Stream + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Stream, otherwise false + */ +function isStream(val) { + return isObject(val) && isFunction(val.pipe); +} + +/** + * Determine if a value is a URLSearchParams object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +function isURLSearchParams(val) { + return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; +} + +/** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * @returns {String} The String freed of excess whitespace + */ +function trim(str) { + return str.replace(/^\s*/, '').replace(/\s*$/, ''); +} + +/** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + */ +function isStandardBrowserEnv() { + if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { + return false; + } + return ( + typeof window !== 'undefined' && + typeof document !== 'undefined' + ); +} + +/** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + */ +function forEach(obj, fn) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + + if (isArray(obj)) { + // Iterate over array values + for (var i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn.call(null, obj[key], key, obj); + } + } + } +} + +/** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * @returns {Object} Result of all merge properties + */ +function merge(/* obj1, obj2, obj3, ... */) { + var result = {}; + function assignValue(val, key) { + if (typeof result[key] === 'object' && typeof val === 'object') { + result[key] = merge(result[key], val); + } else { + result[key] = val; + } + } + + for (var i = 0, l = arguments.length; i < l; i++) { + forEach(arguments[i], assignValue); + } + return result; +} + +/** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * @return {Object} The resulting value of object a + */ +function extend(a, b, thisArg) { + forEach(b, function assignValue(val, key) { + if (thisArg && typeof val === 'function') { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }); + return a; +} + +var utils = { + isArray: isArray, + isArrayBuffer: isArrayBuffer, + isBuffer: isBuffer_1, + isFormData: isFormData, + isArrayBufferView: isArrayBufferView, + isString: isString, + isNumber: isNumber, + isObject: isObject, + isUndefined: isUndefined, + isDate: isDate, + isFile: isFile, + isBlob: isBlob, + isFunction: isFunction, + isStream: isStream, + isURLSearchParams: isURLSearchParams, + isStandardBrowserEnv: isStandardBrowserEnv, + forEach: forEach, + merge: merge, + extend: extend, + trim: trim +}; + +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + +// shim for using process in browser +// based off https://github.com/defunctzombie/node-process/blob/master/browser.js + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +var cachedSetTimeout = defaultSetTimout; +var cachedClearTimeout = defaultClearTimeout; +if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; +} +if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; +} + +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} +function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +} +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +var title = 'browser'; +var platform = 'browser'; +var browser = true; +var env = {}; +var argv = []; +var version = ''; // empty string to avoid regexp issues +var versions = {}; +var release = {}; +var config = {}; + +function noop() {} + +var on = noop; +var addListener = noop; +var once = noop; +var off = noop; +var removeListener = noop; +var removeAllListeners = noop; +var emit = noop; + +function binding(name) { + throw new Error('process.binding is not supported'); +} + +function cwd () { return '/' } +function chdir (dir) { + throw new Error('process.chdir is not supported'); +}function umask() { return 0; } + +// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js +var performance = global$1.performance || {}; +var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + +// generate timestamp or delta +// see http://nodejs.org/api/process.html#process_process_hrtime +function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] +} + +var startTime = new Date(); +function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; +} + +var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime +}; + +var utils$1 = require('./utils'); +var normalizeHeaderName = require('./helpers/normalizeHeaderName'); + +var DEFAULT_CONTENT_TYPE = { + 'Content-Type': 'application/x-www-form-urlencoded' +}; + +function setContentTypeIfUnset(headers, value) { + if (!utils$1.isUndefined(headers) && utils$1.isUndefined(headers['Content-Type'])) { + headers['Content-Type'] = value; + } +} + +function getDefaultAdapter() { + var adapter; + if (typeof XMLHttpRequest !== 'undefined') { + // For browsers use XHR adapter + adapter = require('./adapters/xhr'); + } else if (typeof process !== 'undefined') { + // For node use HTTP adapter + adapter = require('./adapters/http'); + } + return adapter; +} + +var defaults = { + adapter: getDefaultAdapter(), + + transformRequest: [function transformRequest(data, headers) { + normalizeHeaderName(headers, 'Content-Type'); + if (utils$1.isFormData(data) || + utils$1.isArrayBuffer(data) || + utils$1.isBuffer(data) || + utils$1.isStream(data) || + utils$1.isFile(data) || + utils$1.isBlob(data) + ) { + return data; + } + if (utils$1.isArrayBufferView(data)) { + return data.buffer; + } + if (utils$1.isURLSearchParams(data)) { + setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); + return data.toString(); + } + if (utils$1.isObject(data)) { + setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); + return JSON.stringify(data); + } + return data; + }], + + transformResponse: [function transformResponse(data) { + /*eslint no-param-reassign:0*/ + if (typeof data === 'string') { + try { + data = JSON.parse(data); + } catch (e) { /* Ignore */ } + } + return data; + }], + + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + } +}; + +defaults.headers = { + common: { + 'Accept': 'application/json, text/plain, */*' + } +}; + +utils$1.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { + defaults.headers[method] = {}; +}); + +utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + defaults.headers[method] = utils$1.merge(DEFAULT_CONTENT_TYPE); +}); + +module.exports = defaults; + +var defaults$1 = /*#__PURE__*/Object.freeze({ + +}); + +function InterceptorManager() { + this.handlers = []; +} + +/** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ +InterceptorManager.prototype.use = function use(fulfilled, rejected) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected + }); + return this.handlers.length - 1; +}; + +/** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + */ +InterceptorManager.prototype.eject = function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } +}; + +/** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + */ +InterceptorManager.prototype.forEach = function forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); +}; + +var InterceptorManager_1 = InterceptorManager; + +/** + * Transform the data for a request or a response + * + * @param {Object|String} data The data to be transformed + * @param {Array} headers The headers for the request or response + * @param {Array|Function} fns A single function or Array of functions + * @returns {*} The resulting transformed data + */ +var transformData = function transformData(data, headers, fns) { + /*eslint no-param-reassign:0*/ + utils.forEach(fns, function transform(fn) { + data = fn(data, headers); + }); + + return data; +}; + +var isCancel = function isCancel(value) { + return !!(value && value.__CANCEL__); +}; + +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +var isAbsoluteURL = function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); +}; + +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * @returns {string} The combined URL + */ +var combineURLs = function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +}; + +/** + * Throws a `Cancel` if cancellation has been requested. + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } +} + +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * @returns {Promise} The Promise to be fulfilled + */ +var dispatchRequest = function dispatchRequest(config) { + throwIfCancellationRequested(config); + + // Support baseURL config + if (config.baseURL && !isAbsoluteURL(config.url)) { + config.url = combineURLs(config.baseURL, config.url); + } + + // Ensure headers exist + config.headers = config.headers || {}; + + // Transform request data + config.data = transformData( + config.data, + config.headers, + config.transformRequest + ); + + // Flatten headers + config.headers = utils.merge( + config.headers.common || {}, + config.headers[config.method] || {}, + config.headers || {} + ); + + utils.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + function cleanHeaderConfig(method) { + delete config.headers[method]; + } + ); + + var adapter = config.adapter || defaults$1.adapter; + + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData( + response.data, + response.headers, + config.transformResponse + ); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData( + reason.response.data, + reason.response.headers, + config.transformResponse + ); + } + } + + return Promise.reject(reason); + }); +}; + +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + */ +function Axios(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager_1(), + response: new InterceptorManager_1() + }; +} + +/** + * Dispatch a request + * + * @param {Object} config The config specific for this request (merged with this.defaults) + */ +Axios.prototype.request = function request(config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof config === 'string') { + config = utils.merge({ + url: arguments[0] + }, arguments[1]); + } + + config = utils.merge(defaults$1, {method: 'get'}, this.defaults, config); + config.method = config.method.toLowerCase(); + + // Hook up interceptors middleware + var chain = [dispatchRequest, undefined]; + var promise = Promise.resolve(config); + + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + chain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + chain.push(interceptor.fulfilled, interceptor.rejected); + }); + + while (chain.length) { + promise = promise.then(chain.shift(), chain.shift()); + } + + return promise; +}; + +// Provide aliases for supported request methods +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(utils.merge(config || {}, { + method: method, + url: url + })); + }; +}); + +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, data, config) { + return this.request(utils.merge(config || {}, { + method: method, + url: url, + data: data + })); + }; +}); + +var Axios_1 = Axios; + +/** + * A `Cancel` is an object that is thrown when an operation is canceled. + * + * @class + * @param {string=} message The message. + */ +function Cancel(message) { + this.message = message; +} + +Cancel.prototype.toString = function toString() { + return 'Cancel' + (this.message ? ': ' + this.message : ''); +}; + +Cancel.prototype.__CANCEL__ = true; + +var Cancel_1 = Cancel; + +/** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @class + * @param {Function} executor The executor function. + */ +function CancelToken(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + var resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + var token = this; + executor(function cancel(message) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new Cancel_1(message); + resolvePromise(token.reason); + }); +} + +/** + * Throws a `Cancel` if cancellation has been requested. + */ +CancelToken.prototype.throwIfRequested = function throwIfRequested() { + if (this.reason) { + throw this.reason; + } +}; + +/** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ +CancelToken.source = function source() { + var cancel; + var token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token: token, + cancel: cancel + }; +}; + +var CancelToken_1 = CancelToken; + +/** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * @returns {Function} + */ +var spread = function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +}; + +/** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * @return {Axios} A new instance of Axios + */ +function createInstance(defaultConfig) { + var context = new Axios_1(defaultConfig); + var instance = bind(Axios_1.prototype.request, context); + + // Copy axios.prototype to instance + utils.extend(instance, Axios_1.prototype, context); + + // Copy context to instance + utils.extend(instance, context); + + return instance; +} + +// Create the default instance to be exported +var axios = createInstance(defaults$1); + +// Expose Axios class to allow class inheritance +axios.Axios = Axios_1; + +// Factory for creating new instances +axios.create = function create(instanceConfig) { + return createInstance(utils.merge(defaults$1, instanceConfig)); +}; + +// Expose Cancel & CancelToken +axios.Cancel = Cancel_1; +axios.CancelToken = CancelToken_1; +axios.isCancel = isCancel; + +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; +axios.spread = spread; + +var axios_1 = axios; + +// Allow use of default import syntax in TypeScript +var default_1 = axios; +axios_1.default = default_1; + +var axios$1 = axios_1; + +var __assign$1 = (undefined && undefined.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +var Http = /** @class */ (function () { + function Http() { + } + Http.conf = function (config) { + this.defaultConf = config; + }; + Http.registerRequestInterceptor = function (requestInterceptor) { + axios$1.interceptors.request.use(requestInterceptor); + }; + Http.registerResponseInterceptor = function (responseInterceptor) { + axios$1.interceptors.response.use(responseInterceptor); + }; + Http.mergeConf = function (config) { + return __assign$1({}, this.defaultConf, config); + }; + Http.head = function (url, config) { + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.head(url, config); + }; + Http.get = function (url, config) { + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.get(url, config); + }; + Http.post = function (url, data, config) { + if (data === void 0) { data = {}; } + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.post(url, data, config); + }; + Http.patch = function (url, data, config) { + if (data === void 0) { data = {}; } + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.patch(url, data, config); + }; + Http.put = function (url, data, config) { + if (data === void 0) { data = {}; } + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.put(url, data, config); + }; + Http.delete = function (url, config) { + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.delete(url, config); + }; + return Http; +}()); + var ModuleOptions = /** @class */ (function () { function ModuleOptions() { } @@ -126,14 +1235,48 @@ var ModuleOptions = /** @class */ (function () { if (options.namespace) { this.namespace = options.namespace; } - if (options.resources) { - this.resources = options.resources; + if (options.http) { + this.http = options.http; } + this.check(); + this.confAxiosModule(); }; - ModuleOptions.namespace = 'entities'; - ModuleOptions.resources = { - baseUrl: '' + ModuleOptions.confAxiosModule = function () { + Http.conf(this.http); + if (this.http.requestInterceptor) { + Http.registerRequestInterceptor(this.http.requestInterceptor); + } + if (this.http.responseInterceptor) { + Http.registerResponseInterceptor(this.http.responseInterceptor); + } + }; + ModuleOptions.check = function () { + if (!this.http) { + throw new Error('Vuex orm resources: missing default http conf'); + } + this.checkBaseUrl(); + this.checkHeader(); + this.checkTimeout(); + }; + ModuleOptions.checkBaseUrl = function () { + if (!this.http.baseURL) { + throw new Error('Vuex orm resources: missing default http baseURL conf'); + } }; + ModuleOptions.checkTimeout = function () { + if (!this.http.timeout) { + throw new Error('Vuex orm resources: missing default http timeout conf'); + } + }; + ModuleOptions.checkHeader = function () { + if (!this.http.headers) { + throw new Error('Vuex orm resources: missing default http headers conf'); + } + if (!this.http.headers['Content-Type']) { + throw new Error('Vuex orm resources: missing default http Content-Type headers conf'); + } + }; + ModuleOptions.namespace = 'entities'; return ModuleOptions; }()); @@ -1314,7 +2457,7 @@ var __extends$6 = (undefined && undefined.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); -var __assign$1 = (undefined && undefined.__assign) || Object.assign || function(t) { +var __assign$2 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -1333,7 +2476,7 @@ var Relation = /** @class */ (function (_super) { Relation.prototype.mapRecords = function (records, key) { return records.reduce(function (records, record) { var _a; - return __assign$1({}, records, (_a = {}, _a[record[key]] = record, _a)); + return __assign$2({}, records, (_a = {}, _a[record[key]] = record, _a)); }, {}); }; /** @@ -1773,7 +2916,7 @@ var __extends$11 = (undefined && undefined.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); -var __assign$2 = (undefined && undefined.__assign) || Object.assign || function(t) { +var __assign$3 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -1881,7 +3024,7 @@ var BelongsToMany = /** @class */ (function (_super) { related.forEach(function (id) { var _a, _b; var pivotKey = record[_this.parentKey] + "_" + id; - data[_this.pivot.entity] = __assign$2({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { + data[_this.pivot.entity] = __assign$3({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { $id: pivotKey }, _b[_this.foreignPivotKey] = record[_this.parentKey], _b[_this.relatedPivotKey] = id, _b), _a)); }); @@ -2144,7 +3287,7 @@ var __extends$15 = (undefined && undefined.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); -var __assign$3 = (undefined && undefined.__assign) || Object.assign || function(t) { +var __assign$4 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -2255,7 +3398,7 @@ var MorphToMany = /** @class */ (function (_super) { var _a, _b; var parentId = record[_this.parentKey]; var pivotKey = parentId + "_" + id + "_" + parent.entity; - data[_this.pivot.entity] = __assign$3({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { + data[_this.pivot.entity] = __assign$4({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { $id: pivotKey }, _b[_this.relatedId] = id, _b[_this.id] = parentId, _b[_this.type] = parent.entity, _b), _a)); }); @@ -2273,7 +3416,7 @@ var __extends$16 = (undefined && undefined.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); -var __assign$4 = (undefined && undefined.__assign) || Object.assign || function(t) { +var __assign$5 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -2384,7 +3527,7 @@ var MorphedByMany = /** @class */ (function (_super) { var _a, _b; var parentId = record[_this.parentKey]; var pivotKey = id + "_" + parentId + "_" + _this.related.entity; - data[_this.pivot.entity] = __assign$4({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { + data[_this.pivot.entity] = __assign$5({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { $id: pivotKey }, _b[_this.relatedId] = parentId, _b[_this.id] = id, _b[_this.type] = _this.related.entity, _b), _a)); }); @@ -2445,7 +3588,7 @@ var IdAttribute = /** @class */ (function () { return IdAttribute; }()); -var __assign$5 = (undefined && undefined.__assign) || Object.assign || function(t) { +var __assign$6 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -2462,7 +3605,7 @@ var ProcessStrategy = /** @class */ (function () { ProcessStrategy.create = function (noKey, model, parent, attr) { var _this = this; return function (value, parentValue, key) { - var record = __assign$5({}, value); + var record = __assign$6({}, value); record = _this.fix(record, model); record = _this.setId(record, model, noKey, key); record = _this.generateMorphFields(record, parentValue, parent, attr); @@ -2499,7 +3642,7 @@ var ProcessStrategy = /** @class */ (function () { */ ProcessStrategy.setId = function (record, model, noKey, key) { var id = model.id(record); - return __assign$5({}, record, { $id: id !== undefined ? id : noKey.increment(key) }); + return __assign$6({}, record, { $id: id !== undefined ? id : noKey.increment(key) }); }; /** * Generate morph fields. This method will generate fileds needed for the @@ -2516,12 +3659,12 @@ var ProcessStrategy = /** @class */ (function () { if (parent === undefined) { return record; } - return __assign$5((_a = {}, _a[attr.id] = parentValue.$id, _a[attr.type] = parent.entity, _a), record); + return __assign$6((_a = {}, _a[attr.id] = parentValue.$id, _a[attr.type] = parent.entity, _a), record); }; return ProcessStrategy; }()); -var __assign$6 = (undefined && undefined.__assign) || Object.assign || function(t) { +var __assign$7 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -2543,7 +3686,7 @@ var Schema = /** @class */ (function () { idAttribute: IdAttribute.create(noKey, model), processStrategy: ProcessStrategy.create(noKey, model, parent, attr) }); - var definition = this.definition(model, __assign$6({}, schemas, (_a = {}, _a[model.entity] = thisSchema, _a))); + var definition = this.definition(model, __assign$7({}, schemas, (_a = {}, _a[model.entity] = thisSchema, _a))); thisSchema.define(definition); return thisSchema; }; @@ -2750,7 +3893,7 @@ var Attacher = /** @class */ (function () { return Attacher; }()); -var __assign$7 = (undefined && undefined.__assign) || Object.assign || function(t) { +var __assign$8 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -2784,7 +3927,7 @@ var IdFixer = /** @class */ (function () { newRecords[id] = record; return newRecords; } - newRecords[newStringId] = __assign$7({}, record, { $id: newId }); + newRecords[newStringId] = __assign$8({}, record, { $id: newId }); return newRecords; }, {}); }; @@ -2971,7 +4114,7 @@ var Hook = /** @class */ (function () { return Hook; }()); -var __assign$8 = (undefined && undefined.__assign) || Object.assign || function(t) { +var __assign$9 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -3218,7 +4361,7 @@ var Query = /** @class */ (function () { callback(); return; } - payload = __assign$8({ entity: this.entity }, payload); + payload = __assign$9({ entity: this.entity }, payload); this.actionContext.commit(this.rootState.$name + "/" + method, payload, { root: true }); }; /** @@ -3286,7 +4429,7 @@ var Query = /** @class */ (function () { Query.prototype.commitInsert = function (data) { var _this = this; this.commit('commitInsert', { data: data }, function () { - _this.state.data = __assign$8({}, _this.state.data, data); + _this.state.data = __assign$9({}, _this.state.data, data); }); }; /** @@ -3373,7 +4516,7 @@ var Query = /** @class */ (function () { Query.prototype.commitUpdate = function (data) { var _this = this; this.commit('commitUpdate', { data: data }, function () { - _this.state.data = __assign$8({}, _this.state.data, data); + _this.state.data = __assign$9({}, _this.state.data, data); }); }; /** @@ -3475,7 +4618,7 @@ var Query = /** @class */ (function () { if (!record) { return null; } - return this.item(__assign$8({}, record)); + return this.item(__assign$9({}, record)); }; /** * Returns all record of the query chain result. @@ -3506,7 +4649,7 @@ var Query = /** @class */ (function () { */ Query.prototype.records = function (records) { var theRecords = records || this.state.data; - return Object.keys(theRecords).map(function (id) { return (__assign$8({}, theRecords[id])); }); + return Object.keys(theRecords).map(function (id) { return (__assign$9({}, theRecords[id])); }); }; /** * Add a and where clause to the query. @@ -4495,76 +5638,6 @@ var BaseModel = /** @class */ (function () { return BaseModel; }()); -var __assign$9 = (undefined && undefined.__assign) || Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; -}; -var Http = /** @class */ (function () { - function Http() { - } - Http.request = function (url, _query, _method, _body, _headers, options) { - if (_body === void 0) { _body = {}; } - if (_headers === void 0) { _headers = {}; } - if (options === void 0) { options = {}; } - var _options = __assign$9({}, this.defaultOptions, options); - _options.method = _method; - if (Object.keys(_body).length) { - _options.body = JSON.stringify(_body); - } - return fetch(url, _options) - .then(function (response) { - if (!response.ok) { - return Promise.reject(new Error('http request failed')); - } - else { - return Promise.resolve(response.json()); - } - }); // parses response to JSON - }; - Http.get = function (url, params, headers, options) { - if (params === void 0) { params = {}; } - if (headers === void 0) { headers = {}; } - if (options === void 0) { options = {}; } - return this.request(url, params, 'GET', {}, headers, options); - }; - Http.post = function (url, payload, headers, options) { - if (payload === void 0) { payload = {}; } - if (headers === void 0) { headers = {}; } - if (options === void 0) { options = {}; } - return this.request(url, {}, 'POST', payload, headers, options); - }; - Http.put = function (url, payload, headers, options) { - if (payload === void 0) { payload = {}; } - if (headers === void 0) { headers = {}; } - if (options === void 0) { options = {}; } - return this.request(url, {}, 'PUT', payload, headers, options); - }; - Http.delete = function (url, payload, headers, options) { - if (payload === void 0) { payload = {}; } - if (headers === void 0) { headers = {}; } - if (options === void 0) { options = {}; } - return this.request(url, {}, 'DELETE', payload, headers, options); - }; - // Default options are marked with * - Http.defaultOptions = { - method: '', - cache: 'no-cache', - credentials: 'same-origin', - headers: { - 'user-agent': 'Mozilla/4.0 MDN Example', - 'content-type': 'application/json' - }, - mode: 'cors', - redirect: 'follow', - referrer: 'no-referrer' // *client, no-referrer - }; - return Http; -}()); - var HttpMethod; (function (HttpMethod) { HttpMethod["GET"] = "get"; @@ -4591,7 +5664,7 @@ var ModelConf = /** @class */ (function () { /** * The host/domain of api server */ - this.baseUrl = ''; + this.baseURL = ''; /** * The endpoint of model entity */ @@ -4601,7 +5674,7 @@ var ModelConf = /** @class */ (function () { */ this.methods = new Map(); if (conf) { - this.baseUrl = conf.baseUrl; + this.baseURL = conf.baseURL; this.endpointPath = conf.endpointPath; if (conf.methods) { conf.methods.forEach(function (method) { @@ -4616,8 +5689,8 @@ var ModelConf = /** @class */ (function () { */ ModelConf.prototype.extend = function (conf) { var _this = this; - if (conf.baseUrl) { - this.baseUrl = conf.baseUrl; + if (conf.baseURL) { + this.baseURL = conf.baseURL; } if (conf.endpointPath) { this.endpointPath = conf.endpointPath; @@ -4715,7 +5788,7 @@ var HttpConf = /** @class */ (function () { return HttpConf; }()); var defaultConf = { - "baseUrl": "http://localhost:3000", + "baseURL": "http://localhost:3000", "endpointPath": "/{self}", "methods": [ { @@ -4875,13 +5948,14 @@ var Model = /** @class */ (function (_super) { Model.fetch = function (conf) { if (conf === void 0) { conf = this.getMethodConf('fetch'); } return __awaiter(this, void 0, void 0, function () { - var _conf, url, data; + var _conf, url, method, data; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('fetch', conf); url = this.getUrl(_conf); - return [4 /*yield*/, Http[_conf.http.method](url) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url) .catch(function (err) { console.log(err); })]; case 1: data = (_a.sent()) || []; @@ -4963,13 +6037,14 @@ var Model = /** @class */ (function (_super) { Model.fetchById = function (id, conf) { if (conf === void 0) { conf = this.getMethodConf('fetchById'); } return __awaiter(this, void 0, void 0, function () { - var _conf, url, data; + var _conf, url, method, data; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('fetchById', conf); url = this.getUrl(_conf, new PathParam('id', id.toString())); - return [4 /*yield*/, Http[_conf.http.method](url) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url) .catch(function (err) { console.log(err); })]; case 1: data = (_a.sent()) || []; @@ -4995,14 +6070,15 @@ var Model = /** @class */ (function (_super) { Model.exist = function (id, conf) { if (conf === void 0) { conf = this.getMethodConf('exist'); } return __awaiter(this, void 0, void 0, function () { - var _conf, data, url; + var _conf, data, url, method; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('exist', conf); if (!_conf.remote) return [3 /*break*/, 2]; url = this.getUrl(_conf, new PathParam('id', id.toString())); - return [4 /*yield*/, Http[_conf.http.method](url) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url) .catch(function (err) { console.log(err); })]; case 1: data = (_a.sent()) || []; @@ -5024,13 +6100,14 @@ var Model = /** @class */ (function (_super) { Model.count = function (conf) { if (conf === void 0) { conf = this.getMethodConf('count'); } return __awaiter(this, void 0, void 0, function () { - var _conf, data; + var _conf, data, method; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('count', conf); if (!_conf.remote) return [3 /*break*/, 2]; - return [4 /*yield*/, Http[_conf.http.method](this.getUrl(_conf)) + method = _conf.http.method; + return [4 /*yield*/, Http[method](this.getUrl(_conf)) .catch(function (err) { console.log(err); })]; case 1: data = (_a.sent()) || []; @@ -5053,13 +6130,14 @@ var Model = /** @class */ (function (_super) { Model.create = function (data, conf) { if (conf === void 0) { conf = this.getMethodConf('create'); } return __awaiter(this, void 0, void 0, function () { - var _conf, dataOutput; + var _conf, dataOutput, method; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('create', conf); if (!_conf.remote) return [3 /*break*/, 2]; - return [4 /*yield*/, Http[_conf.http.method](this.getUrl(_conf), data) + method = _conf.http.method; + return [4 /*yield*/, Http[method](this.getUrl(_conf), data) .catch(function (err) { console.log(err); })]; case 1: dataOutput = (_a.sent()) || []; @@ -5086,14 +6164,15 @@ var Model = /** @class */ (function (_super) { Model.update = function (id, data, conf) { if (conf === void 0) { conf = this.getMethodConf('update'); } return __awaiter(this, void 0, void 0, function () { - var _conf, dataOutput, url; + var _conf, dataOutput, url, method; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('update', conf); if (!_conf.remote) return [3 /*break*/, 2]; url = this.getUrl(_conf, new PathParam('id', id.toString())); - return [4 /*yield*/, Http[_conf.http.method](url, data) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url, data) .catch(function (err) { console.log(err); })]; case 1: dataOutput = (_a.sent()) || []; @@ -5124,14 +6203,15 @@ var Model = /** @class */ (function (_super) { Model.deleteById = function (id, conf) { if (conf === void 0) { conf = this.getMethodConf('deleteById'); } return __awaiter(this, void 0, void 0, function () { - var _conf, url, dataOutput; + var _conf, url, method, dataOutput; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('deleteById', conf); if (!_conf.remote) return [3 /*break*/, 2]; url = this.getUrl(_conf, new PathParam('id', id.toString())); - return [4 /*yield*/, Http[_conf.http.method](url) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url) .catch(function (err) { console.log(err); })]; case 1: dataOutput = (_a.sent()) || []; @@ -5155,13 +6235,14 @@ var Model = /** @class */ (function (_super) { Model.delete = function (conf) { if (conf === void 0) { conf = this.getMethodConf('deleteById'); } return __awaiter(this, void 0, void 0, function () { - var _conf, dataOutput; + var _conf, method, dataOutput; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('deleteById', conf); if (!_conf.remote) return [3 /*break*/, 2]; - return [4 /*yield*/, Http[_conf.http.method](this.getUrl(_conf)) + method = _conf.http.method; + return [4 /*yield*/, Http[method](this.getUrl(_conf)) .catch(function (err) { console.log(err); })]; case 1: dataOutput = (_a.sent()) || []; @@ -5197,13 +6278,9 @@ var Model = /** @class */ (function (_super) { for (var _i = 1; _i < arguments.length; _i++) { pathParams[_i - 1] = arguments[_i]; } - var baseUrl = this._conf.baseUrl; var methodPath = pathParams.length ? conf.http.bindPathParams(pathParams) : conf.http.path; - if (ModuleOptions.resources.baseUrl) { - baseUrl = ModuleOptions.resources.baseUrl; - } - return baseUrl + this._conf.endpointPath + methodPath; + return this._conf.endpointPath + methodPath; }; /** * Check if the method configuration exist and diff --git a/dist/vuex-orm.esm.js b/dist/vuex-orm.esm.js index d35c7699..c94df6f8 100644 --- a/dist/vuex-orm.esm.js +++ b/dist/vuex-orm.esm.js @@ -116,6 +116,1115 @@ var Container = /** @class */ (function () { return Container; }()); +var bind = function bind(fn, thisArg) { + return function wrap() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + return fn.apply(thisArg, args); + }; +}; + +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +var isBuffer_1 = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +}; + +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} + +/*global toString:true*/ + +// utils is a library of generic helper functions non-specific to axios + +var toString = Object.prototype.toString; + +/** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Array, otherwise false + */ +function isArray(val) { + return toString.call(val) === '[object Array]'; +} + +/** + * Determine if a value is an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +function isArrayBuffer(val) { + return toString.call(val) === '[object ArrayBuffer]'; +} + +/** + * Determine if a value is a FormData + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an FormData, otherwise false + */ +function isFormData(val) { + return (typeof FormData !== 'undefined') && (val instanceof FormData); +} + +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + var result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); + } + return result; +} + +/** + * Determine if a value is a String + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a String, otherwise false + */ +function isString(val) { + return typeof val === 'string'; +} + +/** + * Determine if a value is a Number + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Number, otherwise false + */ +function isNumber(val) { + return typeof val === 'number'; +} + +/** + * Determine if a value is undefined + * + * @param {Object} val The value to test + * @returns {boolean} True if the value is undefined, otherwise false + */ +function isUndefined(val) { + return typeof val === 'undefined'; +} + +/** + * Determine if a value is an Object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Object, otherwise false + */ +function isObject(val) { + return val !== null && typeof val === 'object'; +} + +/** + * Determine if a value is a Date + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Date, otherwise false + */ +function isDate(val) { + return toString.call(val) === '[object Date]'; +} + +/** + * Determine if a value is a File + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a File, otherwise false + */ +function isFile(val) { + return toString.call(val) === '[object File]'; +} + +/** + * Determine if a value is a Blob + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Blob, otherwise false + */ +function isBlob(val) { + return toString.call(val) === '[object Blob]'; +} + +/** + * Determine if a value is a Function + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ +function isFunction(val) { + return toString.call(val) === '[object Function]'; +} + +/** + * Determine if a value is a Stream + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Stream, otherwise false + */ +function isStream(val) { + return isObject(val) && isFunction(val.pipe); +} + +/** + * Determine if a value is a URLSearchParams object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +function isURLSearchParams(val) { + return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; +} + +/** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * @returns {String} The String freed of excess whitespace + */ +function trim(str) { + return str.replace(/^\s*/, '').replace(/\s*$/, ''); +} + +/** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + */ +function isStandardBrowserEnv() { + if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { + return false; + } + return ( + typeof window !== 'undefined' && + typeof document !== 'undefined' + ); +} + +/** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + */ +function forEach(obj, fn) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + + if (isArray(obj)) { + // Iterate over array values + for (var i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn.call(null, obj[key], key, obj); + } + } + } +} + +/** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * @returns {Object} Result of all merge properties + */ +function merge(/* obj1, obj2, obj3, ... */) { + var result = {}; + function assignValue(val, key) { + if (typeof result[key] === 'object' && typeof val === 'object') { + result[key] = merge(result[key], val); + } else { + result[key] = val; + } + } + + for (var i = 0, l = arguments.length; i < l; i++) { + forEach(arguments[i], assignValue); + } + return result; +} + +/** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * @return {Object} The resulting value of object a + */ +function extend(a, b, thisArg) { + forEach(b, function assignValue(val, key) { + if (thisArg && typeof val === 'function') { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }); + return a; +} + +var utils = { + isArray: isArray, + isArrayBuffer: isArrayBuffer, + isBuffer: isBuffer_1, + isFormData: isFormData, + isArrayBufferView: isArrayBufferView, + isString: isString, + isNumber: isNumber, + isObject: isObject, + isUndefined: isUndefined, + isDate: isDate, + isFile: isFile, + isBlob: isBlob, + isFunction: isFunction, + isStream: isStream, + isURLSearchParams: isURLSearchParams, + isStandardBrowserEnv: isStandardBrowserEnv, + forEach: forEach, + merge: merge, + extend: extend, + trim: trim +}; + +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + +// shim for using process in browser +// based off https://github.com/defunctzombie/node-process/blob/master/browser.js + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +var cachedSetTimeout = defaultSetTimout; +var cachedClearTimeout = defaultClearTimeout; +if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; +} +if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; +} + +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} +function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +} +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +var title = 'browser'; +var platform = 'browser'; +var browser = true; +var env = {}; +var argv = []; +var version = ''; // empty string to avoid regexp issues +var versions = {}; +var release = {}; +var config = {}; + +function noop() {} + +var on = noop; +var addListener = noop; +var once = noop; +var off = noop; +var removeListener = noop; +var removeAllListeners = noop; +var emit = noop; + +function binding(name) { + throw new Error('process.binding is not supported'); +} + +function cwd () { return '/' } +function chdir (dir) { + throw new Error('process.chdir is not supported'); +}function umask() { return 0; } + +// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js +var performance = global$1.performance || {}; +var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + +// generate timestamp or delta +// see http://nodejs.org/api/process.html#process_process_hrtime +function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] +} + +var startTime = new Date(); +function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; +} + +var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime +}; + +var utils$1 = require('./utils'); +var normalizeHeaderName = require('./helpers/normalizeHeaderName'); + +var DEFAULT_CONTENT_TYPE = { + 'Content-Type': 'application/x-www-form-urlencoded' +}; + +function setContentTypeIfUnset(headers, value) { + if (!utils$1.isUndefined(headers) && utils$1.isUndefined(headers['Content-Type'])) { + headers['Content-Type'] = value; + } +} + +function getDefaultAdapter() { + var adapter; + if (typeof XMLHttpRequest !== 'undefined') { + // For browsers use XHR adapter + adapter = require('./adapters/xhr'); + } else if (typeof process !== 'undefined') { + // For node use HTTP adapter + adapter = require('./adapters/http'); + } + return adapter; +} + +var defaults = { + adapter: getDefaultAdapter(), + + transformRequest: [function transformRequest(data, headers) { + normalizeHeaderName(headers, 'Content-Type'); + if (utils$1.isFormData(data) || + utils$1.isArrayBuffer(data) || + utils$1.isBuffer(data) || + utils$1.isStream(data) || + utils$1.isFile(data) || + utils$1.isBlob(data) + ) { + return data; + } + if (utils$1.isArrayBufferView(data)) { + return data.buffer; + } + if (utils$1.isURLSearchParams(data)) { + setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); + return data.toString(); + } + if (utils$1.isObject(data)) { + setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); + return JSON.stringify(data); + } + return data; + }], + + transformResponse: [function transformResponse(data) { + /*eslint no-param-reassign:0*/ + if (typeof data === 'string') { + try { + data = JSON.parse(data); + } catch (e) { /* Ignore */ } + } + return data; + }], + + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + } +}; + +defaults.headers = { + common: { + 'Accept': 'application/json, text/plain, */*' + } +}; + +utils$1.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { + defaults.headers[method] = {}; +}); + +utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + defaults.headers[method] = utils$1.merge(DEFAULT_CONTENT_TYPE); +}); + +module.exports = defaults; + +var defaults$1 = /*#__PURE__*/Object.freeze({ + +}); + +function InterceptorManager() { + this.handlers = []; +} + +/** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ +InterceptorManager.prototype.use = function use(fulfilled, rejected) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected + }); + return this.handlers.length - 1; +}; + +/** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + */ +InterceptorManager.prototype.eject = function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } +}; + +/** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + */ +InterceptorManager.prototype.forEach = function forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); +}; + +var InterceptorManager_1 = InterceptorManager; + +/** + * Transform the data for a request or a response + * + * @param {Object|String} data The data to be transformed + * @param {Array} headers The headers for the request or response + * @param {Array|Function} fns A single function or Array of functions + * @returns {*} The resulting transformed data + */ +var transformData = function transformData(data, headers, fns) { + /*eslint no-param-reassign:0*/ + utils.forEach(fns, function transform(fn) { + data = fn(data, headers); + }); + + return data; +}; + +var isCancel = function isCancel(value) { + return !!(value && value.__CANCEL__); +}; + +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +var isAbsoluteURL = function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); +}; + +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * @returns {string} The combined URL + */ +var combineURLs = function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +}; + +/** + * Throws a `Cancel` if cancellation has been requested. + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } +} + +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * @returns {Promise} The Promise to be fulfilled + */ +var dispatchRequest = function dispatchRequest(config) { + throwIfCancellationRequested(config); + + // Support baseURL config + if (config.baseURL && !isAbsoluteURL(config.url)) { + config.url = combineURLs(config.baseURL, config.url); + } + + // Ensure headers exist + config.headers = config.headers || {}; + + // Transform request data + config.data = transformData( + config.data, + config.headers, + config.transformRequest + ); + + // Flatten headers + config.headers = utils.merge( + config.headers.common || {}, + config.headers[config.method] || {}, + config.headers || {} + ); + + utils.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + function cleanHeaderConfig(method) { + delete config.headers[method]; + } + ); + + var adapter = config.adapter || defaults$1.adapter; + + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData( + response.data, + response.headers, + config.transformResponse + ); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData( + reason.response.data, + reason.response.headers, + config.transformResponse + ); + } + } + + return Promise.reject(reason); + }); +}; + +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + */ +function Axios(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager_1(), + response: new InterceptorManager_1() + }; +} + +/** + * Dispatch a request + * + * @param {Object} config The config specific for this request (merged with this.defaults) + */ +Axios.prototype.request = function request(config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof config === 'string') { + config = utils.merge({ + url: arguments[0] + }, arguments[1]); + } + + config = utils.merge(defaults$1, {method: 'get'}, this.defaults, config); + config.method = config.method.toLowerCase(); + + // Hook up interceptors middleware + var chain = [dispatchRequest, undefined]; + var promise = Promise.resolve(config); + + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + chain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + chain.push(interceptor.fulfilled, interceptor.rejected); + }); + + while (chain.length) { + promise = promise.then(chain.shift(), chain.shift()); + } + + return promise; +}; + +// Provide aliases for supported request methods +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(utils.merge(config || {}, { + method: method, + url: url + })); + }; +}); + +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, data, config) { + return this.request(utils.merge(config || {}, { + method: method, + url: url, + data: data + })); + }; +}); + +var Axios_1 = Axios; + +/** + * A `Cancel` is an object that is thrown when an operation is canceled. + * + * @class + * @param {string=} message The message. + */ +function Cancel(message) { + this.message = message; +} + +Cancel.prototype.toString = function toString() { + return 'Cancel' + (this.message ? ': ' + this.message : ''); +}; + +Cancel.prototype.__CANCEL__ = true; + +var Cancel_1 = Cancel; + +/** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @class + * @param {Function} executor The executor function. + */ +function CancelToken(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + var resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + var token = this; + executor(function cancel(message) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new Cancel_1(message); + resolvePromise(token.reason); + }); +} + +/** + * Throws a `Cancel` if cancellation has been requested. + */ +CancelToken.prototype.throwIfRequested = function throwIfRequested() { + if (this.reason) { + throw this.reason; + } +}; + +/** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ +CancelToken.source = function source() { + var cancel; + var token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token: token, + cancel: cancel + }; +}; + +var CancelToken_1 = CancelToken; + +/** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * @returns {Function} + */ +var spread = function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +}; + +/** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * @return {Axios} A new instance of Axios + */ +function createInstance(defaultConfig) { + var context = new Axios_1(defaultConfig); + var instance = bind(Axios_1.prototype.request, context); + + // Copy axios.prototype to instance + utils.extend(instance, Axios_1.prototype, context); + + // Copy context to instance + utils.extend(instance, context); + + return instance; +} + +// Create the default instance to be exported +var axios = createInstance(defaults$1); + +// Expose Axios class to allow class inheritance +axios.Axios = Axios_1; + +// Factory for creating new instances +axios.create = function create(instanceConfig) { + return createInstance(utils.merge(defaults$1, instanceConfig)); +}; + +// Expose Cancel & CancelToken +axios.Cancel = Cancel_1; +axios.CancelToken = CancelToken_1; +axios.isCancel = isCancel; + +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; +axios.spread = spread; + +var axios_1 = axios; + +// Allow use of default import syntax in TypeScript +var default_1 = axios; +axios_1.default = default_1; + +var axios$1 = axios_1; + +var __assign$1 = (undefined && undefined.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +var Http = /** @class */ (function () { + function Http() { + } + Http.conf = function (config) { + this.defaultConf = config; + }; + Http.registerRequestInterceptor = function (requestInterceptor) { + axios$1.interceptors.request.use(requestInterceptor); + }; + Http.registerResponseInterceptor = function (responseInterceptor) { + axios$1.interceptors.response.use(responseInterceptor); + }; + Http.mergeConf = function (config) { + return __assign$1({}, this.defaultConf, config); + }; + Http.head = function (url, config) { + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.head(url, config); + }; + Http.get = function (url, config) { + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.get(url, config); + }; + Http.post = function (url, data, config) { + if (data === void 0) { data = {}; } + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.post(url, data, config); + }; + Http.patch = function (url, data, config) { + if (data === void 0) { data = {}; } + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.patch(url, data, config); + }; + Http.put = function (url, data, config) { + if (data === void 0) { data = {}; } + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.put(url, data, config); + }; + Http.delete = function (url, config) { + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.delete(url, config); + }; + return Http; +}()); + var ModuleOptions = /** @class */ (function () { function ModuleOptions() { } @@ -124,14 +1233,48 @@ var ModuleOptions = /** @class */ (function () { if (options.namespace) { this.namespace = options.namespace; } - if (options.resources) { - this.resources = options.resources; + if (options.http) { + this.http = options.http; } + this.check(); + this.confAxiosModule(); }; - ModuleOptions.namespace = 'entities'; - ModuleOptions.resources = { - baseUrl: '' + ModuleOptions.confAxiosModule = function () { + Http.conf(this.http); + if (this.http.requestInterceptor) { + Http.registerRequestInterceptor(this.http.requestInterceptor); + } + if (this.http.responseInterceptor) { + Http.registerResponseInterceptor(this.http.responseInterceptor); + } + }; + ModuleOptions.check = function () { + if (!this.http) { + throw new Error('Vuex orm resources: missing default http conf'); + } + this.checkBaseUrl(); + this.checkHeader(); + this.checkTimeout(); + }; + ModuleOptions.checkBaseUrl = function () { + if (!this.http.baseURL) { + throw new Error('Vuex orm resources: missing default http baseURL conf'); + } }; + ModuleOptions.checkTimeout = function () { + if (!this.http.timeout) { + throw new Error('Vuex orm resources: missing default http timeout conf'); + } + }; + ModuleOptions.checkHeader = function () { + if (!this.http.headers) { + throw new Error('Vuex orm resources: missing default http headers conf'); + } + if (!this.http.headers['Content-Type']) { + throw new Error('Vuex orm resources: missing default http Content-Type headers conf'); + } + }; + ModuleOptions.namespace = 'entities'; return ModuleOptions; }()); @@ -1312,7 +2455,7 @@ var __extends$6 = (undefined && undefined.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); -var __assign$1 = (undefined && undefined.__assign) || Object.assign || function(t) { +var __assign$2 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -1331,7 +2474,7 @@ var Relation = /** @class */ (function (_super) { Relation.prototype.mapRecords = function (records, key) { return records.reduce(function (records, record) { var _a; - return __assign$1({}, records, (_a = {}, _a[record[key]] = record, _a)); + return __assign$2({}, records, (_a = {}, _a[record[key]] = record, _a)); }, {}); }; /** @@ -1771,7 +2914,7 @@ var __extends$11 = (undefined && undefined.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); -var __assign$2 = (undefined && undefined.__assign) || Object.assign || function(t) { +var __assign$3 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -1879,7 +3022,7 @@ var BelongsToMany = /** @class */ (function (_super) { related.forEach(function (id) { var _a, _b; var pivotKey = record[_this.parentKey] + "_" + id; - data[_this.pivot.entity] = __assign$2({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { + data[_this.pivot.entity] = __assign$3({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { $id: pivotKey }, _b[_this.foreignPivotKey] = record[_this.parentKey], _b[_this.relatedPivotKey] = id, _b), _a)); }); @@ -2142,7 +3285,7 @@ var __extends$15 = (undefined && undefined.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); -var __assign$3 = (undefined && undefined.__assign) || Object.assign || function(t) { +var __assign$4 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -2253,7 +3396,7 @@ var MorphToMany = /** @class */ (function (_super) { var _a, _b; var parentId = record[_this.parentKey]; var pivotKey = parentId + "_" + id + "_" + parent.entity; - data[_this.pivot.entity] = __assign$3({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { + data[_this.pivot.entity] = __assign$4({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { $id: pivotKey }, _b[_this.relatedId] = id, _b[_this.id] = parentId, _b[_this.type] = parent.entity, _b), _a)); }); @@ -2271,7 +3414,7 @@ var __extends$16 = (undefined && undefined.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); -var __assign$4 = (undefined && undefined.__assign) || Object.assign || function(t) { +var __assign$5 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -2382,7 +3525,7 @@ var MorphedByMany = /** @class */ (function (_super) { var _a, _b; var parentId = record[_this.parentKey]; var pivotKey = id + "_" + parentId + "_" + _this.related.entity; - data[_this.pivot.entity] = __assign$4({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { + data[_this.pivot.entity] = __assign$5({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { $id: pivotKey }, _b[_this.relatedId] = parentId, _b[_this.id] = id, _b[_this.type] = _this.related.entity, _b), _a)); }); @@ -2443,7 +3586,7 @@ var IdAttribute = /** @class */ (function () { return IdAttribute; }()); -var __assign$5 = (undefined && undefined.__assign) || Object.assign || function(t) { +var __assign$6 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -2460,7 +3603,7 @@ var ProcessStrategy = /** @class */ (function () { ProcessStrategy.create = function (noKey, model, parent, attr) { var _this = this; return function (value, parentValue, key) { - var record = __assign$5({}, value); + var record = __assign$6({}, value); record = _this.fix(record, model); record = _this.setId(record, model, noKey, key); record = _this.generateMorphFields(record, parentValue, parent, attr); @@ -2497,7 +3640,7 @@ var ProcessStrategy = /** @class */ (function () { */ ProcessStrategy.setId = function (record, model, noKey, key) { var id = model.id(record); - return __assign$5({}, record, { $id: id !== undefined ? id : noKey.increment(key) }); + return __assign$6({}, record, { $id: id !== undefined ? id : noKey.increment(key) }); }; /** * Generate morph fields. This method will generate fileds needed for the @@ -2514,12 +3657,12 @@ var ProcessStrategy = /** @class */ (function () { if (parent === undefined) { return record; } - return __assign$5((_a = {}, _a[attr.id] = parentValue.$id, _a[attr.type] = parent.entity, _a), record); + return __assign$6((_a = {}, _a[attr.id] = parentValue.$id, _a[attr.type] = parent.entity, _a), record); }; return ProcessStrategy; }()); -var __assign$6 = (undefined && undefined.__assign) || Object.assign || function(t) { +var __assign$7 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -2541,7 +3684,7 @@ var Schema = /** @class */ (function () { idAttribute: IdAttribute.create(noKey, model), processStrategy: ProcessStrategy.create(noKey, model, parent, attr) }); - var definition = this.definition(model, __assign$6({}, schemas, (_a = {}, _a[model.entity] = thisSchema, _a))); + var definition = this.definition(model, __assign$7({}, schemas, (_a = {}, _a[model.entity] = thisSchema, _a))); thisSchema.define(definition); return thisSchema; }; @@ -2748,7 +3891,7 @@ var Attacher = /** @class */ (function () { return Attacher; }()); -var __assign$7 = (undefined && undefined.__assign) || Object.assign || function(t) { +var __assign$8 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -2782,7 +3925,7 @@ var IdFixer = /** @class */ (function () { newRecords[id] = record; return newRecords; } - newRecords[newStringId] = __assign$7({}, record, { $id: newId }); + newRecords[newStringId] = __assign$8({}, record, { $id: newId }); return newRecords; }, {}); }; @@ -2969,7 +4112,7 @@ var Hook = /** @class */ (function () { return Hook; }()); -var __assign$8 = (undefined && undefined.__assign) || Object.assign || function(t) { +var __assign$9 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -3216,7 +4359,7 @@ var Query = /** @class */ (function () { callback(); return; } - payload = __assign$8({ entity: this.entity }, payload); + payload = __assign$9({ entity: this.entity }, payload); this.actionContext.commit(this.rootState.$name + "/" + method, payload, { root: true }); }; /** @@ -3284,7 +4427,7 @@ var Query = /** @class */ (function () { Query.prototype.commitInsert = function (data) { var _this = this; this.commit('commitInsert', { data: data }, function () { - _this.state.data = __assign$8({}, _this.state.data, data); + _this.state.data = __assign$9({}, _this.state.data, data); }); }; /** @@ -3371,7 +4514,7 @@ var Query = /** @class */ (function () { Query.prototype.commitUpdate = function (data) { var _this = this; this.commit('commitUpdate', { data: data }, function () { - _this.state.data = __assign$8({}, _this.state.data, data); + _this.state.data = __assign$9({}, _this.state.data, data); }); }; /** @@ -3473,7 +4616,7 @@ var Query = /** @class */ (function () { if (!record) { return null; } - return this.item(__assign$8({}, record)); + return this.item(__assign$9({}, record)); }; /** * Returns all record of the query chain result. @@ -3504,7 +4647,7 @@ var Query = /** @class */ (function () { */ Query.prototype.records = function (records) { var theRecords = records || this.state.data; - return Object.keys(theRecords).map(function (id) { return (__assign$8({}, theRecords[id])); }); + return Object.keys(theRecords).map(function (id) { return (__assign$9({}, theRecords[id])); }); }; /** * Add a and where clause to the query. @@ -4493,76 +5636,6 @@ var BaseModel = /** @class */ (function () { return BaseModel; }()); -var __assign$9 = (undefined && undefined.__assign) || Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; -}; -var Http = /** @class */ (function () { - function Http() { - } - Http.request = function (url, _query, _method, _body, _headers, options) { - if (_body === void 0) { _body = {}; } - if (_headers === void 0) { _headers = {}; } - if (options === void 0) { options = {}; } - var _options = __assign$9({}, this.defaultOptions, options); - _options.method = _method; - if (Object.keys(_body).length) { - _options.body = JSON.stringify(_body); - } - return fetch(url, _options) - .then(function (response) { - if (!response.ok) { - return Promise.reject(new Error('http request failed')); - } - else { - return Promise.resolve(response.json()); - } - }); // parses response to JSON - }; - Http.get = function (url, params, headers, options) { - if (params === void 0) { params = {}; } - if (headers === void 0) { headers = {}; } - if (options === void 0) { options = {}; } - return this.request(url, params, 'GET', {}, headers, options); - }; - Http.post = function (url, payload, headers, options) { - if (payload === void 0) { payload = {}; } - if (headers === void 0) { headers = {}; } - if (options === void 0) { options = {}; } - return this.request(url, {}, 'POST', payload, headers, options); - }; - Http.put = function (url, payload, headers, options) { - if (payload === void 0) { payload = {}; } - if (headers === void 0) { headers = {}; } - if (options === void 0) { options = {}; } - return this.request(url, {}, 'PUT', payload, headers, options); - }; - Http.delete = function (url, payload, headers, options) { - if (payload === void 0) { payload = {}; } - if (headers === void 0) { headers = {}; } - if (options === void 0) { options = {}; } - return this.request(url, {}, 'DELETE', payload, headers, options); - }; - // Default options are marked with * - Http.defaultOptions = { - method: '', - cache: 'no-cache', - credentials: 'same-origin', - headers: { - 'user-agent': 'Mozilla/4.0 MDN Example', - 'content-type': 'application/json' - }, - mode: 'cors', - redirect: 'follow', - referrer: 'no-referrer' // *client, no-referrer - }; - return Http; -}()); - var HttpMethod; (function (HttpMethod) { HttpMethod["GET"] = "get"; @@ -4589,7 +5662,7 @@ var ModelConf = /** @class */ (function () { /** * The host/domain of api server */ - this.baseUrl = ''; + this.baseURL = ''; /** * The endpoint of model entity */ @@ -4599,7 +5672,7 @@ var ModelConf = /** @class */ (function () { */ this.methods = new Map(); if (conf) { - this.baseUrl = conf.baseUrl; + this.baseURL = conf.baseURL; this.endpointPath = conf.endpointPath; if (conf.methods) { conf.methods.forEach(function (method) { @@ -4614,8 +5687,8 @@ var ModelConf = /** @class */ (function () { */ ModelConf.prototype.extend = function (conf) { var _this = this; - if (conf.baseUrl) { - this.baseUrl = conf.baseUrl; + if (conf.baseURL) { + this.baseURL = conf.baseURL; } if (conf.endpointPath) { this.endpointPath = conf.endpointPath; @@ -4713,7 +5786,7 @@ var HttpConf = /** @class */ (function () { return HttpConf; }()); var defaultConf = { - "baseUrl": "http://localhost:3000", + "baseURL": "http://localhost:3000", "endpointPath": "/{self}", "methods": [ { @@ -4873,13 +5946,14 @@ var Model = /** @class */ (function (_super) { Model.fetch = function (conf) { if (conf === void 0) { conf = this.getMethodConf('fetch'); } return __awaiter(this, void 0, void 0, function () { - var _conf, url, data; + var _conf, url, method, data; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('fetch', conf); url = this.getUrl(_conf); - return [4 /*yield*/, Http[_conf.http.method](url) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url) .catch(function (err) { console.log(err); })]; case 1: data = (_a.sent()) || []; @@ -4961,13 +6035,14 @@ var Model = /** @class */ (function (_super) { Model.fetchById = function (id, conf) { if (conf === void 0) { conf = this.getMethodConf('fetchById'); } return __awaiter(this, void 0, void 0, function () { - var _conf, url, data; + var _conf, url, method, data; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('fetchById', conf); url = this.getUrl(_conf, new PathParam('id', id.toString())); - return [4 /*yield*/, Http[_conf.http.method](url) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url) .catch(function (err) { console.log(err); })]; case 1: data = (_a.sent()) || []; @@ -4993,14 +6068,15 @@ var Model = /** @class */ (function (_super) { Model.exist = function (id, conf) { if (conf === void 0) { conf = this.getMethodConf('exist'); } return __awaiter(this, void 0, void 0, function () { - var _conf, data, url; + var _conf, data, url, method; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('exist', conf); if (!_conf.remote) return [3 /*break*/, 2]; url = this.getUrl(_conf, new PathParam('id', id.toString())); - return [4 /*yield*/, Http[_conf.http.method](url) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url) .catch(function (err) { console.log(err); })]; case 1: data = (_a.sent()) || []; @@ -5022,13 +6098,14 @@ var Model = /** @class */ (function (_super) { Model.count = function (conf) { if (conf === void 0) { conf = this.getMethodConf('count'); } return __awaiter(this, void 0, void 0, function () { - var _conf, data; + var _conf, data, method; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('count', conf); if (!_conf.remote) return [3 /*break*/, 2]; - return [4 /*yield*/, Http[_conf.http.method](this.getUrl(_conf)) + method = _conf.http.method; + return [4 /*yield*/, Http[method](this.getUrl(_conf)) .catch(function (err) { console.log(err); })]; case 1: data = (_a.sent()) || []; @@ -5051,13 +6128,14 @@ var Model = /** @class */ (function (_super) { Model.create = function (data, conf) { if (conf === void 0) { conf = this.getMethodConf('create'); } return __awaiter(this, void 0, void 0, function () { - var _conf, dataOutput; + var _conf, dataOutput, method; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('create', conf); if (!_conf.remote) return [3 /*break*/, 2]; - return [4 /*yield*/, Http[_conf.http.method](this.getUrl(_conf), data) + method = _conf.http.method; + return [4 /*yield*/, Http[method](this.getUrl(_conf), data) .catch(function (err) { console.log(err); })]; case 1: dataOutput = (_a.sent()) || []; @@ -5084,14 +6162,15 @@ var Model = /** @class */ (function (_super) { Model.update = function (id, data, conf) { if (conf === void 0) { conf = this.getMethodConf('update'); } return __awaiter(this, void 0, void 0, function () { - var _conf, dataOutput, url; + var _conf, dataOutput, url, method; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('update', conf); if (!_conf.remote) return [3 /*break*/, 2]; url = this.getUrl(_conf, new PathParam('id', id.toString())); - return [4 /*yield*/, Http[_conf.http.method](url, data) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url, data) .catch(function (err) { console.log(err); })]; case 1: dataOutput = (_a.sent()) || []; @@ -5122,14 +6201,15 @@ var Model = /** @class */ (function (_super) { Model.deleteById = function (id, conf) { if (conf === void 0) { conf = this.getMethodConf('deleteById'); } return __awaiter(this, void 0, void 0, function () { - var _conf, url, dataOutput; + var _conf, url, method, dataOutput; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('deleteById', conf); if (!_conf.remote) return [3 /*break*/, 2]; url = this.getUrl(_conf, new PathParam('id', id.toString())); - return [4 /*yield*/, Http[_conf.http.method](url) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url) .catch(function (err) { console.log(err); })]; case 1: dataOutput = (_a.sent()) || []; @@ -5153,13 +6233,14 @@ var Model = /** @class */ (function (_super) { Model.delete = function (conf) { if (conf === void 0) { conf = this.getMethodConf('deleteById'); } return __awaiter(this, void 0, void 0, function () { - var _conf, dataOutput; + var _conf, method, dataOutput; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('deleteById', conf); if (!_conf.remote) return [3 /*break*/, 2]; - return [4 /*yield*/, Http[_conf.http.method](this.getUrl(_conf)) + method = _conf.http.method; + return [4 /*yield*/, Http[method](this.getUrl(_conf)) .catch(function (err) { console.log(err); })]; case 1: dataOutput = (_a.sent()) || []; @@ -5195,13 +6276,9 @@ var Model = /** @class */ (function (_super) { for (var _i = 1; _i < arguments.length; _i++) { pathParams[_i - 1] = arguments[_i]; } - var baseUrl = this._conf.baseUrl; var methodPath = pathParams.length ? conf.http.bindPathParams(pathParams) : conf.http.path; - if (ModuleOptions.resources.baseUrl) { - baseUrl = ModuleOptions.resources.baseUrl; - } - return baseUrl + this._conf.endpointPath + methodPath; + return this._conf.endpointPath + methodPath; }; /** * Check if the method configuration exist and diff --git a/dist/vuex-orm.js b/dist/vuex-orm.js index 3b10247b..729a32ab 100644 --- a/dist/vuex-orm.js +++ b/dist/vuex-orm.js @@ -122,6 +122,1115 @@ return Container; }()); + var bind = function bind(fn, thisArg) { + return function wrap() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + return fn.apply(thisArg, args); + }; + }; + + /*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + var isBuffer_1 = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) + }; + + function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) + } + + /*global toString:true*/ + + // utils is a library of generic helper functions non-specific to axios + + var toString = Object.prototype.toString; + + /** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Array, otherwise false + */ + function isArray(val) { + return toString.call(val) === '[object Array]'; + } + + /** + * Determine if a value is an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ + function isArrayBuffer(val) { + return toString.call(val) === '[object ArrayBuffer]'; + } + + /** + * Determine if a value is a FormData + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an FormData, otherwise false + */ + function isFormData(val) { + return (typeof FormData !== 'undefined') && (val instanceof FormData); + } + + /** + * Determine if a value is a view on an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ + function isArrayBufferView(val) { + var result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); + } + return result; + } + + /** + * Determine if a value is a String + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a String, otherwise false + */ + function isString(val) { + return typeof val === 'string'; + } + + /** + * Determine if a value is a Number + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Number, otherwise false + */ + function isNumber(val) { + return typeof val === 'number'; + } + + /** + * Determine if a value is undefined + * + * @param {Object} val The value to test + * @returns {boolean} True if the value is undefined, otherwise false + */ + function isUndefined(val) { + return typeof val === 'undefined'; + } + + /** + * Determine if a value is an Object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Object, otherwise false + */ + function isObject(val) { + return val !== null && typeof val === 'object'; + } + + /** + * Determine if a value is a Date + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Date, otherwise false + */ + function isDate(val) { + return toString.call(val) === '[object Date]'; + } + + /** + * Determine if a value is a File + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a File, otherwise false + */ + function isFile(val) { + return toString.call(val) === '[object File]'; + } + + /** + * Determine if a value is a Blob + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Blob, otherwise false + */ + function isBlob(val) { + return toString.call(val) === '[object Blob]'; + } + + /** + * Determine if a value is a Function + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ + function isFunction(val) { + return toString.call(val) === '[object Function]'; + } + + /** + * Determine if a value is a Stream + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Stream, otherwise false + */ + function isStream(val) { + return isObject(val) && isFunction(val.pipe); + } + + /** + * Determine if a value is a URLSearchParams object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ + function isURLSearchParams(val) { + return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; + } + + /** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * @returns {String} The String freed of excess whitespace + */ + function trim(str) { + return str.replace(/^\s*/, '').replace(/\s*$/, ''); + } + + /** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + */ + function isStandardBrowserEnv() { + if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { + return false; + } + return ( + typeof window !== 'undefined' && + typeof document !== 'undefined' + ); + } + + /** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + */ + function forEach(obj, fn) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + + if (isArray(obj)) { + // Iterate over array values + for (var i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn.call(null, obj[key], key, obj); + } + } + } + } + + /** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * @returns {Object} Result of all merge properties + */ + function merge(/* obj1, obj2, obj3, ... */) { + var result = {}; + function assignValue(val, key) { + if (typeof result[key] === 'object' && typeof val === 'object') { + result[key] = merge(result[key], val); + } else { + result[key] = val; + } + } + + for (var i = 0, l = arguments.length; i < l; i++) { + forEach(arguments[i], assignValue); + } + return result; + } + + /** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * @return {Object} The resulting value of object a + */ + function extend(a, b, thisArg) { + forEach(b, function assignValue(val, key) { + if (thisArg && typeof val === 'function') { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }); + return a; + } + + var utils = { + isArray: isArray, + isArrayBuffer: isArrayBuffer, + isBuffer: isBuffer_1, + isFormData: isFormData, + isArrayBufferView: isArrayBufferView, + isString: isString, + isNumber: isNumber, + isObject: isObject, + isUndefined: isUndefined, + isDate: isDate, + isFile: isFile, + isBlob: isBlob, + isFunction: isFunction, + isStream: isStream, + isURLSearchParams: isURLSearchParams, + isStandardBrowserEnv: isStandardBrowserEnv, + forEach: forEach, + merge: merge, + extend: extend, + trim: trim + }; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var utils$1 = require('./utils'); + var normalizeHeaderName = require('./helpers/normalizeHeaderName'); + + var DEFAULT_CONTENT_TYPE = { + 'Content-Type': 'application/x-www-form-urlencoded' + }; + + function setContentTypeIfUnset(headers, value) { + if (!utils$1.isUndefined(headers) && utils$1.isUndefined(headers['Content-Type'])) { + headers['Content-Type'] = value; + } + } + + function getDefaultAdapter() { + var adapter; + if (typeof XMLHttpRequest !== 'undefined') { + // For browsers use XHR adapter + adapter = require('./adapters/xhr'); + } else if (typeof process !== 'undefined') { + // For node use HTTP adapter + adapter = require('./adapters/http'); + } + return adapter; + } + + var defaults = { + adapter: getDefaultAdapter(), + + transformRequest: [function transformRequest(data, headers) { + normalizeHeaderName(headers, 'Content-Type'); + if (utils$1.isFormData(data) || + utils$1.isArrayBuffer(data) || + utils$1.isBuffer(data) || + utils$1.isStream(data) || + utils$1.isFile(data) || + utils$1.isBlob(data) + ) { + return data; + } + if (utils$1.isArrayBufferView(data)) { + return data.buffer; + } + if (utils$1.isURLSearchParams(data)) { + setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); + return data.toString(); + } + if (utils$1.isObject(data)) { + setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); + return JSON.stringify(data); + } + return data; + }], + + transformResponse: [function transformResponse(data) { + /*eslint no-param-reassign:0*/ + if (typeof data === 'string') { + try { + data = JSON.parse(data); + } catch (e) { /* Ignore */ } + } + return data; + }], + + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + } + }; + + defaults.headers = { + common: { + 'Accept': 'application/json, text/plain, */*' + } + }; + + utils$1.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { + defaults.headers[method] = {}; + }); + + utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + defaults.headers[method] = utils$1.merge(DEFAULT_CONTENT_TYPE); + }); + + module.exports = defaults; + + var defaults$1 = /*#__PURE__*/Object.freeze({ + + }); + + function InterceptorManager() { + this.handlers = []; + } + + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ + InterceptorManager.prototype.use = function use(fulfilled, rejected) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected + }); + return this.handlers.length - 1; + }; + + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + */ + InterceptorManager.prototype.eject = function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + }; + + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + */ + InterceptorManager.prototype.forEach = function forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); + }; + + var InterceptorManager_1 = InterceptorManager; + + /** + * Transform the data for a request or a response + * + * @param {Object|String} data The data to be transformed + * @param {Array} headers The headers for the request or response + * @param {Array|Function} fns A single function or Array of functions + * @returns {*} The resulting transformed data + */ + var transformData = function transformData(data, headers, fns) { + /*eslint no-param-reassign:0*/ + utils.forEach(fns, function transform(fn) { + data = fn(data, headers); + }); + + return data; + }; + + var isCancel = function isCancel(value) { + return !!(value && value.__CANCEL__); + }; + + /** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ + var isAbsoluteURL = function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); + }; + + /** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * @returns {string} The combined URL + */ + var combineURLs = function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; + }; + + /** + * Throws a `Cancel` if cancellation has been requested. + */ + function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } + } + + /** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * @returns {Promise} The Promise to be fulfilled + */ + var dispatchRequest = function dispatchRequest(config) { + throwIfCancellationRequested(config); + + // Support baseURL config + if (config.baseURL && !isAbsoluteURL(config.url)) { + config.url = combineURLs(config.baseURL, config.url); + } + + // Ensure headers exist + config.headers = config.headers || {}; + + // Transform request data + config.data = transformData( + config.data, + config.headers, + config.transformRequest + ); + + // Flatten headers + config.headers = utils.merge( + config.headers.common || {}, + config.headers[config.method] || {}, + config.headers || {} + ); + + utils.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + function cleanHeaderConfig(method) { + delete config.headers[method]; + } + ); + + var adapter = config.adapter || defaults$1.adapter; + + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData( + response.data, + response.headers, + config.transformResponse + ); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData( + reason.response.data, + reason.response.headers, + config.transformResponse + ); + } + } + + return Promise.reject(reason); + }); + }; + + /** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + */ + function Axios(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager_1(), + response: new InterceptorManager_1() + }; + } + + /** + * Dispatch a request + * + * @param {Object} config The config specific for this request (merged with this.defaults) + */ + Axios.prototype.request = function request(config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof config === 'string') { + config = utils.merge({ + url: arguments[0] + }, arguments[1]); + } + + config = utils.merge(defaults$1, {method: 'get'}, this.defaults, config); + config.method = config.method.toLowerCase(); + + // Hook up interceptors middleware + var chain = [dispatchRequest, undefined]; + var promise = Promise.resolve(config); + + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + chain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + chain.push(interceptor.fulfilled, interceptor.rejected); + }); + + while (chain.length) { + promise = promise.then(chain.shift(), chain.shift()); + } + + return promise; + }; + + // Provide aliases for supported request methods + utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(utils.merge(config || {}, { + method: method, + url: url + })); + }; + }); + + utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, data, config) { + return this.request(utils.merge(config || {}, { + method: method, + url: url, + data: data + })); + }; + }); + + var Axios_1 = Axios; + + /** + * A `Cancel` is an object that is thrown when an operation is canceled. + * + * @class + * @param {string=} message The message. + */ + function Cancel(message) { + this.message = message; + } + + Cancel.prototype.toString = function toString() { + return 'Cancel' + (this.message ? ': ' + this.message : ''); + }; + + Cancel.prototype.__CANCEL__ = true; + + var Cancel_1 = Cancel; + + /** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @class + * @param {Function} executor The executor function. + */ + function CancelToken(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + var resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + var token = this; + executor(function cancel(message) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new Cancel_1(message); + resolvePromise(token.reason); + }); + } + + /** + * Throws a `Cancel` if cancellation has been requested. + */ + CancelToken.prototype.throwIfRequested = function throwIfRequested() { + if (this.reason) { + throw this.reason; + } + }; + + /** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ + CancelToken.source = function source() { + var cancel; + var token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token: token, + cancel: cancel + }; + }; + + var CancelToken_1 = CancelToken; + + /** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * @returns {Function} + */ + var spread = function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; + }; + + /** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * @return {Axios} A new instance of Axios + */ + function createInstance(defaultConfig) { + var context = new Axios_1(defaultConfig); + var instance = bind(Axios_1.prototype.request, context); + + // Copy axios.prototype to instance + utils.extend(instance, Axios_1.prototype, context); + + // Copy context to instance + utils.extend(instance, context); + + return instance; + } + + // Create the default instance to be exported + var axios = createInstance(defaults$1); + + // Expose Axios class to allow class inheritance + axios.Axios = Axios_1; + + // Factory for creating new instances + axios.create = function create(instanceConfig) { + return createInstance(utils.merge(defaults$1, instanceConfig)); + }; + + // Expose Cancel & CancelToken + axios.Cancel = Cancel_1; + axios.CancelToken = CancelToken_1; + axios.isCancel = isCancel; + + // Expose all/spread + axios.all = function all(promises) { + return Promise.all(promises); + }; + axios.spread = spread; + + var axios_1 = axios; + + // Allow use of default import syntax in TypeScript + var default_1 = axios; + axios_1.default = default_1; + + var axios$1 = axios_1; + + var __assign$1 = (undefined && undefined.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + var Http = /** @class */ (function () { + function Http() { + } + Http.conf = function (config) { + this.defaultConf = config; + }; + Http.registerRequestInterceptor = function (requestInterceptor) { + axios$1.interceptors.request.use(requestInterceptor); + }; + Http.registerResponseInterceptor = function (responseInterceptor) { + axios$1.interceptors.response.use(responseInterceptor); + }; + Http.mergeConf = function (config) { + return __assign$1({}, this.defaultConf, config); + }; + Http.head = function (url, config) { + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.head(url, config); + }; + Http.get = function (url, config) { + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.get(url, config); + }; + Http.post = function (url, data, config) { + if (data === void 0) { data = {}; } + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.post(url, data, config); + }; + Http.patch = function (url, data, config) { + if (data === void 0) { data = {}; } + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.patch(url, data, config); + }; + Http.put = function (url, data, config) { + if (data === void 0) { data = {}; } + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.put(url, data, config); + }; + Http.delete = function (url, config) { + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return axios$1.delete(url, config); + }; + return Http; + }()); + var ModuleOptions = /** @class */ (function () { function ModuleOptions() { } @@ -130,14 +1239,48 @@ if (options.namespace) { this.namespace = options.namespace; } - if (options.resources) { - this.resources = options.resources; + if (options.http) { + this.http = options.http; } + this.check(); + this.confAxiosModule(); }; - ModuleOptions.namespace = 'entities'; - ModuleOptions.resources = { - baseUrl: '' + ModuleOptions.confAxiosModule = function () { + Http.conf(this.http); + if (this.http.requestInterceptor) { + Http.registerRequestInterceptor(this.http.requestInterceptor); + } + if (this.http.responseInterceptor) { + Http.registerResponseInterceptor(this.http.responseInterceptor); + } + }; + ModuleOptions.check = function () { + if (!this.http) { + throw new Error('Vuex orm resources: missing default http conf'); + } + this.checkBaseUrl(); + this.checkHeader(); + this.checkTimeout(); + }; + ModuleOptions.checkBaseUrl = function () { + if (!this.http.baseURL) { + throw new Error('Vuex orm resources: missing default http baseURL conf'); + } }; + ModuleOptions.checkTimeout = function () { + if (!this.http.timeout) { + throw new Error('Vuex orm resources: missing default http timeout conf'); + } + }; + ModuleOptions.checkHeader = function () { + if (!this.http.headers) { + throw new Error('Vuex orm resources: missing default http headers conf'); + } + if (!this.http.headers['Content-Type']) { + throw new Error('Vuex orm resources: missing default http Content-Type headers conf'); + } + }; + ModuleOptions.namespace = 'entities'; return ModuleOptions; }()); @@ -1318,7 +2461,7 @@ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); - var __assign$1 = (undefined && undefined.__assign) || Object.assign || function(t) { + var __assign$2 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -1337,7 +2480,7 @@ Relation.prototype.mapRecords = function (records, key) { return records.reduce(function (records, record) { var _a; - return __assign$1({}, records, (_a = {}, _a[record[key]] = record, _a)); + return __assign$2({}, records, (_a = {}, _a[record[key]] = record, _a)); }, {}); }; /** @@ -1777,7 +2920,7 @@ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); - var __assign$2 = (undefined && undefined.__assign) || Object.assign || function(t) { + var __assign$3 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -1885,7 +3028,7 @@ related.forEach(function (id) { var _a, _b; var pivotKey = record[_this.parentKey] + "_" + id; - data[_this.pivot.entity] = __assign$2({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { + data[_this.pivot.entity] = __assign$3({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { $id: pivotKey }, _b[_this.foreignPivotKey] = record[_this.parentKey], _b[_this.relatedPivotKey] = id, _b), _a)); }); @@ -2148,7 +3291,7 @@ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); - var __assign$3 = (undefined && undefined.__assign) || Object.assign || function(t) { + var __assign$4 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -2259,7 +3402,7 @@ var _a, _b; var parentId = record[_this.parentKey]; var pivotKey = parentId + "_" + id + "_" + parent.entity; - data[_this.pivot.entity] = __assign$3({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { + data[_this.pivot.entity] = __assign$4({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { $id: pivotKey }, _b[_this.relatedId] = id, _b[_this.id] = parentId, _b[_this.type] = parent.entity, _b), _a)); }); @@ -2277,7 +3420,7 @@ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); - var __assign$4 = (undefined && undefined.__assign) || Object.assign || function(t) { + var __assign$5 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -2388,7 +3531,7 @@ var _a, _b; var parentId = record[_this.parentKey]; var pivotKey = id + "_" + parentId + "_" + _this.related.entity; - data[_this.pivot.entity] = __assign$4({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { + data[_this.pivot.entity] = __assign$5({}, data[_this.pivot.entity], (_a = {}, _a[pivotKey] = (_b = { $id: pivotKey }, _b[_this.relatedId] = parentId, _b[_this.id] = id, _b[_this.type] = _this.related.entity, _b), _a)); }); @@ -2449,7 +3592,7 @@ return IdAttribute; }()); - var __assign$5 = (undefined && undefined.__assign) || Object.assign || function(t) { + var __assign$6 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -2466,7 +3609,7 @@ ProcessStrategy.create = function (noKey, model, parent, attr) { var _this = this; return function (value, parentValue, key) { - var record = __assign$5({}, value); + var record = __assign$6({}, value); record = _this.fix(record, model); record = _this.setId(record, model, noKey, key); record = _this.generateMorphFields(record, parentValue, parent, attr); @@ -2503,7 +3646,7 @@ */ ProcessStrategy.setId = function (record, model, noKey, key) { var id = model.id(record); - return __assign$5({}, record, { $id: id !== undefined ? id : noKey.increment(key) }); + return __assign$6({}, record, { $id: id !== undefined ? id : noKey.increment(key) }); }; /** * Generate morph fields. This method will generate fileds needed for the @@ -2520,12 +3663,12 @@ if (parent === undefined) { return record; } - return __assign$5((_a = {}, _a[attr.id] = parentValue.$id, _a[attr.type] = parent.entity, _a), record); + return __assign$6((_a = {}, _a[attr.id] = parentValue.$id, _a[attr.type] = parent.entity, _a), record); }; return ProcessStrategy; }()); - var __assign$6 = (undefined && undefined.__assign) || Object.assign || function(t) { + var __assign$7 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -2547,7 +3690,7 @@ idAttribute: IdAttribute.create(noKey, model), processStrategy: ProcessStrategy.create(noKey, model, parent, attr) }); - var definition = this.definition(model, __assign$6({}, schemas, (_a = {}, _a[model.entity] = thisSchema, _a))); + var definition = this.definition(model, __assign$7({}, schemas, (_a = {}, _a[model.entity] = thisSchema, _a))); thisSchema.define(definition); return thisSchema; }; @@ -2754,7 +3897,7 @@ return Attacher; }()); - var __assign$7 = (undefined && undefined.__assign) || Object.assign || function(t) { + var __assign$8 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -2788,7 +3931,7 @@ newRecords[id] = record; return newRecords; } - newRecords[newStringId] = __assign$7({}, record, { $id: newId }); + newRecords[newStringId] = __assign$8({}, record, { $id: newId }); return newRecords; }, {}); }; @@ -2975,7 +4118,7 @@ return Hook; }()); - var __assign$8 = (undefined && undefined.__assign) || Object.assign || function(t) { + var __assign$9 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -3222,7 +4365,7 @@ callback(); return; } - payload = __assign$8({ entity: this.entity }, payload); + payload = __assign$9({ entity: this.entity }, payload); this.actionContext.commit(this.rootState.$name + "/" + method, payload, { root: true }); }; /** @@ -3290,7 +4433,7 @@ Query.prototype.commitInsert = function (data) { var _this = this; this.commit('commitInsert', { data: data }, function () { - _this.state.data = __assign$8({}, _this.state.data, data); + _this.state.data = __assign$9({}, _this.state.data, data); }); }; /** @@ -3377,7 +4520,7 @@ Query.prototype.commitUpdate = function (data) { var _this = this; this.commit('commitUpdate', { data: data }, function () { - _this.state.data = __assign$8({}, _this.state.data, data); + _this.state.data = __assign$9({}, _this.state.data, data); }); }; /** @@ -3479,7 +4622,7 @@ if (!record) { return null; } - return this.item(__assign$8({}, record)); + return this.item(__assign$9({}, record)); }; /** * Returns all record of the query chain result. @@ -3510,7 +4653,7 @@ */ Query.prototype.records = function (records) { var theRecords = records || this.state.data; - return Object.keys(theRecords).map(function (id) { return (__assign$8({}, theRecords[id])); }); + return Object.keys(theRecords).map(function (id) { return (__assign$9({}, theRecords[id])); }); }; /** * Add a and where clause to the query. @@ -4499,76 +5642,6 @@ return BaseModel; }()); - var __assign$9 = (undefined && undefined.__assign) || Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - var Http = /** @class */ (function () { - function Http() { - } - Http.request = function (url, _query, _method, _body, _headers, options) { - if (_body === void 0) { _body = {}; } - if (_headers === void 0) { _headers = {}; } - if (options === void 0) { options = {}; } - var _options = __assign$9({}, this.defaultOptions, options); - _options.method = _method; - if (Object.keys(_body).length) { - _options.body = JSON.stringify(_body); - } - return fetch(url, _options) - .then(function (response) { - if (!response.ok) { - return Promise.reject(new Error('http request failed')); - } - else { - return Promise.resolve(response.json()); - } - }); // parses response to JSON - }; - Http.get = function (url, params, headers, options) { - if (params === void 0) { params = {}; } - if (headers === void 0) { headers = {}; } - if (options === void 0) { options = {}; } - return this.request(url, params, 'GET', {}, headers, options); - }; - Http.post = function (url, payload, headers, options) { - if (payload === void 0) { payload = {}; } - if (headers === void 0) { headers = {}; } - if (options === void 0) { options = {}; } - return this.request(url, {}, 'POST', payload, headers, options); - }; - Http.put = function (url, payload, headers, options) { - if (payload === void 0) { payload = {}; } - if (headers === void 0) { headers = {}; } - if (options === void 0) { options = {}; } - return this.request(url, {}, 'PUT', payload, headers, options); - }; - Http.delete = function (url, payload, headers, options) { - if (payload === void 0) { payload = {}; } - if (headers === void 0) { headers = {}; } - if (options === void 0) { options = {}; } - return this.request(url, {}, 'DELETE', payload, headers, options); - }; - // Default options are marked with * - Http.defaultOptions = { - method: '', - cache: 'no-cache', - credentials: 'same-origin', - headers: { - 'user-agent': 'Mozilla/4.0 MDN Example', - 'content-type': 'application/json' - }, - mode: 'cors', - redirect: 'follow', - referrer: 'no-referrer' // *client, no-referrer - }; - return Http; - }()); - var HttpMethod; (function (HttpMethod) { HttpMethod["GET"] = "get"; @@ -4595,7 +5668,7 @@ /** * The host/domain of api server */ - this.baseUrl = ''; + this.baseURL = ''; /** * The endpoint of model entity */ @@ -4605,7 +5678,7 @@ */ this.methods = new Map(); if (conf) { - this.baseUrl = conf.baseUrl; + this.baseURL = conf.baseURL; this.endpointPath = conf.endpointPath; if (conf.methods) { conf.methods.forEach(function (method) { @@ -4620,8 +5693,8 @@ */ ModelConf.prototype.extend = function (conf) { var _this = this; - if (conf.baseUrl) { - this.baseUrl = conf.baseUrl; + if (conf.baseURL) { + this.baseURL = conf.baseURL; } if (conf.endpointPath) { this.endpointPath = conf.endpointPath; @@ -4719,7 +5792,7 @@ return HttpConf; }()); var defaultConf = { - "baseUrl": "http://localhost:3000", + "baseURL": "http://localhost:3000", "endpointPath": "/{self}", "methods": [ { @@ -4879,13 +5952,14 @@ Model.fetch = function (conf) { if (conf === void 0) { conf = this.getMethodConf('fetch'); } return __awaiter(this, void 0, void 0, function () { - var _conf, url, data; + var _conf, url, method, data; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('fetch', conf); url = this.getUrl(_conf); - return [4 /*yield*/, Http[_conf.http.method](url) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url) .catch(function (err) { console.log(err); })]; case 1: data = (_a.sent()) || []; @@ -4967,13 +6041,14 @@ Model.fetchById = function (id, conf) { if (conf === void 0) { conf = this.getMethodConf('fetchById'); } return __awaiter(this, void 0, void 0, function () { - var _conf, url, data; + var _conf, url, method, data; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('fetchById', conf); url = this.getUrl(_conf, new PathParam('id', id.toString())); - return [4 /*yield*/, Http[_conf.http.method](url) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url) .catch(function (err) { console.log(err); })]; case 1: data = (_a.sent()) || []; @@ -4999,14 +6074,15 @@ Model.exist = function (id, conf) { if (conf === void 0) { conf = this.getMethodConf('exist'); } return __awaiter(this, void 0, void 0, function () { - var _conf, data, url; + var _conf, data, url, method; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('exist', conf); if (!_conf.remote) return [3 /*break*/, 2]; url = this.getUrl(_conf, new PathParam('id', id.toString())); - return [4 /*yield*/, Http[_conf.http.method](url) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url) .catch(function (err) { console.log(err); })]; case 1: data = (_a.sent()) || []; @@ -5028,13 +6104,14 @@ Model.count = function (conf) { if (conf === void 0) { conf = this.getMethodConf('count'); } return __awaiter(this, void 0, void 0, function () { - var _conf, data; + var _conf, data, method; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('count', conf); if (!_conf.remote) return [3 /*break*/, 2]; - return [4 /*yield*/, Http[_conf.http.method](this.getUrl(_conf)) + method = _conf.http.method; + return [4 /*yield*/, Http[method](this.getUrl(_conf)) .catch(function (err) { console.log(err); })]; case 1: data = (_a.sent()) || []; @@ -5057,13 +6134,14 @@ Model.create = function (data, conf) { if (conf === void 0) { conf = this.getMethodConf('create'); } return __awaiter(this, void 0, void 0, function () { - var _conf, dataOutput; + var _conf, dataOutput, method; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('create', conf); if (!_conf.remote) return [3 /*break*/, 2]; - return [4 /*yield*/, Http[_conf.http.method](this.getUrl(_conf), data) + method = _conf.http.method; + return [4 /*yield*/, Http[method](this.getUrl(_conf), data) .catch(function (err) { console.log(err); })]; case 1: dataOutput = (_a.sent()) || []; @@ -5090,14 +6168,15 @@ Model.update = function (id, data, conf) { if (conf === void 0) { conf = this.getMethodConf('update'); } return __awaiter(this, void 0, void 0, function () { - var _conf, dataOutput, url; + var _conf, dataOutput, url, method; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('update', conf); if (!_conf.remote) return [3 /*break*/, 2]; url = this.getUrl(_conf, new PathParam('id', id.toString())); - return [4 /*yield*/, Http[_conf.http.method](url, data) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url, data) .catch(function (err) { console.log(err); })]; case 1: dataOutput = (_a.sent()) || []; @@ -5128,14 +6207,15 @@ Model.deleteById = function (id, conf) { if (conf === void 0) { conf = this.getMethodConf('deleteById'); } return __awaiter(this, void 0, void 0, function () { - var _conf, url, dataOutput; + var _conf, url, method, dataOutput; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('deleteById', conf); if (!_conf.remote) return [3 /*break*/, 2]; url = this.getUrl(_conf, new PathParam('id', id.toString())); - return [4 /*yield*/, Http[_conf.http.method](url) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url) .catch(function (err) { console.log(err); })]; case 1: dataOutput = (_a.sent()) || []; @@ -5159,13 +6239,14 @@ Model.delete = function (conf) { if (conf === void 0) { conf = this.getMethodConf('deleteById'); } return __awaiter(this, void 0, void 0, function () { - var _conf, dataOutput; + var _conf, method, dataOutput; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('deleteById', conf); if (!_conf.remote) return [3 /*break*/, 2]; - return [4 /*yield*/, Http[_conf.http.method](this.getUrl(_conf)) + method = _conf.http.method; + return [4 /*yield*/, Http[method](this.getUrl(_conf)) .catch(function (err) { console.log(err); })]; case 1: dataOutput = (_a.sent()) || []; @@ -5201,13 +6282,9 @@ for (var _i = 1; _i < arguments.length; _i++) { pathParams[_i - 1] = arguments[_i]; } - var baseUrl = this._conf.baseUrl; var methodPath = pathParams.length ? conf.http.bindPathParams(pathParams) : conf.http.path; - if (ModuleOptions.resources.baseUrl) { - baseUrl = ModuleOptions.resources.baseUrl; - } - return baseUrl + this._conf.endpointPath + methodPath; + return this._conf.endpointPath + methodPath; }; /** * Check if the method configuration exist and diff --git a/dist/vuex-orm.min.js b/dist/vuex-orm.min.js index 3e6e45bc..5076a22b 100644 --- a/dist/vuex-orm.min.js +++ b/dist/vuex-orm.min.js @@ -1 +1 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.VuexORM=e()}(this,function(){"use strict";String.prototype.startsWith||(String.prototype.startsWith=function(t,e){return this.substr(!e||e<0?0:+e,t.length)===t}),Array.prototype.includes||(Array.prototype.includes=function(t){for(var e=[],n=1;n=e}:"="===e&&"number"==typeof n?i=function(t){return t.length===n}:">"===e&&"number"==typeof n?i=function(t){return t.length>n}:">="===e&&"number"==typeof n?i=function(t){return t.length>=n}:"<"===e&&"number"==typeof n?i=function(t){return t.lengtha[0]&&e[1]=e}:"="===e&&"number"==typeof n?i=function(t){return t.length===n}:">"===e&&"number"==typeof n?i=function(t){return t.length>n}:">="===e&&"number"==typeof n?i=function(t){return t.length>=n}:"<"===e&&"number"==typeof n?i=function(t){return t.lengtha[0]&&e[1] AxiosRequestConfig | Promise; +export declare type InterceptorResponseClosure = (record: AxiosResponse) => AxiosResponse | Promise>; +export declare type HttpConf = AxiosRequestConfig; export default class Http { - static defaultOptions: RequestInit; - static request(url: string, _query: {}, _method: string, _body?: {}, _headers?: {}, options?: {}): Promise; - static get(url: string, params?: {}, headers?: {}, options?: {}): Promise; - static post(url: string, payload?: {}, headers?: {}, options?: {}): Promise; - static put(url: string, payload?: {}, headers?: {}, options?: {}): Promise; - static delete(url: string, payload?: {}, headers?: {}, options?: {}): Promise; + static defaultConf: AxiosRequestConfig; + static conf(config: AxiosRequestConfig): void; + static registerRequestInterceptor(requestInterceptor: InterceptorRequestClosure): void; + static registerResponseInterceptor(responseInterceptor: InterceptorResponseClosure): void; + private static mergeConf; + static head(url: string, config?: AxiosRequestConfig): AxiosPromise; + static get(url: string, config?: AxiosRequestConfig): AxiosPromise; + static post(url: string, data?: {}, config?: AxiosRequestConfig): AxiosPromise; + static patch(url: string, data?: {}, config?: AxiosRequestConfig): AxiosPromise; + static put(url: string, data?: {}, config?: AxiosRequestConfig): AxiosPromise; + static delete(url: string, config?: AxiosRequestConfig): AxiosPromise; } diff --git a/lib/http/Http.js b/lib/http/Http.js index b0ae4737..11ded09f 100644 --- a/lib/http/Http.js +++ b/lib/http/Http.js @@ -6,64 +6,54 @@ var __assign = (this && this.__assign) || Object.assign || function(t) { } return t; }; +import Axios from 'axios'; var Http = /** @class */ (function () { function Http() { } - Http.request = function (url, _query, _method, _body, _headers, options) { - if (_body === void 0) { _body = {}; } - if (_headers === void 0) { _headers = {}; } - if (options === void 0) { options = {}; } - var _options = __assign({}, this.defaultOptions, options); - _options.method = _method; - if (Object.keys(_body).length) { - _options.body = JSON.stringify(_body); - } - return fetch(url, _options) - .then(function (response) { - if (!response.ok) { - return Promise.reject(new Error('http request failed')); - } - else { - return Promise.resolve(response.json()); - } - }); // parses response to JSON + Http.conf = function (config) { + this.defaultConf = config; }; - Http.get = function (url, params, headers, options) { - if (params === void 0) { params = {}; } - if (headers === void 0) { headers = {}; } - if (options === void 0) { options = {}; } - return this.request(url, params, 'GET', {}, headers, options); + Http.registerRequestInterceptor = function (requestInterceptor) { + Axios.interceptors.request.use(requestInterceptor); }; - Http.post = function (url, payload, headers, options) { - if (payload === void 0) { payload = {}; } - if (headers === void 0) { headers = {}; } - if (options === void 0) { options = {}; } - return this.request(url, {}, 'POST', payload, headers, options); + Http.registerResponseInterceptor = function (responseInterceptor) { + Axios.interceptors.response.use(responseInterceptor); }; - Http.put = function (url, payload, headers, options) { - if (payload === void 0) { payload = {}; } - if (headers === void 0) { headers = {}; } - if (options === void 0) { options = {}; } - return this.request(url, {}, 'PUT', payload, headers, options); + Http.mergeConf = function (config) { + return __assign({}, this.defaultConf, config); }; - Http.delete = function (url, payload, headers, options) { - if (payload === void 0) { payload = {}; } - if (headers === void 0) { headers = {}; } - if (options === void 0) { options = {}; } - return this.request(url, {}, 'DELETE', payload, headers, options); + Http.head = function (url, config) { + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return Axios.head(url, config); }; - // Default options are marked with * - Http.defaultOptions = { - method: '', - cache: 'no-cache', - credentials: 'same-origin', - headers: { - 'user-agent': 'Mozilla/4.0 MDN Example', - 'content-type': 'application/json' - }, - mode: 'cors', - redirect: 'follow', - referrer: 'no-referrer' // *client, no-referrer + Http.get = function (url, config) { + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return Axios.get(url, config); + }; + Http.post = function (url, data, config) { + if (data === void 0) { data = {}; } + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return Axios.post(url, data, config); + }; + Http.patch = function (url, data, config) { + if (data === void 0) { data = {}; } + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return Axios.patch(url, data, config); + }; + Http.put = function (url, data, config) { + if (data === void 0) { data = {}; } + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return Axios.put(url, data, config); + }; + Http.delete = function (url, config) { + if (config === void 0) { config = this.defaultConf; } + this.mergeConf(config); + return Axios.delete(url, config); }; return Http; }()); diff --git a/lib/http/Http.js.map b/lib/http/Http.js.map index 4b5d1a4f..300ee2b0 100644 --- a/lib/http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AAA,EAAA,SAA6B,IAAI,CAAC,WAAW;QAE7C,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAA;QACtB,OAAO,KAAK,CAAC,KAAK,CAAI,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;IAC3C,CAAC;IAEa,QAAG,GAAjB,UACE,GAAW,EACX,IAAS,EACT,MAA6C;QAD7C,qBAAA,EAAA,SAAS;QACT,uBAAA,EAAA,SAA6B,IAAI,CAAC,WAAW;QAE7C,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAA;QACtB,OAAO,KAAK,CAAC,GAAG,CAAI,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;IACzC,CAAC;IAEa,WAAM,GAApB,UACE,GAAW,EACX,MAA6C;QAA7C,uBAAA,EAAA,SAA6B,IAAI,CAAC,WAAW;QAE7C,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAA;QACtB,OAAO,KAAK,CAAC,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IACnC,CAAC;IACH,WAAC;AAAD,CAAC,AAtED,IAsEC"} \ No newline at end of file diff --git a/lib/model/Model.d.ts b/lib/model/Model.d.ts index 318d8e03..1a1633db 100644 --- a/lib/model/Model.d.ts +++ b/lib/model/Model.d.ts @@ -1,12 +1,14 @@ import BaseModel from './BaseModel'; +import { HttpConf } from '../http/Http'; import { Record } from '../data'; import Query, { UpdateClosure } from '../query/Query'; import EntityCollection from '../query/EntityCollection'; import { Collection, Item } from '../query'; import ModelConf, { JsonModelConf, MethodConf, PathParam } from '../model/ModelConf'; export declare type UpdateReturn = Item | Collection | EntityCollection; +export declare type MethodConfParameter = MethodConf & HttpConf; export default class Model extends BaseModel { - static _conf: ModelConf | JsonModelConf; + static _conf: ModelConf | (JsonModelConf & HttpConf); /** * Configure a model with default conf and extend or override * the default configuration with a custom configuration present on @@ -24,7 +26,7 @@ export default class Model extends BaseModel { * @async * @return {Promise} fetched data */ - static fetch(conf?: MethodConf): Promise; + static fetch(conf?: MethodConfParameter): Promise; /** * Wrap find method * @param {MethodConf} conf a method's conf @@ -32,7 +34,7 @@ export default class Model extends BaseModel { * @async * @return {Promise} list of results */ - static find(conf?: MethodConf): Promise; + static find(conf?: MethodConfParameter): Promise; /** * Wrap findById method * @param {number} id of record to find @@ -40,7 +42,7 @@ export default class Model extends BaseModel { * @static * @return {Promise} result object */ - static findById(id: number, conf?: MethodConf): Promise; + static findById(id: number, conf?: MethodConfParameter): Promise; /** * Exec a fetchById api method with the default confs * or the pass confs and sync to the local store (optionaly) @@ -50,7 +52,7 @@ export default class Model extends BaseModel { * @async * @return {Promise} fetched item */ - static fetchById(id: number, conf?: MethodConf): Promise; + static fetchById(id: number, conf?: MethodConfParameter): Promise; /** * Check if record identified by id param exist * @param {number} id of the record to search @@ -58,14 +60,14 @@ export default class Model extends BaseModel { * @static * @return {Promise} the result */ - static exist(id: number, conf?: MethodConf): Promise; + static exist(id: number, conf?: MethodConfParameter): Promise; /** * Wrap count method * @param {MethodConf} conf a method's conf * @static * @return {Promise} number of element */ - static count(conf?: MethodConf): Promise; + static count(conf?: MethodConfParameter): Promise; /** * Wrap create method * @param {Record | Record[]} data to create @@ -73,7 +75,7 @@ export default class Model extends BaseModel { * @static * @return {Promise} the created data */ - static create(data: Record | Record[], conf?: MethodConf): Promise; + static create(data: Record | Record[], conf?: MethodConfParameter): Promise; /** * Wrap update method * @param {number} id of the record to search @@ -82,20 +84,20 @@ export default class Model extends BaseModel { * @static * @return {Promise} updated data */ - static update(id: number, data: Record | Record[] | UpdateClosure, conf?: MethodConf): Promise; + static update(id: number, data: Record | Record[] | UpdateClosure, conf?: MethodConfParameter): Promise; /** * Wrap deleteById method * @param id of record to delete * @param {MethodConf} conf a method's conf * @static */ - static deleteById(id: number, conf?: MethodConf): Promise; + static deleteById(id: number, conf?: MethodConfParameter): Promise; /** * Wrap deleteAll method * @param {MethodConf} conf a method's conf * @static */ - static delete(conf?: MethodConf): Promise; + static delete(conf?: MethodConfParameter): Promise; /** * Wrap query getter * @static @@ -109,7 +111,7 @@ export default class Model extends BaseModel { * @static * @return {string} api's url */ - protected static getUrl(conf: MethodConf, ...pathParams: PathParam[]): string; + protected static getUrl(conf: MethodConfParameter, ...pathParams: PathParam[]): string; /** * Check if the method configuration exist and * assign the pass method's conf to it @@ -121,7 +123,7 @@ export default class Model extends BaseModel { * @return {MethodConf} the new method's configuration * @throws Error */ - protected static checkMethodConf(methodName: string, conf: MethodConf): MethodConf; + protected static checkMethodConf(methodName: string, conf: MethodConfParameter): MethodConf; /** * Get the model conf * @static @@ -134,5 +136,5 @@ export default class Model extends BaseModel { * @static * @return {MethodConf} */ - protected static getMethodConf(methodName: string): MethodConf; + protected static getMethodConf(methodName: string): MethodConfParameter; } diff --git a/lib/model/Model.js b/lib/model/Model.js index b530bcd0..2d011629 100644 --- a/lib/model/Model.js +++ b/lib/model/Model.js @@ -45,7 +45,6 @@ var __generator = (this && this.__generator) || function (thisArg, body) { }; import BaseModel from './BaseModel'; import Http from '../http/Http'; -import ModuleOptions from '../options/Options'; import ModelConf, { defaultConf, MethodConf, PathParam } from '../model/ModelConf'; import { replaceAll } from '../support/Utils'; var Model = /** @class */ (function (_super) { @@ -85,13 +84,14 @@ var Model = /** @class */ (function (_super) { Model.fetch = function (conf) { if (conf === void 0) { conf = this.getMethodConf('fetch'); } return __awaiter(this, void 0, void 0, function () { - var _conf, url, data; + var _conf, url, method, data; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('fetch', conf); url = this.getUrl(_conf); - return [4 /*yield*/, Http[_conf.http.method](url) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url) .catch(function (err) { console.log(err); })]; case 1: data = (_a.sent()) || []; @@ -173,13 +173,14 @@ var Model = /** @class */ (function (_super) { Model.fetchById = function (id, conf) { if (conf === void 0) { conf = this.getMethodConf('fetchById'); } return __awaiter(this, void 0, void 0, function () { - var _conf, url, data; + var _conf, url, method, data; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('fetchById', conf); url = this.getUrl(_conf, new PathParam('id', id.toString())); - return [4 /*yield*/, Http[_conf.http.method](url) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url) .catch(function (err) { console.log(err); })]; case 1: data = (_a.sent()) || []; @@ -205,14 +206,15 @@ var Model = /** @class */ (function (_super) { Model.exist = function (id, conf) { if (conf === void 0) { conf = this.getMethodConf('exist'); } return __awaiter(this, void 0, void 0, function () { - var _conf, data, url; + var _conf, data, url, method; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('exist', conf); if (!_conf.remote) return [3 /*break*/, 2]; url = this.getUrl(_conf, new PathParam('id', id.toString())); - return [4 /*yield*/, Http[_conf.http.method](url) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url) .catch(function (err) { console.log(err); })]; case 1: data = (_a.sent()) || []; @@ -234,13 +236,14 @@ var Model = /** @class */ (function (_super) { Model.count = function (conf) { if (conf === void 0) { conf = this.getMethodConf('count'); } return __awaiter(this, void 0, void 0, function () { - var _conf, data; + var _conf, data, method; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('count', conf); if (!_conf.remote) return [3 /*break*/, 2]; - return [4 /*yield*/, Http[_conf.http.method](this.getUrl(_conf)) + method = _conf.http.method; + return [4 /*yield*/, Http[method](this.getUrl(_conf)) .catch(function (err) { console.log(err); })]; case 1: data = (_a.sent()) || []; @@ -263,13 +266,14 @@ var Model = /** @class */ (function (_super) { Model.create = function (data, conf) { if (conf === void 0) { conf = this.getMethodConf('create'); } return __awaiter(this, void 0, void 0, function () { - var _conf, dataOutput; + var _conf, dataOutput, method; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('create', conf); if (!_conf.remote) return [3 /*break*/, 2]; - return [4 /*yield*/, Http[_conf.http.method](this.getUrl(_conf), data) + method = _conf.http.method; + return [4 /*yield*/, Http[method](this.getUrl(_conf), data) .catch(function (err) { console.log(err); })]; case 1: dataOutput = (_a.sent()) || []; @@ -296,14 +300,15 @@ var Model = /** @class */ (function (_super) { Model.update = function (id, data, conf) { if (conf === void 0) { conf = this.getMethodConf('update'); } return __awaiter(this, void 0, void 0, function () { - var _conf, dataOutput, url; + var _conf, dataOutput, url, method; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('update', conf); if (!_conf.remote) return [3 /*break*/, 2]; url = this.getUrl(_conf, new PathParam('id', id.toString())); - return [4 /*yield*/, Http[_conf.http.method](url, data) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url, data) .catch(function (err) { console.log(err); })]; case 1: dataOutput = (_a.sent()) || []; @@ -334,14 +339,15 @@ var Model = /** @class */ (function (_super) { Model.deleteById = function (id, conf) { if (conf === void 0) { conf = this.getMethodConf('deleteById'); } return __awaiter(this, void 0, void 0, function () { - var _conf, url, dataOutput; + var _conf, url, method, dataOutput; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('deleteById', conf); if (!_conf.remote) return [3 /*break*/, 2]; url = this.getUrl(_conf, new PathParam('id', id.toString())); - return [4 /*yield*/, Http[_conf.http.method](url) + method = _conf.http.method; + return [4 /*yield*/, Http[method](url) .catch(function (err) { console.log(err); })]; case 1: dataOutput = (_a.sent()) || []; @@ -365,13 +371,14 @@ var Model = /** @class */ (function (_super) { Model.delete = function (conf) { if (conf === void 0) { conf = this.getMethodConf('deleteById'); } return __awaiter(this, void 0, void 0, function () { - var _conf, dataOutput; + var _conf, method, dataOutput; return __generator(this, function (_a) { switch (_a.label) { case 0: _conf = this.checkMethodConf('deleteById', conf); if (!_conf.remote) return [3 /*break*/, 2]; - return [4 /*yield*/, Http[_conf.http.method](this.getUrl(_conf)) + method = _conf.http.method; + return [4 /*yield*/, Http[method](this.getUrl(_conf)) .catch(function (err) { console.log(err); })]; case 1: dataOutput = (_a.sent()) || []; @@ -407,13 +414,9 @@ var Model = /** @class */ (function (_super) { for (var _i = 1; _i < arguments.length; _i++) { pathParams[_i - 1] = arguments[_i]; } - var baseUrl = this._conf.baseUrl; var methodPath = pathParams.length ? conf.http.bindPathParams(pathParams) : conf.http.path; - if (ModuleOptions.resources.baseUrl) { - baseUrl = ModuleOptions.resources.baseUrl; - } - return baseUrl + this._conf.endpointPath + methodPath; + return this._conf.endpointPath + methodPath; }; /** * Check if the method configuration exist and diff --git a/lib/model/Model.js.map b/lib/model/Model.js.map index 5c6d3586..8716f352 100644 --- a/lib/model/Model.js.map +++ b/lib/model/Model.js.map @@ -1 +1 @@ -{"version":3,"file":"Model.js","sourceRoot":"","sources":["../../src/model/Model.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,SAAS,MAAM,aAAa,CAAA;AACnC,OAAO,IAAI,MAAM,cAAc,CAAA;AAC/B,OAAO,aAAa,MAAM,oBAAoB,CAAA;AAK9C,OAAO,SAAS,EAAE,EAEhB,WAAW,EACX,UAAU,EAEV,SAAS,EACV,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAI7C;IAAmC,yBAAS;IAA5C;;IAwXA,CAAC;IArXC;;;;;;;;OAQG;IACW,UAAI,GAAlB,UAAoB,aAA6B;QAE/C,IAAM,YAAY,GAAkB,IAAI,CAAC,KAAsB,CAAA;QAE/D,wBAAwB;QACxB,IAAI,CAAC,KAAK,GAAG,IAAI,SAAS,CACxB,IAAI,CAAC,KAAK,CACR,UAAU,CACR,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,EAC3B,QAAQ,EACR,IAAI,CAAC,MAAM,CACZ,CACF,CACF,CAAA;QAED,sCAAsC;QACtC,IAAI,YAAY,EAAE;YAChB,IAAI,CAAC,KAAK,CAAC,MAAM,CACf,IAAI,CAAC,KAAK,CACR,UAAU,CACR,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,EAC5B,QAAQ,EACR,IAAI,CAAC,MAAM,CACZ,CACF,C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CAAC,CAAC,CAAE,IAAI,CAAC,IAAY,CAAC,IAAI,CAAA;QAEzE,OAAO,IAAI,CAAC,KAAK,CAAC,YAAY,GAAG,UAAU,CAAA;IAC7C,CAAC;IAED;;;;;;;;;;OAUG;IACc,qBAAe,GAAhC,UAAkC,UAAkB,EAAE,IAAyB;QAC7E,IAAM,KAAK,GAAG,IAAI,CAAC,KAAkB,CAAA;QACrC,IAAI,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,UAAU,CAAC,CAAA;QACtC,IAAI,IAAI,IAAI,OAAO,EAAE;YACnB,OAAO,GAAG,IAAI,UAAU,CAAC,OAAqB,CAAC,CAAA;YAC/C,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;SACrB;QACD,IAAG,CAAC,OAAO,EAAE;YACX,MAAM,IAAI,KAAK,CAAI,UAAU,oCAAiC,CAAC,CAAA;SAChE;QACD,OAAO,OAAqB,CAAA;IAC9B,CAAC;IAED;;;;OAIG;IACc,aAAO,GAAxB;QACE,OAAO,IAAI,CAAC,KAAkB,CAAA;IAChC,CAAC;IAED;;;;;OAKG;IACc,mBAAa,GAA9B,UAAgC,UAAkB;QAChD,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC,MAAM,CAAC,UAAU,CAAwB,CAAA;IACjE,CAAC;IACH,YAAC;AAAD,CAAC,AAhYD,CAAmC,SAAS,GAgY3C"} \ No newline at end of file diff --git a/lib/model/ModelConf.d.ts b/lib/model/ModelConf.d.ts index 7c4cd4bb..761b89a2 100644 --- a/lib/model/ModelConf.d.ts +++ b/lib/model/ModelConf.d.ts @@ -1,5 +1,5 @@ export interface JsonModelConf { - baseUrl?: string; + baseURL?: string; endpointPath: string; methods?: MethodConf[]; } @@ -20,7 +20,7 @@ export default class ModelConf { /** * The host/domain of api server */ - baseUrl: string | undefined; + baseURL: string | undefined; /** * The endpoint of model entity */ @@ -107,7 +107,7 @@ export declare class HttpConf { bindPathParams(params: PathParam[]): string; } export declare const defaultConf: { - "baseUrl": string; + "baseURL": string; "endpointPath": string; "methods": ({ "name": string; diff --git a/lib/model/ModelConf.js b/lib/model/ModelConf.js index 5046f0ea..4f3583f1 100644 --- a/lib/model/ModelConf.js +++ b/lib/model/ModelConf.js @@ -26,7 +26,7 @@ var ModelConf = /** @class */ (function () { /** * The host/domain of api server */ - this.baseUrl = ''; + this.baseURL = ''; /** * The endpoint of model entity */ @@ -36,7 +36,7 @@ var ModelConf = /** @class */ (function () { */ this.methods = new Map(); if (conf) { - this.baseUrl = conf.baseUrl; + this.baseURL = conf.baseURL; this.endpointPath = conf.endpointPath; if (conf.methods) { conf.methods.forEach(function (method) { @@ -51,8 +51,8 @@ var ModelConf = /** @class */ (function () { */ ModelConf.prototype.extend = function (conf) { var _this = this; - if (conf.baseUrl) { - this.baseUrl = conf.baseUrl; + if (conf.baseURL) { + this.baseURL = conf.baseURL; } if (conf.endpointPath) { this.endpointPath = conf.endpointPath; @@ -153,7 +153,7 @@ var HttpConf = /** @class */ (function () { }()); export { HttpConf }; export var defaultConf = { - "baseUrl": "http://localhost:3000", + "baseURL": "http://localhost:3000", "endpointPath": "/{self}", "methods": [ { diff --git a/lib/options/Options.d.ts b/lib/options/Options.d.ts index 1c5af88c..cc7f5eaa 100644 --- a/lib/options/Options.d.ts +++ b/lib/options/Options.d.ts @@ -1,12 +1,20 @@ -export interface ResourcesOptions { - baseUrl?: string; +import { HttpConf, InterceptorRequestClosure, InterceptorResponseClosure } from '../http/Http'; +interface InterceptosClosures { + requestInterceptor?: InterceptorRequestClosure; + responseInterceptor?: InterceptorResponseClosure; } export interface Options { namespace?: string; - resources?: ResourcesOptions; + http?: HttpConf & InterceptosClosures; } export default class ModuleOptions implements Options { static namespace: string; - static resources: ResourcesOptions; + static http: HttpConf & InterceptosClosures; static register(options?: Options): void; + private static confAxiosModule; + static check(): void; + static checkBaseUrl(): void; + static checkTimeout(): void; + static checkHeader(): void; } +export {}; diff --git a/lib/options/Options.js b/lib/options/Options.js index 1c12eda1..96c62aa2 100644 --- a/lib/options/Options.js +++ b/lib/options/Options.js @@ -1,3 +1,4 @@ +import Http from '../http/Http'; var ModuleOptions = /** @class */ (function () { function ModuleOptions() { } @@ -6,14 +7,48 @@ var ModuleOptions = /** @class */ (function () { if (options.namespace) { this.namespace = options.namespace; } - if (options.resources) { - this.resources = options.resources; + if (options.http) { + this.http = options.http; } + this.check(); + this.confAxiosModule(); }; - ModuleOptions.namespace = 'entities'; - ModuleOptions.resources = { - baseUrl: '' + ModuleOptions.confAxiosModule = function () { + Http.conf(this.http); + if (this.http.requestInterceptor) { + Http.registerRequestInterceptor(this.http.requestInterceptor); + } + if (this.http.responseInterceptor) { + Http.registerResponseInterceptor(this.http.responseInterceptor); + } + }; + ModuleOptions.check = function () { + if (!this.http) { + throw new Error('Vuex orm resources: missing default http conf'); + } + this.checkBaseUrl(); + this.checkHeader(); + this.checkTimeout(); + }; + ModuleOptions.checkBaseUrl = function () { + if (!this.http.baseURL) { + throw new Error('Vuex orm resources: missing default http baseURL conf'); + } }; + ModuleOptions.checkTimeout = function () { + if (!this.http.timeout) { + throw new Error('Vuex orm resources: missing default http timeout conf'); + } + }; + ModuleOptions.checkHeader = function () { + if (!this.http.headers) { + throw new Error('Vuex orm resources: missing default http headers conf'); + } + if (!this.http.headers['Content-Type']) { + throw new Error('Vuex orm resources: missing default http Content-Type headers conf'); + } + }; + ModuleOptions.namespace = 'entities'; return ModuleOptions; }()); export default ModuleOptions; diff --git a/lib/options/Options.js.map b/lib/options/Options.js.map index edc4c61a..67ccc06f 100644 --- a/lib/options/Options.js.map +++ b/lib/options/Options.js.map @@ -1 +1 @@ -{"version":3,"file":"Options.js","sourceRoot":"","sources":["../../src/options/Options.ts"],"names":[],"mappings":"AASA;IAAA;IAeA,CAAC;IATe,sBAAQ,GAAtB,UAAwB,OAAqB;QAArB,wBAAA,EAAA,YAAqB;QAC3C,IAAI,OAAO,CAAC,SAAS,EAAE;YACrB,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAA;SACnC;QACD,IAAI,OAAO,CAAC,SAAS,EAAE;YACrB,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAA;SACnC;IACH,CAAC;IAZa,uBAAS,GAAW,UAAU,CAAA;IAC9B,uBAAS,GAAqB;QAC1C,OAAO,EAAE,EAAE;KACZ,CAAA;IAWH,oBAAC;CAAA,AAfD,IAeC;eAfoB,aAAa"} \ No newline at end of file +{"version":3,"file":"Options.js","sourceRoot":"","sources":["../../src/options/Options.ts"],"names":[],"mappings":"AAAA,OAAO,IAIN,MAAM,cAAc,CAAC;AAYtB;IAAA;IAwDA,CAAC;IApDe,sBAAQ,GAAtB,UAAwB,OAAqB;QAArB,wBAAA,EAAA,YAAqB;QAC3C,IAAI,OAAO,CAAC,SAAS,EAAE;YACrB,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAA;SACnC;QACD,IAAI,OAAO,CAAC,IAAI,EAAE;YAChB,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAA;SACzB;QACD,IAAI,CAAC,KAAK,EAAE,CAAA;QACZ,IAAI,CAAC,eAAe,EAAE,CAAA;IACxB,CAAC;IAEc,6BAAe,GAA9B;QAEE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QAEpB,IAAG,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE;YAC/B,IAAI,CAAC,0BAA0B,CAAC,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAA;SAC9D;QAED,IAAG,IAAI,CAAC,IAAI,CAAC,mBAAmB,EAAE;YAChC,IAAI,CAAC,2BAA2B,CAAC,IAAI,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAA;SAChE;IAEH,CAAC;IACa,mBAAK,GAAnB;QACE,IAAG,CAAC,IAAI,CAAC,IAAI,EAAE;YACb,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;SAClE;QACD,IAAI,CAAC,YAAY,EAAE,CAAA;QACnB,IAAI,CAAC,WAAW,EAAE,CAAA;QAClB,IAAI,CAAC,YAAY,EAAE,CAAA;IACrB,CAAC;IACa,0BAAY,GAA1B;QACE,IAAG,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE;YACrB,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;SAC1E;IACH,CAAC;IACa,0BAAY,GAA1B;QACE,IAAG,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE;YACrB,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;SAC1E;IACH,CAAC;IACa,yBAAW,GAAzB;QACE,IAAG,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE;YACrB,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;SAC1E;QAED,IAAG,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE;YACrC,MAAM,IAAI,KAAK,CAAC,oEAAoE,CAAC,CAAC;SACvF;IACH,CAAC;IArDa,uBAAS,GAAW,UAAU,CAAA;IAuD9C,oBAAC;CAAA,AAxDD,IAwDC;eAxDoB,aAAa"} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index d256ba5b..ba775e1c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -551,6 +551,16 @@ "dev": true, "optional": true }, + "axios": { + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.18.0.tgz", + "integrity": "sha1-MtU+SFHv3AoRmTts0AB4nXDAUQI=", + "dev": true, + "requires": { + "follow-redirects": "1.5.1", + "is-buffer": "1.1.6" + } + }, "babel-code-frame": { "version": "6.26.0", "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", @@ -1561,6 +1571,12 @@ } } }, + "buffer-es6": { + "version": "4.9.3", + "resolved": "https://registry.npmjs.org/buffer-es6/-/buffer-es6-4.9.3.tgz", + "integrity": "sha1-8mNHuC33b9N+GLy1KIxJcM/VxAQ=", + "dev": true + }, "buffer-from": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.0.tgz", @@ -2567,6 +2583,26 @@ } } }, + "follow-redirects": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.1.tgz", + "integrity": "sha512-v9GI1hpaqq1ZZR6pBD1+kI7O24PhDvNGNodjS3MdcEqyrahCp8zbtpv+2B/krUnSmUH80lbAS7MrdeK5IylgKg==", + "dev": true, + "requires": { + "debug": "3.1.0" + }, + "dependencies": { + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + } + } + }, "for-in": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", @@ -7995,6 +8031,12 @@ "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=", "dev": true }, + "process-es6": { + "version": "0.11.6", + "resolved": "https://registry.npmjs.org/process-es6/-/process-es6-0.11.6.tgz", + "integrity": "sha1-xrs4n5qVH4K9TrFpYAEFvS/5x3g=", + "dev": true + }, "process-nextick-args": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", @@ -8414,6 +8456,20 @@ "rollup-pluginutils": "2.3.0" } }, + "rollup-plugin-node-globals": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/rollup-plugin-node-globals/-/rollup-plugin-node-globals-1.2.1.tgz", + "integrity": "sha512-PZgkJkVLWZRdwx33GaAeD92UjmvCM7kM9i/8wgoe9hN901RrjVs8eVjg5DzQ+2kGZSiqyx0aiIunLnOOCWshWQ==", + "dev": true, + "requires": { + "acorn": "5.7.1", + "buffer-es6": "4.9.3", + "estree-walker": "0.5.2", + "magic-string": "0.22.5", + "process-es6": "0.11.6", + "rollup-pluginutils": "2.3.0" + } + }, "rollup-plugin-node-resolve": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/rollup-plugin-node-resolve/-/rollup-plugin-node-resolve-3.3.0.tgz", diff --git a/package.json b/package.json index 2dd2ea20..142c85f3 100644 --- a/package.json +++ b/package.json @@ -41,6 +41,7 @@ }, "devDependencies": { "@types/sinon": "^4.3.1", + "axios": "^0.18.0", "babel-core": "^6.26.0", "babel-loader": "^7.1.4", "babel-plugin-transform-runtime": "^6.23.0", @@ -58,6 +59,7 @@ "nyc": "^11.6.0", "rollup": "^0.57.1", "rollup-plugin-commonjs": "^9.1.0", + "rollup-plugin-node-globals": "^1.2.1", "rollup-plugin-node-resolve": "^3.3.0", "sinon": "^4.5.0", "ts-loader": "^4.2.0", diff --git a/src/http/Http.ts b/src/http/Http.ts index 2f2611d3..20a516a7 100644 --- a/src/http/Http.ts +++ b/src/http/Http.ts @@ -1,55 +1,81 @@ +import Axios, { AxiosRequestConfig, AxiosPromise, AxiosResponse } from 'axios' + +export type InterceptorRequestClosure = + (record: AxiosRequestConfig) => AxiosRequestConfig | Promise + +export type InterceptorResponseClosure = + (record: AxiosResponse) => AxiosResponse | Promise> + +export type HttpConf = AxiosRequestConfig; + export default class Http { - // Default options are marked with * - public static defaultOptions: RequestInit = { - method: '', - cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached - credentials: 'same-origin', // include, same-origin, *omit - headers: { - 'user-agent': 'Mozilla/4.0 MDN Example', - 'content-type': 'application/json' - }, - mode: 'cors', // no-cors, cors, *same-origin - redirect: 'follow', // *manual, follow, error - referrer: 'no-referrer' // *client, no-referrer - } - - public static request ( - url: string, - _query: {}, - _method: string, - _body = {}, - _headers = {}, - options = {} - ): Promise { - - const _options = { ...this.defaultOptions, ...options } - _options.method = _method - if (Object.keys(_body).length) { - _options.body = JSON.stringify(_body) - } - return fetch(url, _options as RequestInit) - .then(response => { - if (!response.ok) { - return Promise.reject(new Error('http request failed')) - } else { - return Promise.resolve(response.json()) - } - }) // parses response to JSON - } - - public static get (url: string, params = {}, headers = {}, options = {}): Promise { - return this.request(url, params, 'GET', {}, headers, options) - } - - public static post (url: string, payload = {}, headers = {}, options = {}): Promise { - return this.request(url, {}, 'POST', payload, headers, options) - } - - public static put (url: string, payload = {}, headers = {}, options = {}): Promise { - return this.request(url, {}, 'PUT', payload, headers, options) - } - - public static delete (url: string, payload = {}, headers = {}, options = {}): Promise { - return this.request(url, {}, 'DELETE', payload, headers, options) + + public static defaultConf: AxiosRequestConfig + + public static conf(config: AxiosRequestConfig) { + this.defaultConf = config + } + + public static registerRequestInterceptor(requestInterceptor: InterceptorRequestClosure) { + Axios.interceptors.request.use(requestInterceptor) + } + + public static registerResponseInterceptor(responseInterceptor: InterceptorResponseClosure) { + Axios.interceptors.response.use(responseInterceptor) + } + + private static mergeConf(config: AxiosRequestConfig) { + return { ...this.defaultConf, ...config } + } + + public static head ( + url: string, + config: AxiosRequestConfig = this.defaultConf + ): AxiosPromise { + this.mergeConf(config) + return Axios.head(url, config); + } + + public static get ( + url: string, + config: AxiosRequestConfig = this.defaultConf + ): AxiosPromise { + this.mergeConf(config) + return Axios.get(url, config); + } + + public static post ( + url: string, + data = {}, + config: AxiosRequestConfig = this.defaultConf + ): AxiosPromise { + this.mergeConf(config) + return Axios.post(url, data, config); + } + + public static patch ( + url: string, + data = {}, + config: AxiosRequestConfig = this.defaultConf + ): AxiosPromise { + this.mergeConf(config) + return Axios.patch(url, data, config); + } + + public static put ( + url: string, + data = {}, + config: AxiosRequestConfig = this.defaultConf + ): AxiosPromise { + this.mergeConf(config) + return Axios.put(url, data, config); + } + + public static delete ( + url: string, + config: AxiosRequestConfig = this.defaultConf + ): AxiosPromise { + this.mergeConf(config) + return Axios.delete(url, config); } } diff --git a/src/model/Model.ts b/src/model/Model.ts index 9b3d07b3..bd1ba139 100644 --- a/src/model/Model.ts +++ b/src/model/Model.ts @@ -1,6 +1,5 @@ import BaseModel from './BaseModel' -import Http from '../http/Http' -import ModuleOptions from '../options/Options' +import Http, { HttpConf }from '../http/Http' import { Record } from '../data' import Query, { UpdateClosure } from '../query/Query' import EntityCollection from '../query/EntityCollection' @@ -9,15 +8,15 @@ import ModelConf, { JsonModelConf, defaultConf, MethodConf, - HttpMethod, PathParam } from '../model/ModelConf' import { replaceAll } from '../support/Utils' export type UpdateReturn = Item | Collection | EntityCollection +export type MethodConfParameter = MethodConf & HttpConf export default class Model extends BaseModel { - public static _conf: ModelConf | JsonModelConf + public static _conf: ModelConf | (JsonModelConf & HttpConf) /** * Configure a model with default conf and extend or override @@ -77,10 +76,14 @@ export default class Model extends BaseModel { * @async * @return {Promise} fetched data */ - public static async fetch (conf: MethodConf = this.getMethodConf('fetch')): Promise { + public static async fetch (conf: MethodConfParameter = this.getMethodConf('fetch')): Promise { const _conf = this.checkMethodConf('fetch', conf) const url = this.getUrl(_conf) - const data = await Http[((_conf.http as any) as any).method as HttpMethod](url) + /* const data = await Http[((_conf.http as any) as any).method as HttpMethod](url) + .catch((err: Error) => { console.log(err) }) || [] */ + + const method = (_conf.http as any).method as string + const data = await Http[method](url) .catch((err: Error) => { console.log(err) }) || [] if (_conf.localSync) { @@ -96,7 +99,7 @@ export default class Model extends BaseModel { * @async * @return {Promise} list of results */ - public static async find (conf: MethodConf = this.getMethodConf('find')): Promise { + public static async find (conf: MethodConfParameter = this.getMethodConf('find')): Promise { const _conf = this.checkMethodConf('find', conf) let data if (_conf.remote) { @@ -119,7 +122,7 @@ export default class Model extends BaseModel { */ public static async findById ( id: number, - conf: MethodConf = this.getMethodConf('findById') + conf: MethodConfParameter = this.getMethodConf('findById') ): Promise { const _conf = this.checkMethodConf('findById', conf) let data @@ -145,11 +148,12 @@ export default class Model extends BaseModel { */ public static async fetchById ( id: number, - conf: MethodConf = this.getMethodConf('fetchById') + conf: MethodConfParameter = this.getMethodConf('fetchById') ): Promise { const _conf = this.checkMethodConf('fetchById', conf) const url = this.getUrl(_conf, new PathParam('id', id.toString())) - const data = await Http[(_conf.http as any).method as HttpMethod](url) + const method = (_conf.http as any).method as string + const data = await Http[method](url) .catch((err: Error) => { console.log(err); }) || [] if(_conf.localSync) { @@ -168,14 +172,15 @@ export default class Model extends BaseModel { */ public static async exist ( id: number, - conf: MethodConf = this.getMethodConf('exist') + conf: MethodConfParameter = this.getMethodConf('exist') ): Promise { const _conf = this.checkMethodConf('exist', conf) let data if (_conf.remote) { const url = this.getUrl(_conf, new PathParam('id', id.toString())) - data = await Http[(_conf.http as any).method as HttpMethod](url) + const method = (_conf.http as any).method as string + data = await Http[method](url) .catch((err: Error) => { console.log(err); }) || [] } else { @@ -190,12 +195,13 @@ export default class Model extends BaseModel { * @static * @return {Promise} number of element */ - public static async count (conf: MethodConf = this.getMethodConf('count')): Promise { + public static async count (conf: MethodConfParameter = this.getMethodConf('count')): Promise { const _conf = this.checkMethodConf('count', conf) let data if (_conf.remote) { - data = await Http[(_conf.http as any).method as HttpMethod](this.getUrl(_conf)) + const method = (_conf.http as any).method as string + data = await Http[method](this.getUrl(_conf)) .catch((err: Error) => { console.log(err); }) || [] } else { @@ -213,13 +219,14 @@ export default class Model extends BaseModel { */ public static async create ( data: Record | Record[], - conf: MethodConf = this.getMethodConf('create') + conf: MethodConfParameter = this.getMethodConf('create') ): Promise { const _conf = this.checkMethodConf('create', conf) let dataOutput if (_conf.remote) { - dataOutput = await Http[(_conf.http as any).method as HttpMethod](this.getUrl(_conf), data) + const method = (_conf.http as any).method as string + dataOutput = await Http[method](this.getUrl(_conf), data) .catch((err: Error) => { console.log(err); }) || [] if(_conf.localSync) { @@ -245,14 +252,15 @@ export default class Model extends BaseModel { public static async update ( id: number, data: Record | Record[] | UpdateClosure, - conf: MethodConf = this.getMethodConf('update') + conf: MethodConfParameter = this.getMethodConf('update') ): Promise { const _conf = this.checkMethodConf('update', conf) let dataOutput if (_conf.remote) { const url = this.getUrl(_conf, new PathParam('id', id.toString())) - dataOutput = await Http[(_conf.http as any).method as HttpMethod](url, data) + const method = (_conf.http as any).method as string + dataOutput = await Http[method](url, data) .catch((err: Error) => { console.log(err); }) || [] if(_conf.localSync && dataOutput) { @@ -281,14 +289,15 @@ export default class Model extends BaseModel { */ public static async deleteById ( id: number, - conf: MethodConf = this.getMethodConf('deleteById') + conf: MethodConfParameter = this.getMethodConf('deleteById') ): Promise { const _conf = this.checkMethodConf('deleteById', conf) if (_conf.remote) { const url = this.getUrl(_conf, new PathParam('id', id.toString())) - const dataOutput = await Http[(_conf.http as any).method as HttpMethod](url) + const method = (_conf.http as any).method as string + const dataOutput = await Http[method](url) .catch((err: Error) => { console.log(err); }) || [] if(_conf.localSync && dataOutput) { @@ -306,12 +315,13 @@ export default class Model extends BaseModel { * @param {MethodConf} conf a method's conf * @static */ - public static async delete (conf: MethodConf = this.getMethodConf('deleteById')): Promise { + public static async delete (conf: MethodConfParameter = this.getMethodConf('deleteById')): Promise { const _conf = this.checkMethodConf('deleteById', conf) if (_conf.remote) { - const dataOutput = await Http[(_conf.http as any).method as HttpMethod](this.getUrl(_conf)) + const method = (_conf.http as any).method as string + const dataOutput = await Http[method](this.getUrl(_conf)) .catch((err: Error) => { console.log(err); }) || [] if(_conf.localSync && dataOutput) { @@ -340,14 +350,11 @@ export default class Model extends BaseModel { * @static * @return {string} api's url */ - protected static getUrl (conf: MethodConf, ...pathParams: PathParam[]): string { - let baseUrl = this._conf.baseUrl + protected static getUrl (conf: MethodConfParameter, ...pathParams: PathParam[]): string { const methodPath = pathParams.length ? (conf.http as any).bindPathParams(pathParams) : (conf.http as any).path - if(ModuleOptions.resources.baseUrl) { - baseUrl = ModuleOptions.resources.baseUrl - } - return baseUrl + this._conf.endpointPath + methodPath + + return this._conf.endpointPath + methodPath } /** @@ -361,7 +368,7 @@ export default class Model extends BaseModel { * @return {MethodConf} the new method's configuration * @throws Error */ - protected static checkMethodConf (methodName: string, conf: MethodConf): MethodConf { + protected static checkMethodConf (methodName: string, conf: MethodConfParameter): MethodConf { const _conf = this._conf as ModelConf let _method = _conf.method(methodName) if (conf && _method) { @@ -389,7 +396,7 @@ export default class Model extends BaseModel { * @static * @return {MethodConf} */ - protected static getMethodConf (methodName: string): MethodConf { - return this.getConf().method(methodName) as MethodConf + protected static getMethodConf (methodName: string): MethodConfParameter { + return this.getConf().method(methodName) as MethodConfParameter } } diff --git a/src/model/ModelConf.ts b/src/model/ModelConf.ts index 499cfe87..ff155d90 100644 --- a/src/model/ModelConf.ts +++ b/src/model/ModelConf.ts @@ -1,6 +1,6 @@ import { replaceAll, clone } from '../support/Utils' export interface JsonModelConf { - baseUrl?: string, + baseURL?: string, endpointPath: string, methods?: MethodConf[] } @@ -27,7 +27,7 @@ export default class ModelConf { /** * The host/domain of api server */ - public baseUrl: string | undefined = '' + public baseURL: string | undefined = '' /** * The endpoint of model entity */ @@ -43,7 +43,7 @@ export default class ModelConf { */ constructor (conf?: JsonModelConf) { if (conf) { - this.baseUrl = conf.baseUrl + this.baseURL = conf.baseURL this.endpointPath = conf.endpointPath if(conf.methods) { conf.methods.forEach((method: MethodConf) => { @@ -58,8 +58,8 @@ export default class ModelConf { * @param {JsonModelConf} conf a json model's conf */ public extend (conf: JsonModelConf): void { - if (conf.baseUrl) { - this.baseUrl = conf.baseUrl + if (conf.baseURL) { + this.baseURL = conf.baseURL } if (conf.endpointPath) { this.endpointPath = conf.endpointPath @@ -207,7 +207,7 @@ export class HttpConf { } export const defaultConf = { - "baseUrl": "http://localhost:3000", + "baseURL": "http://localhost:3000", "endpointPath": "/{self}", "methods": [ { diff --git a/src/options/Options.ts b/src/options/Options.ts index 0217a501..c61845f9 100644 --- a/src/options/Options.ts +++ b/src/options/Options.ts @@ -1,24 +1,72 @@ -export interface ResourcesOptions { - baseUrl?: string +import Http, { + HttpConf, + InterceptorRequestClosure, + InterceptorResponseClosure +} from '../http/Http'; + +interface InterceptosClosures { + requestInterceptor?: InterceptorRequestClosure; + responseInterceptor?: InterceptorResponseClosure } export interface Options { namespace?: string - resources?: ResourcesOptions + http?: HttpConf & InterceptosClosures } export default class ModuleOptions implements Options { public static namespace: string = 'entities' - public static resources: ResourcesOptions = { - baseUrl: '' - } + public static http: HttpConf & InterceptosClosures public static register (options: Options = {}) { if (options.namespace) { this.namespace = options.namespace } - if (options.resources) { - this.resources = options.resources + if (options.http) { + this.http = options.http + } + this.check() + this.confAxiosModule() + } + + private static confAxiosModule() { + + Http.conf(this.http) + + if(this.http.requestInterceptor) { + Http.registerRequestInterceptor(this.http.requestInterceptor) + } + + if(this.http.responseInterceptor) { + Http.registerResponseInterceptor(this.http.responseInterceptor) + } + + } + public static check() { + if(!this.http) { + throw new Error('Vuex orm resources: missing default http conf'); + } + this.checkBaseUrl() + this.checkHeader() + this.checkTimeout() + } + public static checkBaseUrl() { + if(!this.http.baseURL) { + throw new Error('Vuex orm resources: missing default http baseURL conf'); + } + } + public static checkTimeout() { + if(!this.http.timeout) { + throw new Error('Vuex orm resources: missing default http timeout conf'); + } + } + public static checkHeader() { + if(!this.http.headers) { + throw new Error('Vuex orm resources: missing default http headers conf'); + } + + if(!this.http.headers['Content-Type']) { + throw new Error('Vuex orm resources: missing default http Content-Type headers conf'); } }