diff --git a/.gitignore b/.gitignore index e499a792..e97fec2b 100644 --- a/.gitignore +++ b/.gitignore @@ -28,8 +28,6 @@ jsconfig.json coverage/ doc/ node_modules/ -dist/*.js -dist/*.map typings yarn.lock -package-lock.json \ No newline at end of file +package-lock.json diff --git a/AUTHORS b/AUTHORS index e432aff9..442e3fdc 100644 --- a/AUTHORS +++ b/AUTHORS @@ -17,6 +17,7 @@ Jeremy TRUFIER Ken Børge Viktil Kent C. Dodds Kurt Van Delden +lumimies Matt Lewis Matt Winkler Matthew Overall diff --git a/dist/js-data.es2015.js b/dist/js-data.es2015.js new file mode 100644 index 00000000..e2a69816 --- /dev/null +++ b/dist/js-data.es2015.js @@ -0,0 +1,14513 @@ +/*! +* js-data +* @version 3.0.2 - Homepage +* @author js-data project authors +* @copyright (c) 2014-2016 js-data project authors +* @license MIT +* +* @overview js-data is a framework-agnostic, datastore-agnostic ORM/ODM for Node.js and the Browser. +*/ +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; +} : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; +}; + + + + + + + + + + + + + + + + + + + +var defineProperty = function (obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +}; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +var toConsumableArray = function (arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } else { + return Array.from(arr); + } +}; + +/** + * Utility methods used by JSData. + * + * @example + * import { utils } from 'js-data'; + * console.log(utils.isString('foo')); // true + * + * @namespace utils + * @type {Object} + */ + +var DOMAIN = 'utils'; + +var INFINITY = 1 / 0; +var MAX_INTEGER = 1.7976931348623157e+308; +var BOOL_TAG = '[object Boolean]'; +var DATE_TAG = '[object Date]'; +var FUNC_TAG = '[object Function]'; +var NUMBER_TAG = '[object Number]'; +var OBJECT_TAG = '[object Object]'; +var REGEXP_TAG = '[object RegExp]'; +var STRING_TAG = '[object String]'; +var objToString = Object.prototype.toString; +var PATH = /^(.+)\.(.+)$/; + +var ERRORS = { + '400': function _() { + return 'expected: ' + arguments[0] + ', found: ' + (arguments[2] ? arguments[1] : _typeof(arguments[1])); + }, + '404': function _() { + return arguments[0] + ' not found'; + } +}; + +var toInteger = function toInteger(value) { + if (!value) { + return 0; + } + // Coerce to number + value = +value; + if (value === INFINITY || value === -INFINITY) { + var sign = value < 0 ? -1 : 1; + return sign * MAX_INTEGER; + } + var remainder = value % 1; + return value === value ? remainder ? value - remainder : value : 0; // eslint-disable-line +}; + +var toStr = function toStr(value) { + return objToString.call(value); +}; + +var isPlainObject = function isPlainObject(value) { + return !!value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value.constructor === Object; +}; + +var mkdirP = function mkdirP(object, path) { + if (!path) { + return object; + } + var parts = path.split('.'); + parts.forEach(function (key) { + if (!object[key]) { + object[key] = {}; + } + object = object[key]; + }); + return object; +}; + +var utils = { + /** + * Reference to the Promise constructor used by JSData. Defaults to + * `window.Promise` or `global.Promise`. + * + * @example Make JSData use a different `Promise` constructor + * import Promise from 'bluebird'; + * import { utils } from 'js-data'; + * utils.Promise = Promise; + * + * @name utils.Promise + * @since 3.0.0 + * @type {Function} + */ + Promise: Promise, + + /** + * Shallow copy properties that meet the following criteria from `src` to + * `dest`: + * + * - own enumerable + * - not a function + * - does not start with "_" + * + * @method utils._ + * @param {object} dest Destination object. + * @param {object} src Source object. + * @private + * @since 3.0.0 + */ + _: function _(dest, src) { + utils.forOwn(src, function (value, key) { + if (key && dest[key] === undefined && !utils.isFunction(value) && key.indexOf('_') !== 0) { + dest[key] = value; + } + }); + }, + + + /** + * Recursively iterates over relations found in `opts.with`. + * + * @method utils._forRelation + * @param {object} opts Configuration options. + * @param {Relation} def Relation definition. + * @param {Function} fn Callback function. + * @param {*} [thisArg] Execution context for the callback function. + * @private + * @since 3.0.0 + */ + _forRelation: function _forRelation(opts, def, fn, thisArg) { + var relationName = def.relation; + var containedName = null; + var index = void 0; + opts || (opts = {}); + opts.with || (opts.with = []); + + if ((index = utils._getIndex(opts.with, relationName)) >= 0) { + containedName = relationName; + } else if ((index = utils._getIndex(opts.with, def.localField)) >= 0) { + containedName = def.localField; + } + + if (opts.withAll) { + fn.call(thisArg, def, {}); + return; + } else if (!containedName) { + return; + } + var optsCopy = {}; + utils.fillIn(optsCopy, def.getRelation()); + utils.fillIn(optsCopy, opts); + optsCopy.with = opts.with.slice(); + optsCopy._activeWith = optsCopy.with.splice(index, 1)[0]; + optsCopy.with.forEach(function (relation, i) { + if (relation && relation.indexOf(containedName) === 0 && relation.length >= containedName.length && relation[containedName.length] === '.') { + optsCopy.with[i] = relation.substr(containedName.length + 1); + } else { + optsCopy.with[i] = ''; + } + }); + fn.call(thisArg, def, optsCopy); + }, + + + /** + * Find the index of a relation in the given list + * + * @method utils._getIndex + * @param {string[]} list List to search. + * @param {string} relation Relation to find. + * @private + * @returns {number} + */ + _getIndex: function _getIndex(list, relation) { + var index = -1; + list.forEach(function (_relation, i) { + if (_relation === relation) { + index = i; + return false; + } else if (utils.isObject(_relation)) { + if (_relation.relation === relation) { + index = i; + return false; + } + } + }); + return index; + }, + + + /** + * Define hidden (non-enumerable), writable properties on `target` from the + * provided `props`. + * + * @example + * import { utils } from 'js-data'; + * function Cat () {} + * utils.addHiddenPropsToTarget(Cat.prototype, { + * say () { + * console.log('meow'); + * } + * }); + * const cat = new Cat(); + * cat.say(); // "meow" + * + * @method utils.addHiddenPropsToTarget + * @param {object} target That to which `props` should be added. + * @param {object} props Properties to be added to `target`. + * @since 3.0.0 + */ + addHiddenPropsToTarget: function addHiddenPropsToTarget(target, props) { + var map = {}; + Object.keys(props).forEach(function (propName) { + var descriptor = Object.getOwnPropertyDescriptor(props, propName); + + descriptor.enumerable = false; + map[propName] = descriptor; + }); + Object.defineProperties(target, map); + }, + + + /** + * Return whether the two objects are deeply different. + * + * @example + * import { utils } from 'js-data'; + * utils.areDifferent({}, {}); // false + * utils.areDifferent({ a: 1 }, { a: 1 }); // false + * utils.areDifferent({ foo: 'bar' }, {}); // true + * + * @method utils.areDifferent + * @param {object} a Base object. + * @param {object} b Comparison object. + * @param {object} [opts] Configuration options. + * @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function. + * @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore. + * @returns {boolean} Whether the two objects are deeply different. + * @see utils.diffObjects + * @since 3.0.0 + */ + areDifferent: function areDifferent(newObject, oldObject, opts) { + opts || (opts = {}); + var diff = utils.diffObjects(newObject, oldObject, opts); + var diffCount = Object.keys(diff.added).length + Object.keys(diff.removed).length + Object.keys(diff.changed).length; + return diffCount > 0; + }, + + + /** + * Verified that the given constructor is being invoked via `new`, as opposed + * to just being called like a normal function. + * + * @example + * import { utils } from 'js-data'; + * function Cat () { + * utils.classCallCheck(this, Cat); + * } + * const cat = new Cat(); // this is ok + * Cat(); // this throws an error + * + * @method utils.classCallCheck + * @param {*} instance Instance that is being constructed. + * @param {Constructor} ctor Constructor function used to construct the + * instance. + * @since 3.0.0 + * @throws {Error} Throws an error if the constructor is being improperly + * invoked. + */ + classCallCheck: function classCallCheck$$1(instance, ctor) { + if (!(instance instanceof ctor)) { + throw utils.err('' + ctor.name)(500, 'Cannot call a class as a function'); + } + }, + + + /** + * Deep copy a value. + * + * @example + * import { utils } from 'js-data'; + * const a = { foo: { bar: 'baz' } }; + * const b = utils.copy(a); + * a === b; // false + * utils.areDifferent(a, b); // false + * + * @param {*} from Value to deep copy. + * @param {*} [to] Destination object for the copy operation. + * @param {*} [stackFrom] For internal use. + * @param {*} [stackTo] For internal use. + * @param {string[]|RegExp[]} [blacklist] List of strings or RegExp of + * properties to skip. + * @param {boolean} [plain] Whether to make a plain copy (don't try to use + * original prototype). + * @returns {*} Deep copy of `from`. + * @since 3.0.0 + */ + copy: function copy(from, to, stackFrom, stackTo, blacklist, plain) { + if (!to) { + to = from; + if (from) { + if (utils.isArray(from)) { + to = utils.copy(from, [], stackFrom, stackTo, blacklist, plain); + } else if (utils.isDate(from)) { + to = new Date(from.getTime()); + } else if (utils.isRegExp(from)) { + to = new RegExp(from.source, from.toString().match(/[^/]*$/)[0]); + to.lastIndex = from.lastIndex; + } else if (utils.isObject(from)) { + if (plain) { + to = utils.copy(from, {}, stackFrom, stackTo, blacklist, plain); + } else { + to = utils.copy(from, Object.create(Object.getPrototypeOf(from)), stackFrom, stackTo, blacklist, plain); + } + } + } + } else { + if (from === to) { + throw utils.err(DOMAIN + '.copy')(500, 'Cannot copy! Source and destination are identical.'); + } + + stackFrom = stackFrom || []; + stackTo = stackTo || []; + + if (utils.isObject(from)) { + var index = stackFrom.indexOf(from); + if (index !== -1) { + return stackTo[index]; + } + + stackFrom.push(from); + stackTo.push(to); + } + + var result = void 0; + if (utils.isArray(from)) { + var i = void 0; + to.length = 0; + for (i = 0; i < from.length; i++) { + result = utils.copy(from[i], null, stackFrom, stackTo, blacklist, plain); + if (utils.isObject(from[i])) { + stackFrom.push(from[i]); + stackTo.push(result); + } + to.push(result); + } + } else { + if (utils.isArray(to)) { + to.length = 0; + } else { + utils.forOwn(to, function (value, key) { + delete to[key]; + }); + } + for (var key in from) { + if (from.hasOwnProperty(key)) { + if (utils.isBlacklisted(key, blacklist)) { + continue; + } + result = utils.copy(from[key], null, stackFrom, stackTo, blacklist, plain); + if (utils.isObject(from[key])) { + stackFrom.push(from[key]); + stackTo.push(result); + } + to[key] = result; + } + } + } + } + return to; + }, + + + /** + * Recursively shallow fill in own enumerable properties from `source` to + * `dest`. + * + * @example + * import { utils } from 'js-data'; + * const a = { foo: { bar: 'baz' }, beep: 'boop' }; + * const b = { beep: 'bip' }; + * utils.deepFillIn(b, a); + * console.log(b); // {"foo":{"bar":"baz"},"beep":"bip"} + * + * @method utils.deepFillIn + * @param {object} dest The destination object. + * @param {object} source The source object. + * @see utils.fillIn + * @see utils.deepMixIn + * @since 3.0.0 + */ + deepFillIn: function deepFillIn(dest, source) { + if (source) { + utils.forOwn(source, function (value, key) { + var existing = dest[key]; + if (isPlainObject(value) && isPlainObject(existing)) { + utils.deepFillIn(existing, value); + } else if (!dest.hasOwnProperty(key) || dest[key] === undefined) { + dest[key] = value; + } + }); + } + return dest; + }, + + + /** + * Recursively shallow copy enumerable properties from `source` to `dest`. + * + * @example + * import { utils } from 'js-data'; + * const a = { foo: { bar: 'baz' }, beep: 'boop' }; + * const b = { beep: 'bip' }; + * utils.deepFillIn(b, a); + * console.log(b); // {"foo":{"bar":"baz"},"beep":"boop"} + * + * @method utils.deepMixIn + * @param {object} dest The destination object. + * @param {object} source The source object. + * @see utils.fillIn + * @see utils.deepFillIn + * @since 3.0.0 + */ + deepMixIn: function deepMixIn(dest, source) { + if (source) { + for (var key in source) { + var value = source[key]; + var existing = dest[key]; + if (isPlainObject(value) && isPlainObject(existing)) { + utils.deepMixIn(existing, value); + } else { + dest[key] = value; + } + } + } + return dest; + }, + + + /** + * Return a diff of the base object to the comparison object. + * + * @example + * import { utils } from 'js-data'; + * const oldObject = { foo: 'bar', a: 1234 }; + * const newObject = { beep: 'boop', a: 5678 }; + * const diff = utils.diffObjects(oldObject, newObject); + * console.log(diff.added); // {"beep":"boop"} + * console.log(diff.changed); // {"a":5678} + * console.log(diff.removed); // {"foo":undefined} + * + * @method utils.diffObjects + * @param {object} newObject Comparison object. + * @param {object} oldObject Base object. + * @param {object} [opts] Configuration options. + * @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function. + * @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore. + * @returns {Object} The diff from the base object to the comparison object. + * @see utils.areDifferent + * @since 3.0.0 + */ + diffObjects: function diffObjects(newObject, oldObject, opts) { + opts || (opts = {}); + var equalsFn = opts.equalsFn; + var blacklist = opts.ignore; + var diff = { + added: {}, + changed: {}, + removed: {} + }; + if (!utils.isFunction(equalsFn)) { + equalsFn = utils.deepEqual; + } + + var newKeys = Object.keys(newObject).filter(function (key) { + return !utils.isBlacklisted(key, blacklist); + }); + var oldKeys = Object.keys(oldObject).filter(function (key) { + return !utils.isBlacklisted(key, blacklist); + }); + + // Check for properties that were added or changed + newKeys.forEach(function (key) { + var oldValue = oldObject[key]; + var newValue = newObject[key]; + if (equalsFn(oldValue, newValue)) { + return; + } + if (oldValue === undefined) { + diff.added[key] = newValue; + } else { + diff.changed[key] = newValue; + } + }); + + // Check for properties that were removed + oldKeys.forEach(function (key) { + var oldValue = oldObject[key]; + var newValue = newObject[key]; + if (newValue === undefined && oldValue !== undefined) { + diff.removed[key] = undefined; + } + }); + + return diff; + }, + + + /** + * Return whether the two values are equal according to the `==` operator. + * + * @example + * import { utils } from 'js-data'; + * console.log(utils.equal(1,1)); // true + * console.log(utils.equal(1,'1')); // true + * console.log(utils.equal(93, 66)); // false + * + * @method utils.equal + * @param {*} a First value in the comparison. + * @param {*} b Second value in the comparison. + * @returns {boolean} Whether the two values are equal according to `==`. + * @since 3.0.0 + */ + equal: function equal(a, b) { + return a == b; // eslint-disable-line + }, + + + /** + * Produce a factory function for making Error objects with the provided + * metadata. Used throughout the various js-data components. + * + * @example + * import { utils } from 'js-data'; + * const errorFactory = utils.err('domain', 'target'); + * const error400 = errorFactory(400, 'expected type', 'actual type'); + * console.log(error400); // [Error: [domain:target] expected: expected type, found: string + http://www.js-data.io/v3.0/docs/errors#400] + * @method utils.err + * @param {string} domain Namespace. + * @param {string} target Target. + * @returns {Function} Factory function. + * @since 3.0.0 + */ + err: function err(domain, target) { + return function (code) { + var prefix = '[' + domain + ':' + target + '] '; + var message = ERRORS[code].apply(null, Array.prototype.slice.call(arguments, 1)); + message = '' + prefix + message + '\nhttp://www.js-data.io/v3.0/docs/errors#' + code; + return new Error(message); + }; + }, + + + /** + * Add eventing capabilities into the target object. + * + * @example + * import { utils } from 'js-data'; + * const user = { name: 'John' }; + * utils.eventify(user); + * user.on('foo', () => console.log(arguments)); + * user.emit('foo', 1, 'bar'); // should log to console values (1, "bar") + * + * @method utils.eventify + * @param {object} target Target object. + * @param {Function} [getter] Custom getter for retrieving the object's event + * listeners. + * @param {Function} [setter] Custom setter for setting the object's event + * listeners. + * @since 3.0.0 + */ + eventify: function eventify(target, getter, setter) { + target = target || this; + var _events = {}; + if (!getter && !setter) { + getter = function getter() { + return _events; + }; + setter = function setter(value) { + _events = value; + }; + } + Object.defineProperties(target, { + emit: { + value: function value() { + var events = getter.call(this) || {}; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var type = args.shift(); + var listeners = events[type] || []; + var i = void 0; + for (i = 0; i < listeners.length; i++) { + listeners[i].f.apply(listeners[i].c, args); + } + listeners = events.all || []; + args.unshift(type); + for (i = 0; i < listeners.length; i++) { + listeners[i].f.apply(listeners[i].c, args); + } + } + }, + off: { + value: function value(type, func) { + var events = getter.call(this); + var listeners = events[type]; + if (!listeners) { + setter.call(this, {}); + } else if (func) { + for (var i = 0; i < listeners.length; i++) { + if (listeners[i].f === func) { + listeners.splice(i, 1); + break; + } + } + } else { + listeners.splice(0, listeners.length); + } + } + }, + on: { + value: function value(type, func, thisArg) { + if (!getter.call(this)) { + setter.call(this, {}); + } + var events = getter.call(this); + events[type] = events[type] || []; + events[type].push({ + c: thisArg, + f: func + }); + } + } + }); + }, + + + /** + * Used for sublcassing. Invoke this method in the context of a superclass to + * to produce a subclass based on `props` and `classProps`. + * + * @example + * import { utils } from 'js-data'; + * function Animal () {} + * Animal.extend = utils.extend; + * const Cat = Animal.extend({ + * say () { + * console.log('meow'); + * } + * }); + * const cat = new Cat(); + * cat instanceof Animal; // true + * cat instanceof Cat; // true + * cat.say(); // "meow" + * + * @method utils.extend + * @param {object} props Instance properties for the subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to use as the subclass. + * @param {object} props Static properties for the subclass. + * @returns {Constructor} A new subclass. + * @since 3.0.0 + */ + extend: function extend(props, classProps) { + var superClass = this; + var _subClass = void 0; + + props || (props = {}); + classProps || (classProps = {}); + + if (props.hasOwnProperty('constructor')) { + _subClass = props.constructor; + delete props.constructor; + } else { + _subClass = function subClass() { + utils.classCallCheck(this, _subClass); + + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + superClass.apply(this, args); + }; + } + + // Setup inheritance of instance members + _subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + configurable: true, + enumerable: false, + value: _subClass, + writable: true + } + }); + + var obj = Object; + // Setup inheritance of static members + if (obj.setPrototypeOf) { + obj.setPrototypeOf(_subClass, superClass); + } else if (classProps.strictEs6Class) { + _subClass.__proto__ = superClass; // eslint-disable-line + } else { + utils.forOwn(superClass, function (value, key) { + _subClass[key] = value; + }); + } + if (!_subClass.hasOwnProperty('__super__')) { + Object.defineProperty(_subClass, '__super__', { + configurable: true, + value: superClass + }); + } + + utils.addHiddenPropsToTarget(_subClass.prototype, props); + utils.fillIn(_subClass, classProps); + + return _subClass; + }, + + + /** + * Shallow copy own enumerable properties from `src` to `dest` that are on + * `src` but are missing from `dest. + * + * @example + * import { utils } from 'js-data'; + * const a = { foo: 'bar', beep: 'boop' }; + * const b = { beep: 'bip' }; + * utils.fillIn(b, a); + * console.log(b); // {"foo":"bar","beep":"bip"} + * + * @method utils.fillIn + * @param {object} dest The destination object. + * @param {object} source The source object. + * @see utils.deepFillIn + * @see utils.deepMixIn + * @since 3.0.0 + */ + fillIn: function fillIn(dest, src) { + utils.forOwn(src, function (value, key) { + if (!dest.hasOwnProperty(key) || dest[key] === undefined) { + dest[key] = value; + } + }); + }, + + + /** + * Find the last index of an item in an array according to the given checker function. + * + * @example + * import { utils } from 'js-data'; + * + * const john = { name: 'John', age: 20 }; + * const sara = { name: 'Sara', age: 25 }; + * const dan = { name: 'Dan', age: 20 }; + * const users = [john, sara, dan]; + * + * console.log(utils.findIndex(users, (user) => user.age === 25)); // 1 + * console.log(utils.findIndex(users, (user) => user.age > 19)); // 2 + * console.log(utils.findIndex(users, (user) => user.name === 'John')); // 0 + * console.log(utils.findIndex(users, (user) => user.name === 'Jimmy')); // -1 + * + * @method utils.findIndex + * @param {array} array The array to search. + * @param {Function} fn Checker function. + * @returns {number} Index if found or -1 if not found. + * @since 3.0.0 + */ + findIndex: function findIndex(array, fn) { + var index = -1; + if (!array) { + return index; + } + array.forEach(function (record, i) { + if (fn(record)) { + index = i; + return false; + } + }); + return index; + }, + + + /** + * Recursively iterate over a {@link Mapper}'s relations according to + * `opts.with`. + * + * @method utils.forEachRelation + * @param {Mapper} mapper Mapper. + * @param {object} opts Configuration options. + * @param {Function} fn Callback function. + * @param {*} thisArg Execution context for the callback function. + * @since 3.0.0 + */ + forEachRelation: function forEachRelation(mapper, opts, fn, thisArg) { + var relationList = mapper.relationList || []; + if (!relationList.length) { + return; + } + relationList.forEach(function (def) { + utils._forRelation(opts, def, fn, thisArg); + }); + }, + + + /** + * Iterate over an object's own enumerable properties. + * + * @example + * import { utils } from 'js-data'; + * const a = { b: 1, c: 4 }; + * let sum = 0; + * utils.forOwn(a, function (value, key) { + * sum += value; + * }); + * console.log(sum); // 5 + * + * @method utils.forOwn + * @param {object} object The object whose properties are to be enumerated. + * @param {Function} fn Iteration function. + * @param {object} [thisArg] Content to which to bind `fn`. + * @since 3.0.0 + */ + forOwn: function forOwn(obj, fn, thisArg) { + var keys = Object.keys(obj); + var len = keys.length; + var i = void 0; + for (i = 0; i < len; i++) { + if (fn.call(thisArg, obj[keys[i]], keys[i], obj) === false) { + break; + } + } + }, + + + /** + * Proxy for `JSON.parse`. + * + * @example + * import { utils } from 'js-data'; + * + * const a = utils.fromJson('{"name" : "John"}'); + * console.log(a); // { name: 'John' } + * + * @method utils.fromJson + * @param {string} json JSON to parse. + * @returns {Object} Parsed object. + * @see utils.toJson + * @since 3.0.0 + */ + fromJson: function fromJson(json) { + return utils.isString(json) ? JSON.parse(json) : json; + }, + + + /** + * Retrieve the specified property from the given object. Supports retrieving + * nested properties. + * + * @example + * import { utils } from 'js-data'; + * const a = { foo: { bar: 'baz' }, beep: 'boop' }; + * console.log(utils.get(a, 'beep')); // "boop" + * console.log(utils.get(a, 'foo.bar')); // "baz" + * + * @method utils.get + * @param {object} object Object from which to retrieve a property's value. + * @param {string} prop Property to retrieve. + * @returns {*} Value of the specified property. + * @see utils.set + * @since 3.0.0 + */ + 'get': function get$$1(object, prop) { + if (!prop) { + return; + } + var parts = prop.split('.'); + var last = parts.pop(); + + while (prop = parts.shift()) { + // eslint-disable-line + object = object[prop]; + if (object == null) { + // eslint-disable-line + return; + } + } + + return object[last]; + }, + + /** + * Return the superclass for the given instance or subclass. If an instance is + * provided, then finds the parent class of the instance's constructor. + * + * @example + * import { utils } from 'js-data'; + * // using ES2015 classes + * class Foo {} + * class Bar extends Foo {} + * const barInstance = new Bar(); + * let baseType = utils.getSuper(barInstance); + * console.log(Foo === baseType); // true + * + * // using Function constructor with utils.extend + * function Foo () {} + * Foo.extend = utils.extend; + * const Bar = Foo.extend(); + * const barInstance = new Bar(); + * let baseType = utils.getSuper(barInstance); + * console.log(Foo === baseType); // true + * + * @method utils.getSuper + * @param {Object|Function} instance Instance or constructor. + * @param {boolean} [isCtor=false] Whether `instance` is a constructor. + * @returns {Constructor} The superclass (grandparent constructor). + * @since 3.0.0 + */ + getSuper: function getSuper(instance, isCtor) { + var ctor = isCtor ? instance : instance.constructor; + if (ctor.hasOwnProperty('__super__')) { + return ctor.__super__; + } + return Object.getPrototypeOf(ctor) || ctor.__proto__; // eslint-disable-line + }, + + + /** + * Return the intersection of two arrays. + * + * @example + * import { utils } from 'js-data'; + * const arrA = ['green', 'red', 'blue', 'red']; + * const arrB = ['green', 'yellow', 'red']; + * const intersected = utils.intersection(arrA, arrB); + * + * console.log(intersected); // ['green', 'red']) + * + * @method utils.intersection + * @param {array} array1 First array. + * @param {array} array2 Second array. + * @returns {Array} Array of elements common to both arrays. + * @since 3.0.0 + */ + intersection: function intersection(array1, array2) { + if (!array1 || !array2) { + return []; + } + var result = []; + var item = void 0; + var i = void 0; + var len = array1.length; + for (i = 0; i < len; i++) { + item = array1[i]; + if (result.indexOf(item) !== -1) { + continue; + } + if (array2.indexOf(item) !== -1) { + result.push(item); + } + } + return result; + }, + + + /** + * Proxy for `Array.isArray`. + * + * @example + * import { utils } from 'js-data'; + * const a = [1,2,3,4,5]; + * const b = { foo: "bar" }; + * console.log(utils.isArray(a)); // true + * console.log(utils.isArray(b)); // false + * + * @method utils.isArray + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is an array. + * @since 3.0.0 + */ + isArray: Array.isArray, + + /** + * Return whether `prop` is matched by any string or regular expression in + * `blacklist`. + * + * @example + * import { utils } from 'js-data'; + * const blacklist = [/^\$hashKey/g, /^_/g, 'id']; + * console.log(utils.isBlacklisted("$hashKey", blacklist)); // true + * console.log(utils.isBlacklisted("id", blacklist)); // true + * console.log(utils.isBlacklisted("_myProp", blacklist)); // true + * console.log(utils.isBlacklisted("my_id", blacklist)); // false + * + * @method utils.isBlacklisted + * @param {string} prop The name of a property to check. + * @param {array} blacklist Array of strings and regular expressions. + * @returns {boolean} Whether `prop` was matched. + * @since 3.0.0 + */ + isBlacklisted: function isBlacklisted(prop, blacklist) { + if (!blacklist || !blacklist.length) { + return false; + } + var matches = void 0; + for (var i = 0; i < blacklist.length; i++) { + if (toStr(blacklist[i]) === REGEXP_TAG && blacklist[i].test(prop) || blacklist[i] === prop) { + matches = prop; + return !!matches; + } + } + return !!matches; + }, + + + /** + * Return whether the provided value is a boolean. + * + * @example + * import { utils } from 'js-data'; + * const a = true; + * const b = { foo: "bar" }; + * console.log(utils.isBoolean(a)); // true + * console.log(utils.isBoolean(b)); // false + * + * @method utils.isBoolean + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is a boolean. + * @since 3.0.0 + */ + isBoolean: function isBoolean(value) { + return toStr(value) === BOOL_TAG; + }, + + + /** + * Return whether the provided value is a date. + * + * @example + * import { utils } from 'js-data'; + * const a = new Date(); + * const b = { foo: "bar" }; + * console.log(utils.isDate(a)); // true + * console.log(utils.isDate(b)); // false + * + * @method utils.isDate + * @param {*} value The value to test. + * @returns {Date} Whether the provided value is a date. + * @since 3.0.0 + */ + isDate: function isDate(value) { + return value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && toStr(value) === DATE_TAG; + }, + + + /** + * Return whether the provided value is a function. + * + * @example + * import { utils } from 'js-data'; + * const a = function () { console.log('foo bar'); }; + * const b = { foo: "bar" }; + * console.log(utils.isFunction(a)); // true + * console.log(utils.isFunction(b)); // false + * + * @method utils.isFunction + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is a function. + * @since 3.0.0 + */ + isFunction: function isFunction(value) { + return typeof value === 'function' || value && toStr(value) === FUNC_TAG; + }, + + + /** + * Return whether the provided value is an integer. + * + * @example + * import { utils } from 'js-data'; + * const a = 1; + * const b = 1.25; + * const c = '1'; + * console.log(utils.isInteger(a)); // true + * console.log(utils.isInteger(b)); // false + * console.log(utils.isInteger(c)); // false + * + * @method utils.isInteger + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is an integer. + * @since 3.0.0 + */ + isInteger: function isInteger(value) { + return toStr(value) === NUMBER_TAG && value == toInteger(value); // eslint-disable-line + }, + + + /** + * Return whether the provided value is `null`. + * + * @example + * import { utils } from 'js-data'; + * const a = null; + * const b = { foo: "bar" }; + * console.log(utils.isNull(a)); // true + * console.log(utils.isNull(b)); // false + * + * @method utils.isNull + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is `null`. + * @since 3.0.0 + */ + isNull: function isNull(value) { + return value === null; + }, + + + /** + * Return whether the provided value is a number. + * + * @example + * import { utils } from 'js-data'; + * const a = 1; + * const b = -1.25; + * const c = '1'; + * console.log(utils.isNumber(a)); // true + * console.log(utils.isNumber(b)); // true + * console.log(utils.isNumber(c)); // false + * + * @method utils.isNumber + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is a number. + * @since 3.0.0 + */ + isNumber: function isNumber(value) { + var type = typeof value === 'undefined' ? 'undefined' : _typeof(value); + return type === 'number' || value && type === 'object' && toStr(value) === NUMBER_TAG; + }, + + + /** + * Return whether the provided value is an object. + * + * @example + * import { utils } from 'js-data'; + * const a = { foo: "bar" }; + * const b = 'foo bar'; + * console.log(utils.isObject(a)); // true + * console.log(utils.isObject(b)); // false + * + * @method utils.isObject + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is an object. + * @since 3.0.0 + */ + isObject: function isObject(value) { + return toStr(value) === OBJECT_TAG; + }, + + + /** + * Return whether the provided value is a regular expression. + * + * @example + * import { utils } from 'js-data'; + * const a = /^\$.+$/ig; + * const b = new RegExp('^\$.+$', 'ig'); + * const c = { foo: "bar" }; + * console.log(utils.isRegExp(a)); // true + * console.log(utils.isRegExp(b)); // true + * console.log(utils.isRegExp(c)); // false + * + * @method utils.isRegExp + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is a regular expression. + * @since 3.0.0 + */ + isRegExp: function isRegExp(value) { + return toStr(value) === REGEXP_TAG; + }, + + + /** + * Return whether the provided value is a string or a number. + * + * @example + * import { utils } from 'js-data'; + * console.log(utils.isSorN('')); // true + * console.log(utils.isSorN(-1.65)); // true + * console.log(utils.isSorN('my string')); // true + * console.log(utils.isSorN({})); // false + * console.log(utils.isSorN([1,2,4])); // false + * + * @method utils.isSorN + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is a string or a number. + * @since 3.0.0 + */ + isSorN: function isSorN(value) { + return utils.isString(value) || utils.isNumber(value); + }, + + + /** + * Return whether the provided value is a string. + * + * @example + * import { utils } from 'js-data'; + * console.log(utils.isString('')); // true + * console.log(utils.isString('my string')); // true + * console.log(utils.isString(100)); // false + * console.log(utils.isString([1,2,4])); // false + * + * @method utils.isString + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is a string. + * @since 3.0.0 + */ + isString: function isString(value) { + return typeof value === 'string' || value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && toStr(value) === STRING_TAG; + }, + + + /** + * Return whether the provided value is a `undefined`. + * + * @example + * import { utils } from 'js-data'; + * const a = undefined; + * const b = { foo: "bar"}; + * console.log(utils.isUndefined(a)); // true + * console.log(utils.isUndefined(b.baz)); // true + * console.log(utils.isUndefined(b)); // false + * console.log(utils.isUndefined(b.foo)); // false + * + * @method utils.isUndefined + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is a `undefined`. + * @since 3.0.0 + */ + isUndefined: function isUndefined(value) { + return value === undefined; + }, + + + /** + * Mix in logging capabilities to the target. + * + * @example + * import { utils } from 'js-data'; + * const a = { foo: "bar"}; + * + * // Add standard logging to an object + * utils.logify(a); + * a.log('info', 'test log info'); // output 'test log info' to console. + * + * // Toggle debug output of an object + * a.dbg('test debug output'); // does not output because debug is off. + * a.debug = true; + * a.dbg('test debug output'); // output 'test debug output' to console. + * + * @method utils.logify + * @param {*} target The target. + * @since 3.0.0 + */ + logify: function logify(target) { + utils.addHiddenPropsToTarget(target, { + dbg: function dbg() { + if (utils.isFunction(this.log)) { + for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + this.log.apply(this, ['debug'].concat(args)); + } + }, + log: function log(level) { + for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + + if (level && !args.length) { + args.push(level); + level = 'debug'; + } + if (level === 'debug' && !this.debug) { + return; + } + var prefix = level.toUpperCase() + ': (' + (this.name || this.constructor.name) + ')'; + if (utils.isFunction(console[level])) { + var _console; + + (_console = console)[level].apply(_console, [prefix].concat(args)); + } else { + var _console2; + + (_console2 = console).log.apply(_console2, [prefix].concat(args)); + } + } + }); + }, + + + /** + * Adds the given record to the provided array only if it's not already in the + * array. + * + * @example + * import { utils } from 'js-data'; + * const colors = ['red', 'green', 'yellow']; + * + * console.log(colors.length); // 3 + * utils.noDupeAdd(colors, 'red'); + * console.log(colors.length); // 3, red already exists + * + * utils.noDupeAdd(colors, 'blue'); + * console.log(colors.length); // 4, blue was added + * + * @method utils.noDupeAdd + * @param {array} array The array. + * @param {*} record The value to add. + * @param {Function} fn Callback function passed to {@link utils.findIndex}. + * @since 3.0.0 + */ + noDupeAdd: function noDupeAdd(array, record, fn) { + if (!array) { + return; + } + var index = this.findIndex(array, fn); + if (index < 0) { + array.push(record); + } + }, + + + /** + * Return a shallow copy of the provided object, minus the properties + * specified in `keys`. + * + * @example + * import { utils } from 'js-data'; + * const a = { name: 'John', $hashKey: 1214910 }; + * + * let b = utils.omit(a, ['$hashKey']); + * console.log(b); // { name: 'John' } + * + * @method utils.omit + * @param {object} props The object to copy. + * @param {string[]} keys Array of strings, representing properties to skip. + * @returns {Object} Shallow copy of `props`, minus `keys`. + * @since 3.0.0 + */ + omit: function omit(props, keys) { + var _props = {}; + utils.forOwn(props, function (value, key) { + if (keys.indexOf(key) === -1) { + _props[key] = value; + } + }); + return _props; + }, + + + /** + * Return a shallow copy of the provided object, but only include the + * properties specified in `keys`. + * + * @example + * import { utils } from 'js-data'; + * const a = { name: 'John', $hashKey: 1214910 }; + * + * let b = utils.pick(a, ['$hashKey']); + * console.log(b); // { $hashKey: 1214910 } + * + * @method utils.pick + * @param {object} props The object to copy. + * @param {string[]} keys Array of strings, representing properties to keep. + * @returns {Object} Shallow copy of `props`, but only including `keys`. + * @since 3.0.0 + */ + pick: function pick(props, keys) { + return keys.reduce(function (map, key) { + map[key] = props[key]; + return map; + }, {}); + }, + + + /** + * Return a plain copy of the given value. + * + * @example + * import { utils } from 'js-data'; + * const a = { name: 'John' }; + * let b = utils.plainCopy(a); + * console.log(a === b); // false + * + * @method utils.plainCopy + * @param {*} value The value to copy. + * @returns {*} Plain copy of `value`. + * @see utils.copy + * @since 3.0.0 + */ + plainCopy: function plainCopy(value) { + return utils.copy(value, undefined, undefined, undefined, undefined, true); + }, + + + /** + * Shortcut for `utils.Promise.reject(value)`. + * + * @example + * import { utils } from 'js-data'; + * + * utils.reject("Testing static reject").then(function (data) { + * // not called + * }).catch(function (reason) { + * console.log(reason); // "Testing static reject" + * }); + * + * @method utils.reject + * @param {*} [value] Value with which to reject the Promise. + * @returns {Promise} Promise reject with `value`. + * @see utils.Promise + * @since 3.0.0 + */ + reject: function reject(value) { + return utils.Promise.reject(value); + }, + + + /** + * Remove the last item found in array according to the given checker function. + * + * @example + * import { utils } from 'js-data'; + * + * const colors = ['red', 'green', 'yellow', 'red']; + * utils.remove(colors, (color) => color === 'red'); + * console.log(colors); // ['red', 'green', 'yellow'] + * + * @method utils.remove + * @param {array} array The array to search. + * @param {Function} fn Checker function. + */ + remove: function remove(array, fn) { + if (!array || !array.length) { + return; + } + var index = this.findIndex(array, fn); + if (index >= 0) { + array.splice(index, 1); // todo should this be recursive? + } + }, + + + /** + * Shortcut for `utils.Promise.resolve(value)`. + * + * @example + * import { utils } from 'js-data'; + * + * utils.resolve("Testing static resolve").then(function (data) { + * console.log(data); // "Testing static resolve" + * }).catch(function (reason) { + * // not called + * }); + * + * @param {*} [value] Value with which to resolve the Promise. + * @returns {Promise} Promise resolved with `value`. + * @see utils.Promise + * @since 3.0.0 + */ + resolve: function resolve(value) { + return utils.Promise.resolve(value); + }, + + + /** + * Set the value at the provided key or path. + * + * @example + * import { utils } from 'js-data'; + * + * const john = { + * name: 'John', + * age: 25, + * parent: { + * name: 'John's Mom', + * age: 50 + * } + * }; + * // set value by key + * utils.set(john, 'id', 98); + * console.log(john.id); // 98 + * + * // set value by path + * utils.set(john, 'parent.id', 20); + * console.log(john.parent.id); // 20 + * + * // set value by path/value map + * utils.set(john, { + * 'id': 1098, + * 'parent': { id: 1020 }, + * 'parent.age': '55' + * }); + * console.log(john.id); // 1098 + * console.log(john.parent.id); // 1020 + * console.log(john.parent.age); // 55 + * + * @method utils.set + * @param {object} object The object on which to set a property. + * @param {(string|Object)} path The key or path to the property. Can also + * pass in an object of path/value pairs, which will all be set on the target + * object. + * @param {*} [value] The value to set. + */ + set: function set$$1(object, path, value) { + if (utils.isObject(path)) { + utils.forOwn(path, function (value, _path) { + utils.set(object, _path, value); + }); + } else { + var parts = PATH.exec(path); + if (parts) { + mkdirP(object, parts[1])[parts[2]] = value; + } else { + object[path] = value; + } + } + }, + + /** + * Check whether the two provided objects are deeply equal. + * + * @example + * import { utils } from 'js-data'; + * + * const objA = { + * name: 'John', + * id: 27, + * nested: { + * item: 'item 1', + * colors: ['red', 'green', 'blue'] + * } + * }; + * + * const objB = { + * name: 'John', + * id: 27, + * nested: { + * item: 'item 1', + * colors: ['red', 'green', 'blue'] + * } + * }; + * + * console.log(utils.deepEqual(a,b)); // true + * objB.nested.colors.add('yellow'); // make a change to a nested object's array + * console.log(utils.deepEqual(a,b)); // false + * + * @method utils.deepEqual + * @param {object} a First object in the comparison. + * @param {object} b Second object in the comparison. + * @returns {boolean} Whether the two provided objects are deeply equal. + * @see utils.equal + * @since 3.0.0 + */ + deepEqual: function deepEqual(a, b) { + if (a === b) { + return true; + } + var _equal = true; + if (utils.isArray(a) && utils.isArray(b)) { + if (a.length !== b.length) { + return false; + } + for (var i = a.length; i--;) { + if (!utils.deepEqual(a[i], b[i])) { + // Exit loop early + return false; + } + } + } else if (utils.isObject(a) && utils.isObject(b)) { + utils.forOwn(a, function (value, key) { + if (!(_equal = utils.deepEqual(value, b[key]))) { + // Exit loop early + return false; + } + }); + if (_equal) { + utils.forOwn(b, function (value, key) { + if (!(_equal = utils.deepEqual(value, a[key]))) { + // Exit loop early + return false; + } + }); + } + } else { + return false; + } + return _equal; + }, + + + /** + * Proxy for `JSON.stringify`. + * + * @example + * import { utils } from 'js-data'; + * + * const a = { name: 'John' }; + * let jsonVal = utils.toJson(a); + * console.log(jsonVal); // '{"name" : "John"}' + * + * @method utils.toJson + * @param {*} value Value to serialize to JSON. + * @returns {string} JSON string. + * @see utils.fromJson + * @since 3.0.0 + */ + toJson: JSON.stringify, + + /** + * Unset the value at the provided key or path. + * + * @example + * import { utils } from 'js-data'; + * + * const john = { + * name: 'John', + * age: 25, + * parent: { + * name: 'John's Mom', + * age: 50 + * } + * }; + * + * utils.unset(john, age); + * utils.unset(john, parent.age); + * + * console.log(john.age); // null + * console.log(john.parent.age); // null + * + * @method utils.unset + * @param {object} object The object from which to delete the property. + * @param {string} path The key or path to the property. + * @see utils.set + * @since 3.0.0 + */ + unset: function unset(object, path) { + var parts = path.split('.'); + var last = parts.pop(); + + while (path = parts.shift()) { + // eslint-disable-line + object = object[path]; + if (object == null) { + // eslint-disable-line + return; + } + } + + object[last] = undefined; + } +}; + +var safeSetProp = function safeSetProp(record, field, value) { + if (record && record._set) { + record._set('props.' + field, value); + } else { + utils.set(record, field, value); + } +}; + +var safeSetLink = function safeSetLink(record, field, value) { + if (record && record._set) { + record._set('links.' + field, value); + } else { + utils.set(record, field, value); + } +}; + +/** + * A base class which gives instances private properties. + * + * Typically you won't instantiate this class directly, but you may find it + * useful as an abstract class for your own components. + * + * See {@link Settable.extend} for an example of using {@link Settable} as a + * base class. + * + *```javascript + * import {Settable} from 'js-data' + * ``` + * + * @class Settable + * @returns {Settable} A new {@link Settable} instance. + * @since 3.0.0 + */ +function Settable() { + var _props = {}; + Object.defineProperties(this, { + /** + * Get a private property of this instance. + * + * __Don't use the method unless you know what you're doing.__ + * + * @method Settable#_get + * @param {string} key The property to retrieve. + * @returns {*} The value of the property. + * @since 3.0.0 + */ + _get: { + value: function value(key) { + return utils.get(_props, key); + } + }, + + /** + * Set a private property of this instance. + * + * __Don't use the method unless you know what you're doing.__ + * + * @method __Don't use the method unless you know what you're doing.__#_set + * @param {(string|Object)} key The key or path to the property. Can also + * pass in an object of key/value pairs, which will all be set on the instance. + * @param {*} [value] The value to set. + * @since 3.0.0 + */ + _set: { + value: function value(key, _value) { + return utils.set(_props, key, _value); + } + }, + + /** + * Unset a private property of this instance. + * + * __Don't use the method unless you know what you're doing.__ + * + * @method __Don't use the method unless you know what you're doing.__#_unset + * @param {string} key The property to unset. + * @since 3.0.0 + */ + _unset: { + value: function value(key) { + return utils.unset(_props, key); + } + } + }); +} + +/** + * Create a subclass of this Settable: + * + * @example Settable.extend + * const JSData = require('js-data'); + * const { Settable } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomSettableClass extends Settable { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customSettable = new CustomSettableClass(); + * console.log(customSettable.foo()); + * console.log(CustomSettableClass.beep()); + * + * // Extend the class using alternate method. + * const OtherSettableClass = Settable.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherSettable = new OtherSettableClass(); + * console.log(otherSettable.foo()); + * console.log(OtherSettableClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherSettableClass () { + * Settable.call(this); + * this.created_at = new Date().getTime(); + * } + * Settable.extend({ + * constructor: AnotherSettableClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }) + * const anotherSettable = new AnotherSettableClass(); + * console.log(anotherSettable.created_at); + * console.log(anotherSettable.foo()); + * console.log(AnotherSettableClass.beep()); + * + * @method Settable.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this Settable class. + * @since 3.0.0 + */ +Settable.extend = utils.extend; + +/** + * The base class from which all JSData components inherit some basic + * functionality. + * + * Typically you won't instantiate this class directly, but you may find it + * useful as an abstract class for your own components. + * + * See {@link Component.extend} for an example of using {@link Component} as a + * base class. + * + *```javascript + * import {Component} from 'js-data' + * ``` + * + * @class Component + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.debug=false] See {@link Component#debug}. + * @returns {Component} A new {@link Component} instance. + * @since 3.0.0 + */ +function Component(opts) { + Settable.call(this); + opts || (opts = {}); + + /** + * Whether to enable debug-level logs for this component. Anything that + * extends `Component` inherits this option and the corresponding logging + * functionality. + * + * @example Component#debug + * const JSData = require('js-data'); + * const { Component } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const component = new Component(); + * component.log('debug', 'some message'); // nothing gets logged + * // Display debug logs: + * component.debug = true; + * component.log('debug', 'other message'); // this DOES get logged + * + * @default false + * @name Component#debug + * @since 3.0.0 + * @type {boolean} + */ + this.debug = opts.hasOwnProperty('debug') ? !!opts.debug : false; + + /** + * Event listeners attached to this Component. __Do not modify.__ Use + * {@link Component#on} and {@link Component#off} instead. + * + * @name Component#_listeners + * @private + * @instance + * @since 3.0.0 + * @type {Object} + */ + Object.defineProperty(this, '_listeners', { value: {}, writable: true }); +} + +var Component$1 = Settable.extend({ + constructor: Component +}); + +/** + * Create a subclass of this Component: + * + * @example Component.extend + * const JSData = require('js-data'); + * const { Component } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomComponentClass extends Component { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customComponent = new CustomComponentClass(); + * console.log(customComponent.foo()); + * console.log(CustomComponentClass.beep()); + * + * // Extend the class using alternate method. + * const OtherComponentClass = Component.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherComponent = new OtherComponentClass(); + * console.log(otherComponent.foo()); + * console.log(OtherComponentClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherComponentClass () { + * Component.call(this); + * this.created_at = new Date().getTime(); + * } + * Component.extend({ + * constructor: AnotherComponentClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }) + * const anotherComponent = new AnotherComponentClass(); + * console.log(anotherComponent.created_at); + * console.log(anotherComponent.foo()); + * console.log(AnotherComponentClass.beep()); + * + * @method Component.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this Component class. + * @since 3.0.0 + */ +Component.extend = utils.extend; + +/** + * Log the provided values at the "debug" level. Debug-level logs are only + * logged if {@link Component#debug} is `true`. + * + * `.dbg(...)` is shorthand for `.log('debug', ...)`. + * + * @method Component#dbg + * @param {...*} [args] Values to log. + * @since 3.0.0 + */ +/** + * Log the provided values. By default sends values to `console[level]`. + * Debug-level logs are only logged if {@link Component#debug} is `true`. + * + * Will attempt to use appropriate `console` methods if they are available. + * + * @method Component#log + * @param {string} level Log level. + * @param {...*} [args] Values to log. + * @since 3.0.0 + */ +utils.logify(Component.prototype); + +/** + * Register a new event listener on this Component. + * + * @example + * // Listen for all "afterCreate" events in a DataStore + * store.on('afterCreate', (mapperName, props, opts, result) => { + * console.log(mapperName); // "post" + * console.log(props.id); // undefined + * console.log(result.id); // 1234 + * }); + * store.create('post', { title: 'Modeling your data' }).then((post) => { + * console.log(post.id); // 1234 + * }); + * + * @example + * // Listen for the "add" event on a collection + * collection.on('add', (records) => { + * console.log(records); // [...] + * }); + * + * @example + * // Listen for "change" events on a record + * post.on('change', (record, changes) => { + * console.log(changes); // { changed: { title: 'Modeling your data' } } + * }); + * post.title = 'Modeling your data'; + * + * @method Component#on + * @param {string} event Name of event to subsribe to. + * @param {Function} listener Listener function to handle the event. + * @param {*} [ctx] Optional content in which to invoke the listener. + * @since 3.0.0 + */ +/** + * Remove an event listener from this Component. If no listener is provided, + * then all listeners for the specified event will be removed. If no event is + * specified then all listeners for all events will be removed. + * + * @example + * // Remove a particular listener for a particular event + * collection.off('add', handler); + * + * @example + * // Remove all listeners for a particular event + * record.off('change'); + * + * @example + * // Remove all listeners to all events + * store.off(); + * + * @method Component#off + * @param {string} [event] Name of event to unsubsribe to. + * @param {Function} [listener] Listener to remove. + * @since 3.0.0 + */ +/** + * Trigger an event on this Component. + * + * @example Component#emit + * // import { Collection, DataStore } from 'js-data'; + * const JSData = require('js-data'); + * const { Collection, DataStore } = JSData; + * + * const collection = new Collection(); + * collection.on('foo', function (msg) { + * console.log(msg); + * }); + * collection.emit('foo', 'bar'); + * + * const store = new DataStore(); + * store.on('beep', function (msg) { + * console.log(msg); + * }); + * store.emit('beep', 'boop'); + * + * @method Component#emit + * @param {string} event Name of event to emit. + * @param {...*} [args] Arguments to pass to any listeners. + * @since 3.0.0 + */ +utils.eventify(Component.prototype, function () { + return this._listeners; +}, function (value) { + this._listeners = value; +}); + +var DOMAIN$2 = 'Query'; +var INDEX_ERR = 'Index inaccessible after first operation'; + +// Reserved words used by JSData's Query Syntax +var reserved = { + limit: '', + offset: '', + orderBy: '', + skip: '', + sort: '', + where: '' + + // Used by our JavaScript implementation of the LIKE operator +};var escapeRegExp = /([.*+?^=!:${}()|[\]/\\])/g; +var percentRegExp = /%/g; +var underscoreRegExp = /_/g; +var escape = function escape(pattern) { + return pattern.replace(escapeRegExp, '\\$1'); +}; + +/** + * A class used by the {@link Collection} class to build queries to be executed + * against the collection's data. An instance of `Query` is returned by + * {@link Collection#query}. Query instances are typically short-lived, and you + * shouldn't have to create them yourself. Just use {@link Collection#query}. + * + * ```javascript + * import { Query } from 'js-data'; + * ``` + * + * @example Query intro + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'draft', id: 2 }, + * { author: 'Mike', age: 32, status: 'draft', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'draft', id: 5 } + * ] + * store.add('post', posts); + * const drafts = store.query('post').filter({ status: 'draft' }).limit(2).run(); + * console.log(drafts); + * + * @class Query + * @extends Component + * @param {Collection} collection The collection on which this query operates. + * @since 3.0.0 + */ +function Query(collection) { + utils.classCallCheck(this, Query); + + /** + * The {@link Collection} on which this query operates. + * + * @name Query#collection + * @since 3.0.0 + * @type {Collection} + */ + this.collection = collection; + + /** + * The current data result of this query. + * + * @name Query#data + * @since 3.0.0 + * @type {Array} + */ + this.data = null; +} + +var Query$1 = Component$1.extend({ + constructor: Query, + + _applyWhereFromObject: function _applyWhereFromObject(where) { + var fields = []; + var ops = []; + var predicates = []; + utils.forOwn(where, function (clause, field) { + if (!utils.isObject(clause)) { + clause = { + '==': clause + }; + } + utils.forOwn(clause, function (expr, op) { + fields.push(field); + ops.push(op); + predicates.push(expr); + }); + }); + return { + fields: fields, + ops: ops, + predicates: predicates + }; + }, + _applyWhereFromArray: function _applyWhereFromArray(where) { + var _this = this; + + var groups = []; + where.forEach(function (_where, i) { + if (utils.isString(_where)) { + return; + } + var prev = where[i - 1]; + var parser = utils.isArray(_where) ? _this._applyWhereFromArray : _this._applyWhereFromObject; + var group = parser.call(_this, _where); + if (prev === 'or') { + group.isOr = true; + } + groups.push(group); + }); + groups.isArray = true; + return groups; + }, + _testObjectGroup: function _testObjectGroup(keep, first, group, item) { + var i = void 0; + var fields = group.fields; + var ops = group.ops; + var predicates = group.predicates; + var len = ops.length; + for (i = 0; i < len; i++) { + var op = ops[i]; + var isOr = op.charAt(0) === '|'; + op = isOr ? op.substr(1) : op; + var expr = this.evaluate(utils.get(item, fields[i]), op, predicates[i]); + if (expr !== undefined) { + keep = first ? expr : isOr ? keep || expr : keep && expr; + } + first = false; + } + return { keep: keep, first: first }; + }, + _testArrayGroup: function _testArrayGroup(keep, first, groups, item) { + var i = void 0; + var len = groups.length; + for (i = 0; i < len; i++) { + var group = groups[i]; + var parser = group.isArray ? this._testArrayGroup : this._testObjectGroup; + var result = parser.call(this, true, true, group, item); + if (groups[i - 1]) { + if (group.isOr) { + keep = keep || result.keep; + } else { + keep = keep && result.keep; + } + } else { + keep = result.keep; + } + first = result.first; + } + return { keep: keep, first: first }; + }, + + + /** + * Find all entities between two boundaries. + * + * @example Get the users ages 18 to 30. + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('user'); + * const users = [ + * { name: 'Peter', age: 25, id: 1 }, + * { name: 'Jim', age: 19, id: 2 }, + * { name: 'Mike', age: 17, id: 3 }, + * { name: 'Alan', age: 29, id: 4 }, + * { name: 'Katie', age: 33, id: 5 } + * ]; + * store.add('user', users) + * const filteredUsers = store + * .query('user') + * .between(18, 30, { index: 'age' }) + * .run(); + * console.log(filteredUsers); + * + * @example Same as above. + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('user'); + * const users = [ + * { name: 'Peter', age: 25, id: 1 }, + * { name: 'Jim', age: 19, id: 2 }, + * { name: 'Mike', age: 17, id: 3 }, + * { name: 'Alan', age: 29, id: 4 }, + * { name: 'Katie', age: 33, id: 5 } + * ]; + * store.add('user', users) + * const filteredUsers = store + * .query('user') + * .between([18], [30], { index: 'age' }) + * .run(); + * console.log(filteredUsers); + * + * @method Query#between + * @param {array} leftKeys Keys defining the left boundary. + * @param {array} rightKeys Keys defining the right boundary. + * @param {object} [opts] Configuration options. + * @param {string} [opts.index] Name of the secondary index to use in the + * query. If no index is specified, the main index is used. + * @param {boolean} [opts.leftInclusive=true] Whether to include entities + * on the left boundary. + * @param {boolean} [opts.rightInclusive=false] Whether to include entities + * on the left boundary. + * @param {boolean} [opts.limit] Limit the result to a certain number. + * @param {boolean} [opts.offset] The number of resulting entities to skip. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + between: function between(leftKeys, rightKeys, opts) { + opts || (opts = {}); + if (this.data) { + throw utils.err(DOMAIN$2 + '#between')(500, 'Cannot access index'); + } + this.data = this.collection.getIndex(opts.index).between(leftKeys, rightKeys, opts); + return this; + }, + + + /** + * The comparison function used by the {@link Query} class. + * + * @method Query#compare + * @param {array} orderBy An orderBy clause used for sorting and sub-sorting. + * @param {number} index The index of the current orderBy clause being used. + * @param {*} a The first item in the comparison. + * @param {*} b The second item in the comparison. + * @returns {number} -1 if `b` should preceed `a`. 0 if `a` and `b` are equal. + * 1 if `a` should preceed `b`. + * @since 3.0.0 + */ + compare: function compare(orderBy, index, a, b) { + var def = orderBy[index]; + var cA = utils.get(a, def[0]); + var cB = utils.get(b, def[0]); + if (cA && utils.isString(cA)) { + cA = cA.toUpperCase(); + } + if (cB && utils.isString(cB)) { + cB = cB.toUpperCase(); + } + if (a === undefined) { + a = null; + } + if (b === undefined) { + b = null; + } + if (def[1].toUpperCase() === 'DESC') { + var temp = cB; + cB = cA; + cA = temp; + } + if (cA < cB) { + return -1; + } else if (cA > cB) { + return 1; + } else { + if (index < orderBy.length - 1) { + return this.compare(orderBy, index + 1, a, b); + } else { + return 0; + } + } + }, + + + /** + * Predicate evaluation function used by the {@link Query} class. + * + * @method Query#evaluate + * @param {*} value The value to evaluate. + * @param {string} op The operator to use in this evaluation. + * @param {*} predicate The predicate to use in this evaluation. + * @returns {boolean} Whether the value passed the evaluation or not. + * @since 3.0.0 + */ + evaluate: function evaluate(value, op, predicate) { + var ops = this.constructor.ops; + if (ops[op]) { + return ops[op](value, predicate); + } + if (op.indexOf('like') === 0) { + return this.like(predicate, op.substr(4)).exec(value) !== null; + } else if (op.indexOf('notLike') === 0) { + return this.like(predicate, op.substr(7)).exec(value) === null; + } + }, + + + /** + * Find the record or records that match the provided query or are accepted by + * the provided filter function. + * + * @example Get the draft posts by authors younger than 30 + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post') + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'published', id: 2 }, + * { author: 'Mike', age: 32, status: 'draft', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'published', id: 5 } + * { author: 'Peter', age: 25, status: 'deleted', id: 6 }, + * { author: 'Sally', age: 21, status: 'draft', id: 7 }, + * { author: 'Jim', age: 27, status: 'draft', id: 8 }, + * { author: 'Jim', age: 27, status: 'published', id: 9 }, + * { author: 'Jason', age: 55, status: 'published', id: 10 } + * ]; + * store.add('post', posts); + * const results = store + * .query('post') + * .filter({ + * where: { + * status: { + * '==': 'draft' + * }, + * age: { + * '<': 30 + * } + * } + * }) + * .run(); + * console.log(results); + * + * @example Use a custom filter function + * const posts = query + * .filter(function (post) { + * return post.isReady(); + * }) + * .run(); + * + * @method Query#filter + * @param {(Object|Function)} [queryOrFn={}] Selection query or filter + * function. + * @param {Function} [thisArg] Context to which to bind `queryOrFn` if + * `queryOrFn` is a function. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + filter: function filter(query, thisArg) { + var _this2 = this; + + /** + * Selection query as defined by JSData's [Query Syntax][querysyntax]. + * + * [querysyntax]: http://www.js-data.io/v3.0/docs/query-syntax + * + * @example Empty "findAll" query + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post') + * store.findAll('post').then((posts) => { + * console.log(posts); // [...] + * }); + * + * @example Empty "filter" query + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * const posts = store.filter('post'); + * console.log(posts); // [...] + * + * @example Complex "filter" query + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * const PAGE_SIZE = 2; + * let currentPage = 3; + * + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'published', id: 2 }, + * { author: 'Mike', age: 32, status: 'draft', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'published', id: 5 } + * { author: 'Peter', age: 25, status: 'deleted', id: 6 }, + * { author: 'Sally', age: 21, status: 'draft', id: 7 }, + * { author: 'Jim', age: 27, status: 'draft', id: 8 }, + * { author: 'Jim', age: 27, status: 'published', id: 9 }, + * { author: 'Jason', age: 55, status: 'published', id: 10 } + * ]; + * store.add('post', posts); + * // Retrieve a filtered page of blog posts + * // Would typically replace filter with findAll + * const results = store.filter('post', { + * where: { + * status: { + * // WHERE status = 'published' + * '==': 'published' + * }, + * author: { + * // AND author IN ('bob', 'alice') + * 'in': ['bob', 'alice'], + * // OR author IN ('karen') + * '|in': ['karen'] + * } + * }, + * orderBy: [ + * // ORDER BY date_published DESC, + * ['date_published', 'DESC'], + * // ORDER BY title ASC + * ['title', 'ASC'] + * ], + * // LIMIT 2 + * limit: PAGE_SIZE, + * // SKIP 4 + * offset: PAGE_SIZE * (currentPage - 1) + * }); + * console.log(results); + * + * @namespace query + * @property {number} [limit] See {@link query.limit}. + * @property {number} [offset] See {@link query.offset}. + * @property {string|Array[]} [orderBy] See {@link query.orderBy}. + * @property {number} [skip] Alias for {@link query.offset}. + * @property {string|Array[]} [sort] Alias for {@link query.orderBy}. + * @property {Object} [where] See {@link query.where}. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/query-syntax","JSData's Query Syntax"] + */ + query || (query = {}); + this.getData(); + if (utils.isObject(query)) { + var where = {}; + + /** + * Filtering criteria. Records that do not meet this criteria will be exluded + * from the result. + * + * @example Return posts where author is at least 32 years old + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post') + * const posts = [ + * { author: 'John', age: 30, id: 5 }, + * { author: 'Sally', age: 31, id: 6 }, + * { author: 'Mike', age: 32, id: 7 }, + * { author: 'Adam', age: 33, id: 8 }, + * { author: 'Adam', age: 33, id: 9 } + * ]; + * store.add('post', posts); + * const results = store.filter('post', { + * where: { + * age: { + * '>=': 30 + * } + * } + * }); + * console.log(results); + * + * @name query.where + * @type {Object} + * @see http://www.js-data.io/v3.0/docs/query-syntax + * @since 3.0.0 + */ + if (utils.isObject(query.where) || utils.isArray(query.where)) { + where = query.where; + } + utils.forOwn(query, function (value, key) { + if (!(key in reserved) && !(key in where)) { + where[key] = { + '==': value + }; + } + }); + var groups = void 0; + + // Apply filter for each field + if (utils.isObject(where) && Object.keys(where).length !== 0) { + groups = this._applyWhereFromArray([where]); + } else if (utils.isArray(where)) { + groups = this._applyWhereFromArray(where); + } + + if (groups) { + this.data = this.data.filter(function (item, i) { + return _this2._testArrayGroup(true, true, groups, item).keep; + }); + } + + // Sort + var orderBy = query.orderBy || query.sort; + + if (utils.isString(orderBy)) { + orderBy = [[orderBy, 'ASC']]; + } + if (!utils.isArray(orderBy)) { + orderBy = null; + } + + /** + * Determines how records should be ordered in the result. + * + * @example Order posts by `author` then by `id` descending + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post') + * const posts = [ + * { author: 'John', age: 30, id: 5 }, + * { author: 'Sally', age: 31, id: 6 }, + * { author: 'Mike', age: 32, id: 7 }, + * { author: 'Adam', age: 33, id: 8 }, + * { author: 'Adam', age: 33, id: 9 } + * ]; + * store.add('post', posts); + * const results = store.filter('post', { + * orderBy:[['author','ASC'],['id','DESC']] + * }); + * console.log(results); + * + * @name query.orderBy + * @type {string|Array[]} + * @see http://www.js-data.io/v3.0/docs/query-syntax + * @since 3.0.0 + */ + if (orderBy) { + var index = 0; + orderBy.forEach(function (def, i) { + if (utils.isString(def)) { + orderBy[i] = [def, 'ASC']; + } + }); + this.data.sort(function (a, b) { + return _this2.compare(orderBy, index, a, b); + }); + } + + /** + * Number of records to skip. + * + * @example Retrieve the first "page" of blog posts using findAll + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * const PAGE_SIZE = 10; + * let currentPage = 1; + * store.findAll('post', { + * offset: PAGE_SIZE * (currentPage 1) + * limit: PAGE_SIZE + * }); + * + * @example Retrieve the last "page" of blog posts using filter + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * + * const PAGE_SIZE = 5; + * let currentPage = 2; + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, id: 1 }, + * { author: 'Sally', age: 31, id: 2 }, + * { author: 'Mike', age: 32, id: 3 }, + * { author: 'Adam', age: 33, id: 4 }, + * { author: 'Adam', age: 33, id: 5 }, + * { author: 'Peter', age: 25, id: 6 }, + * { author: 'Sally', age: 21, id: 7 }, + * { author: 'Jim', age: 27, id: 8 }, + * { author: 'Jim', age: 27, id: 9 }, + * { author: 'Jason', age: 55, id: 10 } + * ]; + * store.add('post', posts); + * const results = store.filter('post', { + * offset: PAGE_SIZE * (currentPage 1) + * limit: PAGE_SIZE + * }); + * console.log(results) + * + * @name query.offset + * @type {number} + * @see http://www.js-data.io/v3.0/docs/query-syntax + * @since 3.0.0 + */ + if (utils.isNumber(query.skip)) { + this.skip(query.skip); + } else if (utils.isNumber(query.offset)) { + this.skip(query.offset); + } + + /** + * Maximum number of records to retrieve. + * + * @example Retrieve the first "page" of blog posts using findAll + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * + * const PAGE_SIZE = 10 + * let currentPage = 1 + * store.findAll('post', { + * offset: PAGE_SIZE * (currentPage 1) + * limit: PAGE_SIZE + * }); + * + * @example Retrieve the last "page" of blog posts using filter + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * + * const PAGE_SIZE = 5 + * let currentPage = 2 + * store.defineMapper('post') + * const posts = [ + * { author: 'John', age: 30, id: 1 }, + * { author: 'Sally', age: 31, id: 2 }, + * { author: 'Mike', age: 32, id: 3 }, + * { author: 'Adam', age: 33, id: 4 }, + * { author: 'Adam', age: 33, id: 5 }, + * { author: 'Peter', age: 25, id: 6 }, + * { author: 'Sally', age: 21, id: 7 }, + * { author: 'Jim', age: 27, id: 8 }, + * { author: 'Jim', age: 27, id: 9 }, + * { author: 'Jason', age: 55, id: 10 } + * ]; + * store.add('post', posts); + * const results = store.filter('post', { + * offset: PAGE_SIZE * (currentPage 1) + * limit: PAGE_SIZE + * }); + * console.log(results) + * + * @name query.limit + * @type {number} + * @see http://www.js-data.io/v3.0/docs/query-syntax + * @since 3.0.0 + */ + if (utils.isNumber(query.limit)) { + this.limit(query.limit); + } + } else if (utils.isFunction(query)) { + this.data = this.data.filter(query, thisArg); + } + return this; + }, + + + /** + * Iterate over all entities. + * + * @method Query#forEach + * @param {Function} forEachFn Iteration function. + * @param {*} [thisArg] Context to which to bind `forEachFn`. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + forEach: function forEach(forEachFn, thisArg) { + this.getData().forEach(forEachFn, thisArg); + return this; + }, + + + /** + * Find the entity or entities that match the provided key. + * + * @example Get the entity whose primary key is 25. + * const entities = query.get(25).run(); + * + * @example Same as above. + * const entities = query.get([25]).run(); + * + * @example Get all users who are active and have the "admin" role. + * const activeAdmins = query.get(['active', 'admin'], { + * index: 'activityAndRoles' + * }).run(); + * + * @example Get all entities that match a certain weather condition. + * const niceDays = query.get(['sunny', 'humid', 'calm'], { + * index: 'weatherConditions' + * }).run(); + * + * @method Query#get + * @param {array} keyList Key(s) defining the entity to retrieve. If + * `keyList` is not an array (i.e. for a single-value key), it will be + * wrapped in an array. + * @param {object} [opts] Configuration options. + * @param {string} [opts.string] Name of the secondary index to use in the + * query. If no index is specified, the main index is used. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + get: function get(keyList, opts) { + keyList || (keyList = []); + opts || (opts = {}); + if (this.data) { + throw utils.err(DOMAIN$2 + '#get')(500, INDEX_ERR); + } + if (keyList && !utils.isArray(keyList)) { + keyList = [keyList]; + } + if (!keyList.length) { + this.getData(); + return this; + } + this.data = this.collection.getIndex(opts.index).get(keyList); + return this; + }, + + + /** + * Find the entity or entities that match the provided keyLists. + * + * @example Get the posts where "status" is "draft" or "inReview". + * const posts = query.getAll('draft', 'inReview', { index: 'status' }).run(); + * + * @example Same as above. + * const posts = query.getAll(['draft'], ['inReview'], { index: 'status' }).run(); + * + * @method Query#getAll + * @param {...Array} [keyList] Provide one or more keyLists, and all + * entities matching each keyList will be retrieved. If no keyLists are + * provided, all entities will be returned. + * @param {object} [opts] Configuration options. + * @param {string} [opts.index] Name of the secondary index to use in the + * query. If no index is specified, the main index is used. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + getAll: function getAll() { + var _this3 = this; + + var opts = {}; + if (this.data) { + throw utils.err(DOMAIN$2 + '#getAll')(500, INDEX_ERR); + } + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + if (!args.length || args.length === 1 && utils.isObject(args[0])) { + this.getData(); + return this; + } else if (args.length && utils.isObject(args[args.length - 1])) { + opts = args[args.length - 1]; + args.pop(); + } + var collection = this.collection; + var index = collection.getIndex(opts.index); + this.data = []; + args.forEach(function (keyList) { + _this3.data = _this3.data.concat(index.get(keyList)); + }); + return this; + }, + + + /** + * Return the current data result of this query. + * + * @method Query#getData + * @returns {Array} The data in this query. + * @since 3.0.0 + */ + getData: function getData() { + if (!this.data) { + this.data = this.collection.index.getAll(); + } + return this.data; + }, + + + /** + * Implementation used by the `like` operator. Takes a pattern and flags and + * returns a `RegExp` instance that can test strings. + * + * @method Query#like + * @param {string} pattern Testing pattern. + * @param {string} flags Flags for the regular expression. + * @returns {RegExp} Regular expression for testing strings. + * @since 3.0.0 + */ + like: function like(pattern, flags) { + return new RegExp('^' + escape(pattern).replace(percentRegExp, '.*').replace(underscoreRegExp, '.') + '$', flags); + }, + + + /** + * Limit the result. + * + * @example Get only the first 2 posts. + * const store = new JSData.DataStore(); + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'draft', id: 2 }, + * { author: 'Mike', age: 32, status: 'draft', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'draft', id: 5 } + * ]; + * store.add('post', posts); + * const results = store.query('post').limit(2).run(); + * console.log(results); + * + * @method Query#limit + * @param {number} num The maximum number of entities to keep in the result. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + limit: function limit(num) { + if (!utils.isNumber(num)) { + throw utils.err(DOMAIN$2 + '#limit', 'num')(400, 'number', num); + } + var data = this.getData(); + this.data = data.slice(0, Math.min(data.length, num)); + return this; + }, + + + /** + * Apply a mapping function to the result data. + * + * @example + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('user'); + * const users = [ + * { name: 'Peter', age: 25, id: 1 }, + * { name: 'Jim', age: 19, id: 2 }, + * { name: 'Mike', age: 17, id: 3 }, + * { name: 'Alan', age: 29, id: 4 }, + * { name: 'Katie', age: 33, id: 5 } + * ]; + * store.add('user', users); + * const ages = store + * .query('user') + * .map(function (user) { + * return user.age; + * }) + * .run(); + * console.log(ages); + * + * @method Query#map + * @param {Function} mapFn Mapping function. + * @param {*} [thisArg] Context to which to bind `mapFn`. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + map: function map(mapFn, thisArg) { + this.data = this.getData().map(mapFn, thisArg); + return this; + }, + + + /** + * Return the result of calling the specified function on each item in this + * collection's main index. + * + * @example + * const stringAges = UserCollection.query().mapCall('toString').run(); + * + * @method Query#mapCall + * @param {string} funcName Name of function to call + * @parama {...*} [args] Remaining arguments to be passed to the function. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + mapCall: function mapCall(funcName) { + for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + this.data = this.getData().map(function (item) { + return item[funcName].apply(item, args); + }); + return this; + }, + + + /** + * Complete the execution of the query and return the resulting data. + * + * @method Query#run + * @returns {Array} The result of executing this query. + * @since 3.0.0 + */ + run: function run() { + var data = this.data; + this.data = null; + return data; + }, + + + /** + * Skip a number of results. + * + * @example Get all but the first 2 posts. + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'draft', id: 2 }, + * { author: 'Mike', age: 32, status: 'draft', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'draft', id: 5 } + * ]; + * store.add('post', posts); + * const results = store.query('post').skip(2).run(); + * console.log(results); + * + * @method Query#skip + * @param {number} num The number of entities to skip. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + skip: function skip(num) { + if (!utils.isNumber(num)) { + throw utils.err(DOMAIN$2 + '#skip', 'num')(400, 'number', num); + } + var data = this.getData(); + if (num < data.length) { + this.data = data.slice(num); + } else { + this.data = []; + } + return this; + } +}, { + /** + * The filtering operators supported by {@link Query#filter}, and which are + * implemented by adapters (for the most part). + * + * @example Variant 1 + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'published', id: 2 }, + * { author: 'Mike', age: 32, status: 'published', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'published', id: 5 } + * ]; + * store.add('post', posts); + * const publishedPosts = store.filter('post', { + * status: 'published', + * limit: 2 + * }); + * console.log(publishedPosts); + * + * + * @example Variant 2 + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post') + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'published', id: 2 }, + * { author: 'Mike', age: 32, status: 'published', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'published', id: 5 } + * ]; + * store.add('post', posts); + * const publishedPosts = store.filter('post', { + * where: { + * status: { + * '==': 'published' + * } + * }, + * limit: 2 + * }); + * console.log(publishedPosts); + * + * @example Variant 3 + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'published', id: 2 }, + * { author: 'Mike', age: 32, status: 'published', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'published', id: 5 } + * ]; + * store.add('post', posts); + * const publishedPosts = store + * .query('post') + * .filter({ status: 'published' }) + * .limit(2) + * .run(); + * console.log(publishedPosts); + * + * @example Variant 4 + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'published', id: 2 }, + * { author: 'Mike', age: 32, status: 'published', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'published', id: 5 } + * ]; + * store.add('post', posts); + * const publishedPosts = store + * .query('post') + * .filter({ + * where: { + * status: { + * '==': 'published' + * } + * } + * }) + * .limit(2) + * .run(); + * console.log(publishedPosts); + * + * @example Multiple operators + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'published', id: 2 }, + * { author: 'Mike', age: 32, status: 'published', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'published', id: 5 } + * ]; + * store.add('post', posts); + * + * const myPublishedPosts = store.filter('post', { + * where: { + * status: { + * '==': 'published' + * }, + * user_id: { + * '==': currentUser.id + * } + * } + * }); + * + * console.log(myPublishedPosts); + * + * @name Query.ops + * @property {Function} == Equality operator. + * @property {Function} != Inequality operator. + * @property {Function} > Greater than operator. + * @property {Function} >= Greater than (inclusive) operator. + * @property {Function} < Less than operator. + * @property {Function} <= Less than (inclusive) operator. + * @property {Function} isectEmpty Operator that asserts that the intersection + * between two arrays is empty. + * @property {Function} isectNotEmpty Operator that asserts that the + * intersection between two arrays is __not__ empty. + * @property {Function} in Operator that asserts whether a value is in an + * array. + * @property {Function} notIn Operator that asserts whether a value is __not__ + * in an array. + * @property {Function} contains Operator that asserts whether an array + * contains a value. + * @property {Function} notContains Operator that asserts whether an array + * does __not__ contain a value. + * @since 3.0.0 + * @type {Object} + */ + ops: { + '=': function _(value, predicate) { + return value == predicate; // eslint-disable-line + }, + '==': function _(value, predicate) { + return value == predicate; // eslint-disable-line + }, + '===': function _(value, predicate) { + return value === predicate; + }, + '!=': function _(value, predicate) { + return value != predicate; // eslint-disable-line + }, + '!==': function _(value, predicate) { + return value !== predicate; + }, + '>': function _(value, predicate) { + return value > predicate; + }, + '>=': function _(value, predicate) { + return value >= predicate; + }, + '<': function _(value, predicate) { + return value < predicate; + }, + '<=': function _(value, predicate) { + return value <= predicate; + }, + 'isectEmpty': function isectEmpty(value, predicate) { + return !utils.intersection(value || [], predicate || []).length; + }, + 'isectNotEmpty': function isectNotEmpty(value, predicate) { + return utils.intersection(value || [], predicate || []).length; + }, + 'in': function _in(value, predicate) { + return predicate.indexOf(value) !== -1; + }, + 'notIn': function notIn(value, predicate) { + return predicate.indexOf(value) === -1; + }, + 'contains': function contains(value, predicate) { + return (value || []).indexOf(predicate) !== -1; + }, + 'notContains': function notContains(value, predicate) { + return (value || []).indexOf(predicate) === -1; + } + } +}); + +/** + * Create a subclass of this Query: + * @example Query.extend + * const JSData = require('js-data'); + * const { Query } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomQueryClass extends Query { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customQuery = new CustomQueryClass(); + * console.log(customQuery.foo()); + * console.log(CustomQueryClass.beep()); + * + * // Extend the class using alternate method. + * const OtherQueryClass = Query.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherQuery = new OtherQueryClass(); + * console.log(otherQuery.foo()); + * console.log(OtherQueryClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherQueryClass (collection) { + * Query.call(this, collection); + * this.created_at = new Date().getTime(); + * } + * Query.extend({ + * constructor: AnotherQueryClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const anotherQuery = new AnotherQueryClass(); + * console.log(anotherQuery.created_at); + * console.log(anotherQuery.foo()); + * console.log(AnotherQueryClass.beep()); + * + * @method Query.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this Query class. + * @since 3.0.0 + */ + +// TODO: remove this when the rest of the project is cleaned +var belongsToType = 'belongsTo'; +var hasManyType = 'hasMany'; +var hasOneType = 'hasOne'; + +var DOMAIN$4 = 'Relation'; + +function Relation(relatedMapper) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + utils.classCallCheck(this, Relation); + + options.type = this.constructor.TYPE_NAME; + this.validateOptions(relatedMapper, options); + + if ((typeof relatedMapper === 'undefined' ? 'undefined' : _typeof(relatedMapper)) === 'object') { + Object.defineProperty(this, 'relatedMapper', { value: relatedMapper }); + } + + Object.defineProperty(this, 'inverse', { writable: true }); + utils.fillIn(this, options); +} + +Relation.extend = utils.extend; + +utils.addHiddenPropsToTarget(Relation.prototype, { + get canAutoAddLinks() { + return this.add === undefined || !!this.add; + }, + + get relatedCollection() { + return this.mapper.datastore.getCollection(this.relation); + }, + + validateOptions: function validateOptions(related, opts) { + var DOMAIN_ERR = 'new ' + DOMAIN$4; + + var localField = opts.localField; + if (!localField) { + throw utils.err(DOMAIN_ERR, 'opts.localField')(400, 'string', localField); + } + + var foreignKey = opts.foreignKey = opts.foreignKey || opts.localKey; + if (!foreignKey && (opts.type === belongsToType || opts.type === hasOneType)) { + throw utils.err(DOMAIN_ERR, 'opts.foreignKey')(400, 'string', foreignKey); + } + + if (utils.isString(related)) { + opts.relation = related; + if (!utils.isFunction(opts.getRelation)) { + throw utils.err(DOMAIN_ERR, 'opts.getRelation')(400, 'function', opts.getRelation); + } + } else if (related) { + opts.relation = related.name; + } else { + throw utils.err(DOMAIN_ERR, 'related')(400, 'Mapper or string', related); + } + }, + assignTo: function assignTo(mapper) { + this.name = mapper.name; + Object.defineProperty(this, 'mapper', { value: mapper }); + + mapper.relationList || Object.defineProperty(mapper, 'relationList', { value: [] }); + mapper.relationFields || Object.defineProperty(mapper, 'relationFields', { value: [] }); + mapper.relationList.push(this); + mapper.relationFields.push(this.localField); + }, + canFindLinkFor: function canFindLinkFor() { + return !!(this.foreignKey || this.localKey); + }, + getRelation: function getRelation() { + return this.relatedMapper; + }, + getForeignKey: function getForeignKey(record) { + return utils.get(record, this.mapper.idAttribute); + }, + setForeignKey: function setForeignKey(record, relatedRecord) { + if (!record || !relatedRecord) { + return; + } + + this._setForeignKey(record, relatedRecord); + }, + _setForeignKey: function _setForeignKey(record, relatedRecords) { + var _this = this; + + var idAttribute = this.mapper.idAttribute; + + if (!utils.isArray(relatedRecords)) { + relatedRecords = [relatedRecords]; + } + + relatedRecords.forEach(function (relatedRecord) { + utils.set(relatedRecord, _this.foreignKey, utils.get(record, idAttribute)); + }); + }, + getLocalField: function getLocalField(record) { + return utils.get(record, this.localField); + }, + setLocalField: function setLocalField(record, relatedData) { + return utils.set(record, this.localField, relatedData); + }, + getInverse: function getInverse(mapper) { + if (!this.inverse) { + this.findInverseRelation(mapper); + } + + return this.inverse; + }, + findInverseRelation: function findInverseRelation(mapper) { + var _this2 = this; + + this.getRelation().relationList.forEach(function (def) { + if (def.getRelation() === mapper && _this2.isInversedTo(def) && _this2 !== def) { + _this2.inverse = def; + return true; + } + }); + }, + isInversedTo: function isInversedTo(def) { + return !def.foreignKey || def.foreignKey === this.foreignKey; + }, + addLinkedRecords: function addLinkedRecords(records) { + var _this3 = this; + + var datastore = this.mapper.datastore; + + records.forEach(function (record) { + var relatedData = _this3.getLocalField(record); + + if (utils.isFunction(_this3.add)) { + relatedData = _this3.add(datastore, _this3, record); + } else if (relatedData) { + relatedData = _this3.linkRecord(record, relatedData); + } + + var isEmptyLinks = !relatedData || utils.isArray(relatedData) && !relatedData.length; + + if (isEmptyLinks && _this3.canFindLinkFor(record)) { + relatedData = _this3.findExistingLinksFor(record); + } + + if (relatedData) { + _this3.setLocalField(record, relatedData); + } + }); + }, + removeLinkedRecords: function removeLinkedRecords(relatedMapper, records) { + var localField = this.localField; + records.forEach(function (record) { + utils.set(record, localField, undefined); + }); + }, + linkRecord: function linkRecord(record, relatedRecord) { + var relatedId = utils.get(relatedRecord, this.mapper.idAttribute); + + if (relatedId === undefined) { + var unsaved = this.relatedCollection.unsaved(); + if (unsaved.indexOf(relatedRecord) === -1) { + if (this.canAutoAddLinks) { + relatedRecord = this.relatedCollection.add(relatedRecord); + } + } + } else { + if (relatedRecord !== this.relatedCollection.get(relatedId)) { + this.setForeignKey(record, relatedRecord); + + if (this.canAutoAddLinks) { + relatedRecord = this.relatedCollection.add(relatedRecord); + } + } + } + + return relatedRecord; + }, + + + // e.g. user hasMany post via "foreignKey", so find all posts of user + findExistingLinksByForeignKey: function findExistingLinksByForeignKey(id) { + if (id === undefined || id === null) { + return; + } + return this.relatedCollection.filter(defineProperty({}, this.foreignKey, id)); + }, + ensureLinkedDataHasProperType: function ensureLinkedDataHasProperType(props, opts) { + var relatedMapper = this.getRelation(); + var relationData = this.getLocalField(props); + + if (utils.isArray(relationData) && (!relationData.length || relatedMapper.is(relationData[0]))) { + return; + } + + if (relationData && !relatedMapper.is(relationData)) { + utils.set(props, this.localField, relatedMapper.createRecord(relationData, opts)); + } + }, + isRequiresParentId: function isRequiresParentId() { + return false; + }, + isRequiresChildId: function isRequiresChildId() { + return false; + }, + createChildRecord: function createChildRecord(props, relationData, opts) { + var _this4 = this; + + this.setForeignKey(props, relationData); + + return this.createLinked(relationData, opts).then(function (result) { + _this4.setLocalField(props, result); + }); + }, + createLinked: function createLinked(props, opts) { + var create = utils.isArray(props) ? 'createMany' : 'create'; + + return this.getRelation()[create](props, opts); + } +}); + +var BelongsToRelation = Relation.extend({ + getForeignKey: function getForeignKey(record) { + return utils.get(record, this.foreignKey); + }, + _setForeignKey: function _setForeignKey(record, relatedRecord) { + utils.set(record, this.foreignKey, utils.get(relatedRecord, this.getRelation().idAttribute)); + }, + findExistingLinksFor: function findExistingLinksFor(record) { + // console.log('\tBelongsTo#findExistingLinksFor', record) + if (!record) { + return; + } + var relatedId = utils.get(record, this.foreignKey); + if (relatedId !== undefined && relatedId !== null) { + return this.relatedCollection.get(relatedId); + } + }, + isRequiresParentId: function isRequiresParentId() { + return true; + }, + createParentRecord: function createParentRecord(props, opts) { + var _this = this; + + var relationData = this.getLocalField(props); + + return this.createLinked(relationData, opts).then(function (record) { + _this.setForeignKey(props, record); + }); + }, + createChildRecord: function createChildRecord() { + throw new Error('"BelongsTo" relation does not support child creation as it cannot have children.'); + } +}, { + TYPE_NAME: 'belongsTo' +}); + +var HasManyRelation = Relation.extend({ + validateOptions: function validateOptions(related, opts) { + Relation.prototype.validateOptions.call(this, related, opts); + + var localKeys = opts.localKeys, + foreignKeys = opts.foreignKeys, + foreignKey = opts.foreignKey; + + + if (!foreignKey && !localKeys && !foreignKeys) { + throw utils.err('new Relation', 'opts.')(400, 'string', foreignKey); + } + }, + canFindLinkFor: function canFindLinkFor(record) { + var hasForeignKeys = this.foreignKey || this.foreignKeys; + return !!(hasForeignKeys || this.localKeys && utils.get(record, this.localKeys)); + }, + linkRecord: function linkRecord(record, relatedRecords) { + var _this = this; + + var relatedCollection = this.relatedCollection; + var canAutoAddLinks = this.canAutoAddLinks; + var foreignKey = this.foreignKey; + var unsaved = this.relatedCollection.unsaved(); + + return relatedRecords.map(function (relatedRecord) { + var relatedId = relatedCollection.recordId(relatedRecord); + + if (relatedId === undefined && unsaved.indexOf(relatedRecord) === -1 || relatedRecord !== relatedCollection.get(relatedId)) { + if (foreignKey) { + // TODO: slow, could be optimized? But user loses hook + _this.setForeignKey(record, relatedRecord); + } + if (canAutoAddLinks) { + relatedRecord = relatedCollection.add(relatedRecord); + } + } + + return relatedRecord; + }); + }, + findExistingLinksFor: function findExistingLinksFor(record) { + var id = utils.get(record, this.mapper.idAttribute); + var ids = this.localKeys ? utils.get(record, this.localKeys) : null; + var records = void 0; + + if (id !== undefined && this.foreignKey) { + records = this.findExistingLinksByForeignKey(id); + } else if (this.localKeys && ids) { + records = this.findExistingLinksByLocalKeys(ids); + } else if (id !== undefined && this.foreignKeys) { + records = this.findExistingLinksByForeignKeys(id); + } + + if (records && records.length) { + return records; + } + }, + + + // e.g. user hasMany group via "foreignKeys", so find all users of a group + findExistingLinksByLocalKeys: function findExistingLinksByLocalKeys(ids) { + return this.relatedCollection.filter({ + where: defineProperty({}, this.mapper.idAttribute, { + 'in': ids + }) + }); + }, + + + // e.g. group hasMany user via "localKeys", so find all groups that own a user + findExistingLinksByForeignKeys: function findExistingLinksByForeignKeys(id) { + return this.relatedCollection.filter({ + where: defineProperty({}, this.foreignKeys, { + 'contains': id + }) + }); + }, + isRequiresParentId: function isRequiresParentId() { + return !!this.localKeys && this.localKeys.length > 0; + }, + isRequiresChildId: function isRequiresChildId() { + return !!this.foreignKey; + }, + createParentRecord: function createParentRecord(props, opts) { + var _this2 = this; + + var relationData = this.getLocalField(props); + var foreignIdField = this.getRelation().idAttribute; + + return this.createLinked(relationData, opts).then(function (records) { + utils.set(props, _this2.localKeys, records.map(function (record) { + return utils.get(record, foreignIdField); + })); + }); + }, + createLinked: function createLinked(props, opts) { + return this.getRelation().createMany(props, opts); + } +}, { + TYPE_NAME: 'hasMany' +}); + +var HasOneRelation = Relation.extend({ + findExistingLinksFor: function findExistingLinksFor(relatedMapper, record) { + var recordId = utils.get(record, relatedMapper.idAttribute); + var records = this.findExistingLinksByForeignKey(recordId); + + if (records && records.length) { + return records[0]; + } + }, + isRequiresChildId: function isRequiresChildId() { + return true; + } +}, { + TYPE_NAME: 'hasOne' +}); + +[BelongsToRelation, HasManyRelation, HasOneRelation].forEach(function (RelationType) { + Relation[RelationType.TYPE_NAME] = function (related, options) { + return new RelationType(related, options); + }; +}); + +/** + * BelongsTo relation decorator. You probably won't use this directly. + * + * @name module:js-data.belongsTo + * @method + * @param {Mapper} related The relation the target belongs to. + * @param {object} opts Configuration options. + * @param {string} opts.foreignKey The field that holds the primary key of the + * related record. + * @param {string} opts.localField The field that holds a reference to the + * related record object. + * @returns {Function} Invocation function, which accepts the target as the only + * parameter. + */ +var belongsTo = function belongsTo(related, opts) { + return function (mapper) { + Relation.belongsTo(related, opts).assignTo(mapper); + }; +}; + +/** + * HasMany relation decorator. You probably won't use this directly. + * + * @name module:js-data.hasMany + * @method + * @param {Mapper} related The relation of which the target has many. + * @param {object} opts Configuration options. + * @param {string} [opts.foreignKey] The field that holds the primary key of the + * related record. + * @param {string} opts.localField The field that holds a reference to the + * related record object. + * @returns {Function} Invocation function, which accepts the target as the only + * parameter. + */ +var hasMany = function hasMany(related, opts) { + return function (mapper) { + Relation.hasMany(related, opts).assignTo(mapper); + }; +}; + +/** + * HasOne relation decorator. You probably won't use this directly. + * + * @name module:js-data.hasOne + * @method + * @param {Mapper} related The relation of which the target has one. + * @param {object} opts Configuration options. + * @param {string} [opts.foreignKey] The field that holds the primary key of the + * related record. + * @param {string} opts.localField The field that holds a reference to the + * related record object. + * @returns {Function} Invocation function, which accepts the target as the only + * parameter. + */ +var hasOne = function hasOne(related, opts) { + return function (mapper) { + Relation.hasOne(related, opts).assignTo(mapper); + }; +}; + +var DOMAIN$3 = 'Record'; + +var superMethod = function superMethod(mapper, name) { + var store = mapper.datastore; + if (store && store[name]) { + return function () { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return store[name].apply(store, [mapper.name].concat(args)); + }; + } + return mapper[name].bind(mapper); +}; + +// Cache these strings +var creatingPath = 'creating'; +var noValidatePath$1 = 'noValidate'; +var keepChangeHistoryPath = 'keepChangeHistory'; +var previousPath = 'previous'; + +/** + * js-data's Record class. An instance of `Record` corresponds to an in-memory + * representation of a single row or document in a database, Firebase, + * localstorage, etc. Basically, a `Record` instance represents whatever kind of + * entity in your persistence layer that has a primary key. + * + * ```javascript + * import {Record} from 'js-data' + * ``` + * + * @example Record#constructor + * const JSData = require('js-data'); + * const { Record } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Instantiate a plain record + * let record = new Record(); + * console.log('record: ' + JSON.stringify(record)); + * + * // You can supply properties on instantiation + * record = new Record({ name: 'John' }); + * console.log('record: ' + JSON.stringify(record)); + * + * @example Record#constructor2 + * const JSData = require('js-data'); + * const { Mapper } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Instantiate a record that's associated with a Mapper: + * const UserMapper = new Mapper({ name: 'user' }); + * const User = UserMapper.recordClass; + * const user = UserMapper.createRecord({ name: 'John' }); + * const user2 = new User({ name: 'Sally' }); + * console.log('user: ' + JSON.stringify(user)); + * console.log('user2: ' + JSON.stringify(user2)); + * + * @example Record#constructor3 + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * store.defineMapper('user'); + * + * // Instantiate a record that's associated with a store's Mapper + * const user = store.createRecord('user', { name: 'John' }); + * console.log('user: ' + JSON.stringify(user)); + * + * @example Record#constructor4 + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * store.defineMapper('user', { + * schema: { + * properties: { + * name: { type: 'string' } + * } + * } + * }); + * + * // Validate on instantiation + * const user = store.createRecord('user', { name: 1234 }); + * console.log('user: ' + JSON.stringify(user)); + * + * @example Record#constructor5 + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * store.defineMapper('user', { + * schema: { + * properties: { + * name: { type: 'string' } + * } + * } + * }); + * + * // Skip validation on instantiation + * const user = store.createRecord('user', { name: 1234 }, { noValidate: true }); + * console.log('user: ' + JSON.stringify(user)); + * console.log('user.isValid(): ' + user.isValid()); + * + * @class Record + * @extends Component + * @param {object} [props] The initial properties of the new Record instance. + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.noValidate=false] Whether to skip validation on the + * initial properties. + * @param {boolean} [opts.validateOnSet=true] Whether to enable setter + * validation on properties after the Record has been initialized. + * @since 3.0.0 + */ +function Record(props, opts) { + utils.classCallCheck(this, Record); + Settable.call(this); + props || (props = {}); + opts || (opts = {}); + var _set = this._set; + var mapper = this.constructor.mapper; + + _set(creatingPath, true); + _set(noValidatePath$1, !!opts.noValidate); + _set(keepChangeHistoryPath, opts.keepChangeHistory === undefined ? mapper ? mapper.keepChangeHistory : true : opts.keepChangeHistory); + + // Set the idAttribute value first, if it exists. + var id = mapper ? utils.get(props, mapper.idAttribute) : undefined; + if (id !== undefined) { + utils.set(this, mapper.idAttribute, id); + } + + utils.fillIn(this, props); + _set(creatingPath, false); + if (opts.validateOnSet !== undefined) { + _set(noValidatePath$1, !opts.validateOnSet); + } else if (mapper && mapper.validateOnSet !== undefined) { + _set(noValidatePath$1, !mapper.validateOnSet); + } else { + _set(noValidatePath$1, false); + } + _set(previousPath, mapper ? mapper.toJSON(props) : utils.plainCopy(props)); +} + +var Record$1 = Component$1.extend({ + constructor: Record, + + /** + * Returns the {@link Mapper} paired with this record's class, if any. + * + * @method Record#_mapper + * @returns {Mapper} The {@link Mapper} paired with this record's class, if any. + * @since 3.0.0 + */ + _mapper: function _mapper() { + var mapper = this.constructor.mapper; + if (!mapper) { + throw utils.err(DOMAIN$3 + '#_mapper', '')(404, 'mapper'); + } + return mapper; + }, + + + /** + * Lifecycle hook. + * + * @method Record#afterLoadRelations + * @param {string[]} relations The `relations` argument passed to {@link Record#loadRelations}. + * @param {object} opts The `opts` argument passed to {@link Record#loadRelations}. + * @since 3.0.0 + */ + afterLoadRelations: function afterLoadRelations() {}, + + + /** + * Lifecycle hook. + * + * @method Record#beforeLoadRelations + * @param {string[]} relations The `relations` argument passed to {@link Record#loadRelations}. + * @param {object} opts The `opts` argument passed to {@link Record#loadRelations}. + * @since 3.0.0 + */ + beforeLoadRelations: function beforeLoadRelations() {}, + + + /** + * Return the change history of this record since it was instantiated or + * {@link Record#commit} was called. + * + * @method Record#changeHistory + * @since 3.0.0 + */ + changeHistory: function changeHistory() { + return (this._get('history') || []).slice(); + }, + + + /** + * Return changes to this record since it was instantiated or + * {@link Record#commit} was called. + * + * @example Record#changes + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * store.defineMapper('user'); + * const user = store.createRecord('user'); + * console.log('user changes: ' + JSON.stringify(user.changes())); + * user.name = 'John'; + * console.log('user changes: ' + JSON.stringify(user.changes())); + * + * @method Record#changes + * @param [opts] Configuration options. + * @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function. + * @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore. + * @returns {Object} Object describing the changes to this record since it was + * instantiated or its {@link Record#commit} method was last called. + * @since 3.0.0 + */ + changes: function changes(opts) { + opts || (opts = {}); + return utils.diffObjects(typeof this.toJSON === 'function' ? this.toJSON(opts) : this, this._get('previous'), opts); + }, + + + /** + * Make the record's current in-memory state it's only state, with any + * previous property values being set to current values. + * + * @example Record#commit + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * store.defineMapper('user'); + * const user = store.createRecord('user'); + * console.log('user hasChanges: ' + user.hasChanges()); + * user.name = 'John'; + * console.log('user hasChanges: ' + user.hasChanges()); + * user.commit(); + * console.log('user hasChanges: ' + user.hasChanges()); + * + * @method Record#commit + * @param {object} [opts] Configuration options. Passed to {@link Record#toJSON}. + * @since 3.0.0 + */ + commit: function commit(opts) { + this._set('changed'); // unset + this._set('changing', false); + this._set('history', []); // clear history + this._set('previous', this.toJSON(opts)); + }, + + + /** + * Call {@link Mapper#destroy} using this record's primary key. + * + * @example + * import { Container } from 'js-data'; + * import { RethinkDBAdapter } from 'js-data-rethinkdb'; + * + * const store = new Container(); + * store.registerAdapter('rethink', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('user'); + * store.find('user', 1234).then((user) => { + * console.log(user.id); // 1234 + * + * // Destroy this user from the database + * return user.destroy(); + * }); + * + * @method Record#destroy + * @param {object} [opts] Configuration options passed to {@link Mapper#destroy}. + * @returns {Promise} The result of calling {@link Mapper#destroy} with the + * primary key of this record. + * @since 3.0.0 + */ + destroy: function destroy(opts) { + opts || (opts = {}); + var mapper = this._mapper(); + return superMethod(mapper, 'destroy')(utils.get(this, mapper.idAttribute), opts); + }, + + + /** + * Return the value at the given path for this instance. + * + * @example Record#get + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user'); + * + * const user = store.createRecord('user', { name: 'Bob' }); + * console.log('user.get("name"): ' + user.get('name')); + * + * @method Record#get + * @param {string} key Path of value to retrieve. + * @returns {*} Value at path. + * @since 3.0.0 + */ + 'get': function get$$1(key) { + return utils.get(this, key); + }, + + + /** + * Return whether this record has changed since it was instantiated or + * {@link Record#commit} was called. + * + * @example Record#hasChanges + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user'); + * const user = store.createRecord('user'); + * console.log('user hasChanges: ' + user.hasChanges()); + * user.name = 'John'; + * console.log('user hasChanges: ' + user.hasChanges()); + * user.commit(); + * console.log('user hasChanges: ' + user.hasChanges()); + * + * @method Record#hasChanges + * @param [opts] Configuration options. + * @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function. + * @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore. + * @returns {boolean} Return whether the record has changed since it was + * instantiated or since its {@link Record#commit} method was called. + * @since 3.0.0 + */ + hasChanges: function hasChanges(opts) { + var quickHasChanges = !!(this._get('changed') || []).length; + return quickHasChanges || utils.areDifferent(typeof this.toJSON === 'function' ? this.toJSON(opts) : this, this._get('previous'), opts); + }, + + + /** + * Return whether the record is unsaved. Records that have primary keys are + * considered "saved". Records without primary keys are considered "unsaved". + * + * @example Record#isNew + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user'); + * const user = store.createRecord('user', { + * id: 1234 + * }); + * const user2 = store.createRecord('user'); + * console.log('user isNew: ' + user.isNew()); // false + * console.log('user2 isNew: ' + user2.isNew()); // true + * + * @method Record#isNew + * @returns {boolean} Whether the record is unsaved. + * @since 3.0.0 + */ + isNew: function isNew(opts) { + return utils.get(this, this._mapper().idAttribute) === undefined; + }, + + + /** + * Return whether the record in its current state passes validation. + * + * @example Record#isValid + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user', { + * schema: { + * properties: { + * name: { type: 'string' } + * } + * } + * }); + * const user = store.createRecord('user', { + * name: 1234 + * }, { + * noValidate: true // this allows us to put the record into an invalid state + * }); + * console.log('user isValid: ' + user.isValid()); + * user.name = 'John'; + * console.log('user isValid: ' + user.isValid()); + * + * @method Record#isValid + * @param {object} [opts] Configuration options. Passed to {@link Mapper#validate}. + * @returns {boolean} Whether the record in its current state passes + * validation. + * @since 3.0.0 + */ + isValid: function isValid(opts) { + return !this._mapper().validate(this, opts); + }, + removeInverseRelation: function removeInverseRelation(currentParent, id, inverseDef, idAttribute) { + var _this = this; + + if (inverseDef.type === hasOneType) { + safeSetLink(currentParent, inverseDef.localField, undefined); + } else if (inverseDef.type === hasManyType) { + // e.g. remove comment from otherPost.comments + var children = utils.get(currentParent, inverseDef.localField); + if (id === undefined) { + utils.remove(children, function (child) { + return child === _this; + }); + } else { + utils.remove(children, function (child) { + return child === _this || id === utils.get(child, idAttribute); + }); + } + } + }, + setupInverseRelation: function setupInverseRelation(record, id, inverseDef, idAttribute) { + var _this2 = this; + + // Update (set) inverse relation + if (inverseDef.type === hasOneType) { + // e.g. someUser.profile = profile + safeSetLink(record, inverseDef.localField, this); + } else if (inverseDef.type === hasManyType) { + // e.g. add comment to somePost.comments + var children = utils.get(record, inverseDef.localField); + if (id === undefined) { + utils.noDupeAdd(children, this, function (child) { + return child === _this2; + }); + } else { + utils.noDupeAdd(children, this, function (child) { + return child === _this2 || id === utils.get(child, idAttribute); + }); + } + } + }, + + + /** + * Lazy load relations of this record, to be attached to the record once their + * loaded. + * + * @example + * import { Container } from 'js-data'; + * import { RethinkDBAdapter } from 'js-data-rethinkdb'; + * + * const store = new Container(); + * store.registerAdapter('rethink', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('user', { + * relations: { + * hasMany: { + * post: { + * localField: 'posts', + * foreignKey: 'user_id' + * } + * } + * } + * }); + * store.defineMapper('post', { + * relations: { + * belongsTo: { + * user: { + * localField: 'user', + * foreignKey: 'user_id' + * } + * } + * } + * }); + * store.find('user', 1234).then((user) => { + * console.log(user.id); // 1234 + * + * // Load the user's post relations + * return user.loadRelations(['post']); + * }).then((user) => { + * console.log(user.posts); // [{...}, {...}, ...] + * }); + * + * @method Record#loadRelations + * @param {string[]} [relations] List of relations to load. Can use localField + * names or Mapper names to pick relations. + * @param {object} [opts] Configuration options. + * @returns {Promise} Resolves with the record, with the loaded relations now + * attached. + * @since 3.0.0 + */ + loadRelations: function loadRelations(relations, opts) { + var _this3 = this; + + var op = void 0; + var mapper = this._mapper(); + + // Default values for arguments + relations || (relations = []); + if (utils.isString(relations)) { + relations = [relations]; + } + opts || (opts = {}); + opts.with = relations; + + // Fill in "opts" with the Model's configuration + utils._(opts, mapper); + opts.adapter = mapper.getAdapterName(opts); + + // beforeLoadRelations lifecycle hook + op = opts.op = 'beforeLoadRelations'; + return utils.resolve(this[op](relations, opts)).then(function () { + // Now delegate to the adapter + op = opts.op = 'loadRelations'; + mapper.dbg(op, _this3, relations, opts); + var tasks = []; + var task = void 0; + utils.forEachRelation(mapper, opts, function (def, optsCopy) { + var relatedMapper = def.getRelation(); + optsCopy.raw = false; + if (utils.isFunction(def.load)) { + task = def.load(mapper, def, _this3, opts); + } else if (def.type === 'hasMany' || def.type === 'hasOne') { + if (def.foreignKey) { + task = superMethod(relatedMapper, 'findAll')(defineProperty({}, def.foreignKey, utils.get(_this3, mapper.idAttribute)), optsCopy).then(function (relatedData) { + if (def.type === 'hasOne') { + return relatedData.length ? relatedData[0] : undefined; + } + return relatedData; + }); + } else if (def.localKeys) { + task = superMethod(relatedMapper, 'findAll')({ + where: defineProperty({}, relatedMapper.idAttribute, { + 'in': utils.get(_this3, def.localKeys) + }) + }); + } else if (def.foreignKeys) { + task = superMethod(relatedMapper, 'findAll')({ + where: defineProperty({}, def.foreignKeys, { + 'contains': utils.get(_this3, mapper.idAttribute) + }) + }, opts); + } + } else if (def.type === 'belongsTo') { + var key = utils.get(_this3, def.foreignKey); + if (utils.isSorN(key)) { + task = superMethod(relatedMapper, 'find')(key, optsCopy); + } + } + if (task) { + task = task.then(function (relatedData) { + def.setLocalField(_this3, relatedData); + }); + tasks.push(task); + } + }); + return Promise.all(tasks); + }).then(function () { + // afterLoadRelations lifecycle hook + op = opts.op = 'afterLoadRelations'; + return utils.resolve(_this3[op](relations, opts)).then(function () { + return _this3; + }); + }); + }, + + + /** + * Return the properties with which this record was instantiated. + * + * @example Record#previous + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user'); + * const user = store.createRecord('user', { + * name: 'William' + * }); + * console.log('user previous: ' + JSON.stringify(user.previous())); + * user.name = 'Bob'; + * console.log('user previous: ' + JSON.stringify(user.previous())); + * user.commit(); + * console.log('user previous: ' + JSON.stringify(user.previous())); + * + * @method Record#previous + * @param {string} [key] If specified, return just the initial value of the + * given key. + * @returns {Object} The initial properties of this record. + * @since 3.0.0 + */ + previous: function previous(key) { + if (key) { + return this._get('previous.' + key); + } + return this._get('previous'); + }, + + + /** + * Revert changes to this record back to the properties it had when it was + * instantiated. + * + * @example Record#revert + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user'); + * const user = store.createRecord('user', { + * name: 'William' + * }); + * console.log('user: ' + JSON.stringify(user)); + * user.name = 'Bob'; + * console.log('user: ' + JSON.stringify(user)); + * user.revert(); + * console.log('user: ' + JSON.stringify(user)); + * + * @method Record#revert + * @param {object} [opts] Configuration options. + * @param {string[]} [opts.preserve] Array of strings or Regular Expressions + * denoting properties that should not be reverted. + * @since 3.0.0 + */ + revert: function revert(opts) { + var _this4 = this; + + var previous = this._get('previous'); + opts || (opts = {}); + opts.preserve || (opts.preserve = []); + utils.forOwn(this, function (value, key) { + if (key !== _this4._mapper().idAttribute && !previous.hasOwnProperty(key) && _this4.hasOwnProperty(key) && opts.preserve.indexOf(key) === -1) { + delete _this4[key]; + } + }); + utils.forOwn(previous, function (value, key) { + if (opts.preserve.indexOf(key) === -1) { + _this4[key] = value; + } + }); + this.commit(); + }, + + + /** + * Delegates to {@link Mapper#create} or {@link Mapper#update}. + * + * @example + * import { Container } from 'js-data'; + * import { RethinkDBAdapter } from 'js-data-rethinkdb'; + * + * const store = new Container(); + * store.registerAdapter('rethink', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('session'); + * const session = store.createRecord('session', { topic: 'Node.js' }); + * + * // Create a new record in the database + * session.save().then(() => { + * console.log(session.id); // 1234 + * + * session.skill_level = 'beginner'; + * + * // Update the record in the database + * return session.save(); + * }); + * + * @method Record#save + * @param {object} [opts] Configuration options. See {@link Mapper#create} and + * {@link Mapper#update}. + * @param {boolean} [opts.changesOnly] Equality function. Default uses `===`. + * @param {Function} [opts.equalsFn] Passed to {@link Record#changes} when + * `opts.changesOnly` is `true`. + * @param {array} [opts.ignore] Passed to {@link Record#changes} when + * `opts.changesOnly` is `true`. + * @returns {Promise} The result of calling {@link Mapper#create} or + * {@link Mapper#update}. + * @since 3.0.0 + */ + save: function save(opts) { + var _this5 = this; + + opts || (opts = {}); + var mapper = this._mapper(); + var id = utils.get(this, mapper.idAttribute); + var props = this; + + var postProcess = function postProcess(result) { + var record = opts.raw ? result.data : result; + if (record) { + utils.deepMixIn(_this5, record); + _this5.commit(); + } + return result; + }; + + if (id === undefined) { + return superMethod(mapper, 'create')(props, opts).then(postProcess); + } + if (opts.changesOnly) { + var changes = this.changes(opts); + props = {}; + utils.fillIn(props, changes.added); + utils.fillIn(props, changes.changed); + } + return superMethod(mapper, 'update')(id, props, opts).then(postProcess); + }, + + + /** + * Set the value for a given key, or the values for the given keys if "key" is + * an object. Triggers change events on those properties that have `track: true` + * in {@link Mapper#schema}. + * + * @example Record#set + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user'); + * + * const user = store.createRecord('user'); + * console.log('user: ' + JSON.stringify(user)); + * + * user.set('name', 'Bob'); + * console.log('user: ' + JSON.stringify(user)); + * + * user.set({ age: 30, role: 'admin' }); + * console.log('user: ' + JSON.stringify(user)); + * + * @fires Record#change + * @method Record#set + * @param {(string|Object)} key Key to set or hash of key-value pairs to set. + * @param {*} [value] Value to set for the given key. + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.silent=false] Whether to trigger change events. + * @since 3.0.0 + */ + 'set': function set$$1(key, value, opts) { + if (utils.isObject(key)) { + opts = value; + } + opts || (opts = {}); + if (opts.silent) { + this._set('silent', true); + } + utils.set(this, key, value); + if (!this._get('eventId')) { + this._set('silent'); // unset + } + }, + + + /** + * Return a plain object representation of this record. If the class from + * which this record was created has a Mapper, then {@link Mapper#toJSON} will + * be called with this record instead. + * + * @example Record#toJSON + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user', { + * schema: { + * properties: { + * name: { type: 'string' } + * } + * } + * }); + * + * const user = store.createRecord('user', { + * name: 'John', + * $$hashKey: '1234' + * }); + * console.log('user: ' + JSON.stringify(user.toJSON())); + * + * @method Record#toJSON + * @param {object} [opts] Configuration options. + * @param {string[]} [opts.with] Array of relation names or relation fields + * to include in the representation. Only available as an option if the class + * from which this record was created has a Mapper and this record resides in + * an instance of {@link DataStore}. + * @returns {Object} Plain object representation of this record. + * @since 3.0.0 + */ + toJSON: function toJSON(opts) { + var mapper = this.constructor.mapper; + if (mapper) { + return mapper.toJSON(this, opts); + } else { + var json = {}; + utils.forOwn(this, function (prop, key) { + json[key] = utils.plainCopy(prop); + }); + return json; + } + }, + + + /** + * Unset the value for a given key. Triggers change events on those properties + * that have `track: true` in {@link Mapper#schema}. + * + * @example Record#unset + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user'); + * + * const user = store.createRecord('user', { + * name: 'John' + * }); + * console.log('user: ' + JSON.stringify(user)); + * + * user.unset('name'); + * console.log('user: ' + JSON.stringify(user)); + * + * @method Record#unset + * @param {string} key Key to unset. + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.silent=false] Whether to trigger change events. + * @since 3.0.0 + */ + unset: function unset(key, opts) { + this.set(key, undefined, opts); + }, + + + /** + * Validate this record based on its current properties. + * + * @example Record#validate + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user', { + * schema: { + * properties: { + * name: { type: 'string' } + * } + * } + * }); + * const user = store.createRecord('user', { + * name: 1234 + * }, { + * noValidate: true // this allows us to put the record into an invalid state + * }); + * console.log('user validation: ' + JSON.stringify(user.validate())); + * user.name = 'John'; + * console.log('user validation: ' + user.validate()); + * + * @method Record#validate + * @param {object} [opts] Configuration options. Passed to {@link Mapper#validate}. + * @returns {*} Array of errors or `undefined` if no errors. + * @since 3.0.0 + */ + validate: function validate(opts) { + return this._mapper().validate(this, opts); + } +}, { + creatingPath: creatingPath, + noValidatePath: noValidatePath$1, + keepChangeHistoryPath: keepChangeHistoryPath, + previousPath: previousPath +}); + +/** + * Allow records to emit events. + * + * An record's registered listeners are stored in the record's private data. + */ +utils.eventify(Record.prototype, function () { + return this._get('events'); +}, function (value) { + this._set('events', value); +}); + +/** + * Fired when a record changes. Only works for records that have tracked fields. + * See {@link Record~changeListener} on how to listen for this event. + * + * @event Record#change + * @see Record~changeListener + */ + +/** + * Callback signature for the {@link Record#event:change} event. + * + * @example + * function onChange (record, changes) { + * // do something + * } + * record.on('change', onChange); + * + * @callback Record~changeListener + * @param {Record} The Record that changed. + * @param {object} The changes. + * @see Record#event:change + * @since 3.0.0 + */ + +/** + * Create a subclass of this Record: + * @example Record.extend + * const JSData = require('js-data'); + * const { Record } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomRecordClass extends Record { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customRecord = new CustomRecordClass(); + * console.log(customRecord.foo()); + * console.log(CustomRecordClass.beep()); + * + * // Extend the class using alternate method. + * const OtherRecordClass = Record.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherRecord = new OtherRecordClass(); + * console.log(otherRecord.foo()); + * console.log(OtherRecordClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherRecordClass () { + * Record.call(this); + * this.created_at = new Date().getTime(); + * } + * Record.extend({ + * constructor: AnotherRecordClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const anotherRecord = new AnotherRecordClass(); + * console.log(anotherRecord.created_at); + * console.log(anotherRecord.foo()); + * console.log(AnotherRecordClass.beep()); + * + * @method Record.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this Record class. + * @since 3.0.0 + */ + +function sort(a, b, hashCode) { + // Short-circuit comparison if a and b are strictly equal + // This is absolutely necessary for indexed objects that + // don't have the idAttribute field + if (a === b) { + return 0; + } + if (hashCode) { + a = hashCode(a); + b = hashCode(b); + } + if (a === null && b === null || a === undefined && b === undefined) { + return -1; + } + + if (a === null || a === undefined) { + return -1; + } + + if (b === null || b === undefined) { + return 1; + } + + if (a < b) { + return -1; + } + + if (a > b) { + return 1; + } + + return 0; +} + +function insertAt(array, index, value) { + array.splice(index, 0, value); + return array; +} + +function removeAt(array, index) { + array.splice(index, 1); + return array; +} + +function binarySearch(array, value, field) { + var lo = 0; + var hi = array.length; + var compared = void 0; + var mid = void 0; + + while (lo < hi) { + mid = (lo + hi) / 2 | 0; + compared = sort(value, array[mid], field); + if (compared === 0) { + return { + found: true, + index: mid + }; + } else if (compared < 0) { + hi = mid; + } else { + lo = mid + 1; + } + } + + return { + found: false, + index: hi + }; +} + +// Copyright (c) 2015, InternalFX. + +// Permission to use, copy, modify, and/or distribute this software for any purpose with or +// without fee is hereby granted, provided that the above copyright notice and this permission +// notice appear in all copies. + +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO +// THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT +// SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR +// ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE +// USE OR PERFORMANCE OF THIS SOFTWARE. + +// Modifications +// Copyright 2015-2016 Jason Dobry +// +// Summary of modifications: +// Reworked dependencies so as to re-use code already in js-data +// Removed unused code +function Index(fieldList, opts) { + utils.classCallCheck(this, Index); + fieldList || (fieldList = []); + + if (!utils.isArray(fieldList)) { + throw new Error('fieldList must be an array.'); + } + + opts || (opts = {}); + this.fieldList = fieldList; + this.fieldGetter = opts.fieldGetter; + this.hashCode = opts.hashCode; + this.isIndex = true; + this.keys = []; + this.values = []; +} + +utils.addHiddenPropsToTarget(Index.prototype, { + 'set': function set(keyList, value) { + if (!utils.isArray(keyList)) { + keyList = [keyList]; + } + + var key = keyList.shift() || undefined; + var pos = binarySearch(this.keys, key); + + if (keyList.length === 0) { + if (pos.found) { + var dataLocation = binarySearch(this.values[pos.index], value, this.hashCode); + if (!dataLocation.found) { + insertAt(this.values[pos.index], dataLocation.index, value); + } + } else { + insertAt(this.keys, pos.index, key); + insertAt(this.values, pos.index, [value]); + } + } else { + if (pos.found) { + this.values[pos.index].set(keyList, value); + } else { + insertAt(this.keys, pos.index, key); + var newIndex = new Index([], { hashCode: this.hashCode }); + newIndex.set(keyList, value); + insertAt(this.values, pos.index, newIndex); + } + } + }, + 'get': function get(keyList) { + if (!utils.isArray(keyList)) { + keyList = [keyList]; + } + + var key = keyList.shift() || undefined; + var pos = binarySearch(this.keys, key); + + if (keyList.length === 0) { + if (pos.found) { + if (this.values[pos.index].isIndex) { + return this.values[pos.index].getAll(); + } else { + return this.values[pos.index].slice(); + } + } else { + return []; + } + } else { + if (pos.found) { + return this.values[pos.index].get(keyList); + } else { + return []; + } + } + }, + getAll: function getAll(opts) { + opts || (opts = {}); + var results = []; + var values = this.values; + if (opts.order === 'desc') { + for (var i = values.length - 1; i >= 0; i--) { + var value = values[i]; + if (value.isIndex) { + results = results.concat(value.getAll(opts)); + } else { + results = results.concat(value); + } + } + } else { + for (var _i = 0; _i < values.length; _i++) { + var _value = values[_i]; + if (_value.isIndex) { + results = results.concat(_value.getAll(opts)); + } else { + results = results.concat(_value); + } + } + } + return results; + }, + visitAll: function visitAll(cb, thisArg) { + this.values.forEach(function (value) { + if (value.isIndex) { + value.visitAll(cb, thisArg); + } else { + value.forEach(cb, thisArg); + } + }); + }, + between: function between(leftKeys, rightKeys, opts) { + opts || (opts = {}); + if (!utils.isArray(leftKeys)) { + leftKeys = [leftKeys]; + } + if (!utils.isArray(rightKeys)) { + rightKeys = [rightKeys]; + } + utils.fillIn(opts, { + leftInclusive: true, + rightInclusive: false, + limit: undefined, + offset: 0 + }); + + var results = this._between(leftKeys, rightKeys, opts); + + if (opts.limit) { + return results.slice(opts.offset, opts.limit + opts.offset); + } else { + return results.slice(opts.offset); + } + }, + _between: function _between(leftKeys, rightKeys, opts) { + var results = []; + + var leftKey = leftKeys.shift(); + var rightKey = rightKeys.shift(); + + var pos = void 0; + + if (leftKey !== undefined) { + pos = binarySearch(this.keys, leftKey); + } else { + pos = { + found: false, + index: 0 + }; + } + + if (leftKeys.length === 0) { + if (pos.found && opts.leftInclusive === false) { + pos.index += 1; + } + + for (var i = pos.index; i < this.keys.length; i += 1) { + if (rightKey !== undefined) { + if (opts.rightInclusive) { + if (this.keys[i] > rightKey) { + break; + } + } else { + if (this.keys[i] >= rightKey) { + break; + } + } + } + + if (this.values[i].isIndex) { + results = results.concat(this.values[i].getAll()); + } else { + results = results.concat(this.values[i]); + } + + if (opts.limit) { + if (results.length >= opts.limit + opts.offset) { + break; + } + } + } + } else { + for (var _i2 = pos.index; _i2 < this.keys.length; _i2 += 1) { + var currKey = this.keys[_i2]; + if (currKey > rightKey) { + break; + } + + if (this.values[_i2].isIndex) { + if (currKey === leftKey) { + results = results.concat(this.values[_i2]._between(utils.copy(leftKeys), rightKeys.map(function () { + return undefined; + }), opts)); + } else if (currKey === rightKey) { + results = results.concat(this.values[_i2]._between(leftKeys.map(function () { + return undefined; + }), utils.copy(rightKeys), opts)); + } else { + results = results.concat(this.values[_i2].getAll()); + } + } else { + results = results.concat(this.values[_i2]); + } + + if (opts.limit) { + if (results.length >= opts.limit + opts.offset) { + break; + } + } + } + } + + if (opts.limit) { + return results.slice(0, opts.limit + opts.offset); + } else { + return results; + } + }, + peek: function peek() { + if (this.values.length) { + if (this.values[0].isIndex) { + return this.values[0].peek(); + } else { + return this.values[0]; + } + } + return []; + }, + clear: function clear() { + this.keys = []; + this.values = []; + }, + insertRecord: function insertRecord(data) { + var keyList = this.fieldList.map(function (field) { + if (utils.isFunction(field)) { + return field(data) || undefined; + } else { + return data[field] || undefined; + } + }); + this.set(keyList, data); + }, + removeRecord: function removeRecord(data) { + var _this = this; + + var removed = void 0; + var isUnique = this.hashCode(data) !== undefined; + this.values.forEach(function (value, i) { + if (value.isIndex) { + if (value.removeRecord(data)) { + if (value.keys.length === 0) { + removeAt(_this.keys, i); + removeAt(_this.values, i); + } + removed = true; + return false; + } + } else { + var dataLocation = {}; + if (_this.keys[i] === undefined || !isUnique) { + for (var j = value.length - 1; j >= 0; j--) { + if (value[j] === data) { + dataLocation = { + found: true, + index: j + }; + break; + } + } + } else if (isUnique) { + dataLocation = binarySearch(value, data, _this.hashCode); + } + if (dataLocation.found) { + removeAt(value, dataLocation.index); + if (value.length === 0) { + removeAt(_this.keys, i); + removeAt(_this.values, i); + } + removed = true; + return false; + } + } + }); + return removed ? data : undefined; + }, + updateRecord: function updateRecord(data) { + var removed = this.removeRecord(data); + if (removed !== undefined) { + this.insertRecord(data); + } + } +}); + +var noValidatePath = Record$1.noValidatePath; + + +var DOMAIN$1 = 'Collection'; + +var COLLECTION_DEFAULTS = { + /** + * Whether to call {@link Record#commit} on records that are added to the + * collection and already exist in the collection. + * + * @name Collection#commitOnMerge + * @type {boolean} + * @default true + */ + commitOnMerge: true, + + /** + * Whether record events should bubble up and be emitted by the collection. + * + * @name Collection#emitRecordEvents + * @type {boolean} + * @default true + */ + emitRecordEvents: true, + + /** + * Field to be used as the unique identifier for records in this collection. + * Defaults to `"id"` unless {@link Collection#mapper} is set, in which case + * this will default to {@link Mapper#idAttribute}. + * + * @name Collection#idAttribute + * @type {string} + * @default "id" + */ + idAttribute: 'id', + + /** + * What to do when inserting a record into this Collection that shares a + * primary key with a record already in this Collection. + * + * Possible values: + * merge + * replace + * skip + * + * Merge: + * + * Recursively shallow copy properties from the new record onto the existing + * record. + * + * Replace: + * + * Shallow copy top-level properties from the new record onto the existing + * record. Any top-level own properties of the existing record that are _not_ + * on the new record will be removed. + * + * Skip: + * + * Ignore new record, keep existing record. + * + * @name Collection#onConflict + * @type {string} + * @default "merge" + */ + onConflict: 'merge' + + /** + * An ordered set of {@link Record} instances. + * + * @example Collection#constructor + * // import { Collection, Record } from 'js-data'; + * const JSData = require('js-data'); + * const {Collection, Record} = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const user1 = new Record({ id: 1 }); + * const user2 = new Record({ id: 2 }); + * const UserCollection = new Collection([user1, user2]); + * console.log(UserCollection.get(1) === user1); + * + * @class Collection + * @extends Component + * @param {array} [records] Initial set of records to insert into the + * collection. + * @param {object} [opts] Configuration options. + * @param {string} [opts.commitOnMerge] See {@link Collection#commitOnMerge}. + * @param {string} [opts.idAttribute] See {@link Collection#idAttribute}. + * @param {string} [opts.onConflict="merge"] See {@link Collection#onConflict}. + * @param {string} [opts.mapper] See {@link Collection#mapper}. + * @since 3.0.0 + */ +};function Collection(records, opts) { + utils.classCallCheck(this, Collection); + Component$1.call(this, opts); + + if (records && !utils.isArray(records)) { + opts = records; + records = []; + } + if (utils.isString(opts)) { + opts = { idAttribute: opts }; + } + + // Default values for arguments + records || (records = []); + opts || (opts = {}); + + Object.defineProperties(this, { + /** + * Default Mapper for this collection. Optional. If a Mapper is provided, then + * the collection will use the {@link Mapper#idAttribute} setting, and will + * wrap records in {@link Mapper#recordClass}. + * + * @example Collection#mapper + * const JSData = require('js-data'); + * const {Collection, Mapper} = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * class MyMapperClass extends Mapper { + * foo () { return 'bar'; } + * } + * const myMapper = new MyMapperClass({ name: 'myMapper' }); + * const collection = new Collection(null, { mapper: myMapper }); + * + * @name Collection#mapper + * @type {Mapper} + * @default null + * @since 3.0.0 + */ + mapper: { + value: undefined, + writable: true + }, + // Query class used by this collection + queryClass: { + value: undefined, + writable: true + } + }); + + // Apply user-provided configuration + utils.fillIn(this, opts); + // Fill in any missing options with the defaults + utils.fillIn(this, utils.copy(COLLECTION_DEFAULTS)); + + if (!this.queryClass) { + this.queryClass = Query$1; + } + + var idAttribute = this.recordId(); + + Object.defineProperties(this, { + /** + * The main index, which uses @{link Collection#recordId} as the key. + * + * @name Collection#index + * @type {Index} + */ + index: { + value: new Index([idAttribute], { + hashCode: function hashCode(obj) { + return utils.get(obj, idAttribute); + } + }) + }, + + /** + * Object that holds the secondary indexes of this collection. + * + * @name Collection#indexes + * @type {Object.} + */ + indexes: { + value: {} + } + }); + + // Insert initial data into the collection + if (utils.isObject(records) || utils.isArray(records) && records.length) { + this.add(records); + } +} + +var Collection$1 = Component$1.extend({ + constructor: Collection, + + /** + * Used to bind to events emitted by records in this Collection. + * + * @method Collection#_onRecordEvent + * @since 3.0.0 + * @private + * @param {...*} [arg] Args passed to {@link Collection#emit}. + */ + _onRecordEvent: function _onRecordEvent() { + if (this.emitRecordEvents) { + this.emit.apply(this, arguments); + } + }, + + + /** + * Insert the provided record or records. + * + * If a record is already in the collection then the provided record will + * either merge with or replace the existing record based on the value of the + * `onConflict` option. + * + * The collection's secondary indexes will be updated as each record is + * visited. + * + * @method Collection#add + * @since 3.0.0 + * @param {(Object|Object[]|Record|Record[])} data The record or records to insert. + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.commitOnMerge=true] See {@link Collection#commitOnMerge}. + * @param {boolean} [opts.noValidate] See {@link Record#noValidate}. + * @param {string} [opts.onConflict] See {@link Collection#onConflict}. + * @returns {(Object|Object[]|Record|Record[])} The added record or records. + */ + add: function add(records, opts) { + var _this = this; + + // Default values for arguments + opts || (opts = {}); + + // Fill in "opts" with the Collection's configuration + utils._(opts, this); + records = this.beforeAdd(records, opts) || records; + + // Track whether just one record or an array of records is being inserted + var singular = false; + var idAttribute = this.recordId(); + if (!utils.isArray(records)) { + if (utils.isObject(records)) { + records = [records]; + singular = true; + } else { + throw utils.err(DOMAIN$1 + '#add', 'records')(400, 'object or array', records); + } + } + + // Map the provided records to existing records. + // New records will be inserted. If any records map to existing records, + // they will be merged into the existing records according to the onConflict + // option. + records = records.map(function (record) { + var id = _this.recordId(record); + // Grab existing record if there is one + var existing = id === undefined ? id : _this.get(id); + // If the currently visited record is just a reference to an existing + // record, then there is nothing to be done. Exit early. + if (record === existing) { + return existing; + } + + if (existing) { + // Here, the currently visited record corresponds to a record already + // in the collection, so we need to merge them + var onConflict = opts.onConflict || _this.onConflict; + if (onConflict !== 'merge' && onConflict !== 'replace' && onConflict !== 'skip') { + throw utils.err(DOMAIN$1 + '#add', 'opts.onConflict')(400, 'one of (merge, replace, skip)', onConflict, true); + } + var existingNoValidate = existing._get(noValidatePath); + if (opts.noValidate) { + // Disable validation + existing._set(noValidatePath, true); + } + if (onConflict === 'merge') { + utils.deepMixIn(existing, record); + } else if (onConflict === 'replace') { + utils.forOwn(existing, function (value, key) { + if (key !== idAttribute && record[key] === undefined) { + existing[key] = undefined; + } + }); + existing.set(record); + } // else if(onConflict === 'skip'){ do nothing } + + if (opts.noValidate) { + // Restore previous `noValidate` value + existing._set(noValidatePath, existingNoValidate); + } + record = existing; + if (opts.commitOnMerge && utils.isFunction(record.commit)) { + record.commit(); + } + // Update all indexes in the collection + _this.updateIndexes(record); + } else { + // Here, the currently visted record does not correspond to any record + // in the collection, so (optionally) instantiate this record and insert + // it into the collection + record = _this.mapper ? _this.mapper.createRecord(record, opts) : record; + _this.index.insertRecord(record); + utils.forOwn(_this.indexes, function (index, name) { + index.insertRecord(record); + }); + if (record && utils.isFunction(record.on)) { + record.on('all', _this._onRecordEvent, _this); + } + } + return record; + }); + // Finally, return the inserted data + var result = singular ? records[0] : records; + if (!opts.silent) { + this.emit('add', result); + } + return this.afterAdd(records, opts, result) || result; + }, + + + /** + * Lifecycle hook called by {@link Collection#add}. If this method returns a + * value then {@link Collection#add} will return that same value. + * + * @method Collection#method + * @since 3.0.0 + * @param {(Object|Object[]|Record|Record[])} result The record or records + * that were added to this Collection by {@link Collection#add}. + * @param {object} opts The `opts` argument passed to {@link Collection#add}. + */ + afterAdd: function afterAdd() {}, + + + /** + * Lifecycle hook called by {@link Collection#remove}. If this method returns + * a value then {@link Collection#remove} will return that same value. + * + * @method Collection#afterRemove + * @since 3.0.0 + * @param {(string|number)} id The `id` argument passed to {@link Collection#remove}. + * @param {object} opts The `opts` argument passed to {@link Collection#remove}. + * @param {object} record The result that will be returned by {@link Collection#remove}. + */ + afterRemove: function afterRemove() {}, + + + /** + * Lifecycle hook called by {@link Collection#removeAll}. If this method + * returns a value then {@link Collection#removeAll} will return that same + * value. + * + * @method Collection#afterRemoveAll + * @since 3.0.0 + * @param {object} query The `query` argument passed to {@link Collection#removeAll}. + * @param {object} opts The `opts` argument passed to {@link Collection#removeAll}. + * @param {object} records The result that will be returned by {@link Collection#removeAll}. + */ + afterRemoveAll: function afterRemoveAll() {}, + + + /** + * Lifecycle hook called by {@link Collection#add}. If this method returns a + * value then the `records` argument in {@link Collection#add} will be + * re-assigned to the returned value. + * + * @method Collection#beforeAdd + * @since 3.0.0 + * @param {(Object|Object[]|Record|Record[])} records The `records` argument passed to {@link Collection#add}. + * @param {object} opts The `opts` argument passed to {@link Collection#add}. + */ + beforeAdd: function beforeAdd() {}, + + + /** + * Lifecycle hook called by {@link Collection#remove}. + * + * @method Collection#beforeRemove + * @since 3.0.0 + * @param {(string|number)} id The `id` argument passed to {@link Collection#remove}. + * @param {object} opts The `opts` argument passed to {@link Collection#remove}. + */ + beforeRemove: function beforeRemove() {}, + + + /** + * Lifecycle hook called by {@link Collection#removeAll}. + * + * @method Collection#beforeRemoveAll + * @since 3.0.0 + * @param {object} query The `query` argument passed to {@link Collection#removeAll}. + * @param {object} opts The `opts` argument passed to {@link Collection#removeAll}. + */ + beforeRemoveAll: function beforeRemoveAll() {}, + + + /** + * Find all records between two boundaries. + * + * Shortcut for `collection.query().between(18, 30, { index: 'age' }).run()` + * + * @example + * // Get all users ages 18 to 30 + * const users = collection.between(18, 30, { index: 'age' }); + * + * @example + * // Same as above + * const users = collection.between([18], [30], { index: 'age' }); + * + * @method Collection#between + * @since 3.0.0 + * @param {array} leftKeys Keys defining the left boundary. + * @param {array} rightKeys Keys defining the right boundary. + * @param {object} [opts] Configuration options. + * @param {string} [opts.index] Name of the secondary index to use in the + * query. If no index is specified, the main index is used. + * @param {boolean} [opts.leftInclusive=true] Whether to include records + * on the left boundary. + * @param {boolean} [opts.rightInclusive=false] Whether to include records + * on the left boundary. + * @param {boolean} [opts.limit] Limit the result to a certain number. + * @param {boolean} [opts.offset] The number of resulting records to skip. + * @returns {Object[]|Record[]} The result. + */ + between: function between(leftKeys, rightKeys, opts) { + return this.query().between(leftKeys, rightKeys, opts).run(); + }, + + + /** + * Create a new secondary index on the contents of the collection. + * + * @example + * // Index users by age + * collection.createIndex('age'); + * + * @example + * // Index users by status and role + * collection.createIndex('statusAndRole', ['status', 'role']); + * + * @method Collection#createIndex + * @since 3.0.0 + * @param {string} name The name of the new secondary index. + * @param {string[]} [fieldList] Array of field names to use as the key or + * compound key of the new secondary index. If no fieldList is provided, then + * the name will also be the field that is used to index the collection. + */ + createIndex: function createIndex(name, fieldList, opts) { + var _this2 = this; + + if (utils.isString(name) && fieldList === undefined) { + fieldList = [name]; + } + opts || (opts = {}); + opts.hashCode || (opts.hashCode = function (obj) { + return _this2.recordId(obj); + }); + var index = this.indexes[name] = new Index(fieldList, opts); + this.index.visitAll(index.insertRecord, index); + }, + + + /** + * Find the record or records that match the provided query or pass the + * provided filter function. + * + * Shortcut for `collection.query().filter(queryOrFn[, thisArg]).run()` + * + * @example Collection#filter + * const JSData = require('js-data'); + * const { Collection } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const collection = new Collection([ + * { id: 1, status: 'draft', created_at_timestamp: new Date().getTime() } + * ]); + * + * // Get the draft posts created less than three months ago + * let posts = collection.filter({ + * where: { + * status: { + * '==': 'draft' + * }, + * created_at_timestamp: { + * '>=': (new Date().getTime() - (1000 \* 60 \* 60 \* 24 \* 30 \* 3)) // 3 months ago + * } + * } + * }); + * console.log(posts); + * + * // Use a custom filter function + * posts = collection.filter((post) => post.id % 2 === 0); + * + * @method Collection#filter + * @param {(Object|Function)} [queryOrFn={}] Selection query or filter + * function. + * @param {object} [thisArg] Context to which to bind `queryOrFn` if + * `queryOrFn` is a function. + * @returns {Array} The result. + * @see query + * @since 3.0.0 + */ + filter: function filter(query, thisArg) { + return this.query().filter(query, thisArg).run(); + }, + + + /** + * Iterate over all records. + * + * @example + * collection.forEach(function (record) { + * // do something + * }); + * + * @method Collection#forEach + * @since 3.0.0 + * @param {Function} forEachFn Iteration function. + * @param {*} [thisArg] Context to which to bind `forEachFn`. + * @returns {Array} The result. + */ + forEach: function forEach(cb, thisArg) { + this.index.visitAll(cb, thisArg); + }, + + + /** + * Get the record with the given id. + * + * @method Collection#get + * @since 3.0.0 + * @param {(string|number)} id The primary key of the record to get. + * @returns {(Object|Record)} The record with the given id. + */ + get: function get(id) { + var instances = id === undefined ? [] : this.query().get(id).run(); + return instances.length ? instances[0] : undefined; + }, + + + /** + * Find the record or records that match the provided keyLists. + * + * Shortcut for `collection.query().getAll(keyList1, keyList2, ...).run()` + * + * @example + * // Get the posts where "status" is "draft" or "inReview" + * const posts = collection.getAll('draft', 'inReview', { index: 'status' }); + * + * @example + * // Same as above + * const posts = collection.getAll(['draft'], ['inReview'], { index: 'status' }); + * + * @method Collection#getAll + * @since 3.0.0 + * @param {...Array} [keyList] Provide one or more keyLists, and all + * records matching each keyList will be retrieved. If no keyLists are + * provided, all records will be returned. + * @param {object} [opts] Configuration options. + * @param {string} [opts.index] Name of the secondary index to use in the + * query. If no index is specified, the main index is used. + * @returns {Array} The result. + */ + getAll: function getAll() { + var _query; + + return (_query = this.query()).getAll.apply(_query, arguments).run(); + }, + + + /** + * Return the index with the given name. If no name is provided, return the + * main index. Throws an error if the specified index does not exist. + * + * @method Collection#getIndex + * @since 3.0.0 + * @param {string} [name] The name of the index to retrieve. + */ + getIndex: function getIndex(name) { + var index = name ? this.indexes[name] : this.index; + if (!index) { + throw utils.err(DOMAIN$1 + '#getIndex', name)(404, 'index'); + } + return index; + }, + + + /** + * Limit the result. + * + * Shortcut for `collection.query().limit(maximumNumber).run()` + * + * @example + * const posts = collection.limit(10); + * + * @method Collection#limit + * @since 3.0.0 + * @param {number} num The maximum number of records to keep in the result. + * @returns {Array} The result. + */ + limit: function limit(num) { + return this.query().limit(num).run(); + }, + + + /** + * Apply a mapping function to all records. + * + * @example + * const names = collection.map((user) => user.name); + * + * @method Collection#map + * @since 3.0.0 + * @param {Function} mapFn Mapping function. + * @param {*} [thisArg] Context to which to bind `mapFn`. + * @returns {Array} The result of the mapping. + */ + map: function map(cb, thisArg) { + var data = []; + this.index.visitAll(function (value) { + data.push(cb.call(thisArg, value)); + }); + return data; + }, + + + /** + * Return the result of calling the specified function on each record in this + * collection's main index. + * + * @method Collection#mapCall + * @since 3.0.0 + * @param {string} funcName Name of function to call + * @parama {...*} [args] Remaining arguments to be passed to the function. + * @returns {Array} The result. + */ + mapCall: function mapCall(funcName) { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + var data = []; + this.index.visitAll(function (record) { + data.push(record[funcName].apply(record, args)); + }); + return data; + }, + + + /** + * Return all "unsaved" (not uniquely identifiable) records in this colleciton. + * + * @method Collection#prune + * @param {object} [opts] Configuration options, passed to {@link Collection#removeAll}. + * @since 3.0.0 + * @returns {Array} The removed records, if any. + */ + prune: function prune(opts) { + return this.removeAll(this.unsaved(), opts); + }, + + + /** + * Create a new query to be executed against the contents of the collection. + * The result will be all or a subset of the contents of the collection. + * + * @example + * // Grab page 2 of users between ages 18 and 30 + * collection.query() + * .between(18, 30, { index: 'age' }) // between ages 18 and 30 + * .skip(10) // second page + * .limit(10) // page size + * .run(); + * + * @method Collection#query + * @since 3.0.0 + * @returns {Query} New query object. + */ + query: function query() { + var Ctor = this.queryClass; + return new Ctor(this); + }, + + + /** + * Return the primary key of the given, or if no record is provided, return the + * name of the field that holds the primary key of records in this Collection. + * + * @method Collection#recordId + * @since 3.0.0 + * @param {(Object|Record)} [record] The record whose primary key is to be + * returned. + * @returns {(string|number)} Primary key or name of field that holds primary + * key. + */ + recordId: function recordId(record) { + if (record) { + return utils.get(record, this.recordId()); + } + return this.mapper ? this.mapper.idAttribute : this.idAttribute; + }, + + + /** + * Reduce the data in the collection to a single value and return the result. + * + * @example + * const totalVotes = collection.reduce((prev, record) => { + * return prev + record.upVotes + record.downVotes; + * }, 0); + * + * @method Collection#reduce + * @since 3.0.0 + * @param {Function} cb Reduction callback. + * @param {*} initialValue Initial value of the reduction. + * @returns {*} The result. + */ + reduce: function reduce(cb, initialValue) { + var data = this.getAll(); + return data.reduce(cb, initialValue); + }, + + + /** + * Remove the record with the given id from this Collection. + * + * @method Collection#remove + * @since 3.0.0 + * @param {(string|number|object|Record)} idOrRecord The primary key of the + * record to be removed, or a reference to the record that is to be removed. + * @param {object} [opts] Configuration options. + * @returns {Object|Record} The removed record, if any. + */ + remove: function remove(idOrRecord, opts) { + // Default values for arguments + opts || (opts = {}); + this.beforeRemove(idOrRecord, opts); + var record = utils.isSorN(idOrRecord) ? this.get(idOrRecord) : idOrRecord; + + // The record is in the collection, remove it + if (utils.isObject(record)) { + record = this.index.removeRecord(record); + if (record) { + utils.forOwn(this.indexes, function (index, name) { + index.removeRecord(record); + }); + if (utils.isFunction(record.off)) { + record.off('all', this._onRecordEvent, this); + if (!opts.silent) { + this.emit('remove', record); + } + } + } + } + return this.afterRemove(idOrRecord, opts, record) || record; + }, + + + /** + * Remove from this collection the given records or the records selected by + * the given "query". + * + * @method Collection#removeAll + * @since 3.0.0 + * @param {Object|Object[]|Record[]} [queryOrRecords={}] Records to be removed or selection query. See {@link query}. + * @param {object} [queryOrRecords.where] See {@link query.where}. + * @param {number} [queryOrRecords.offset] See {@link query.offset}. + * @param {number} [queryOrRecords.limit] See {@link query.limit}. + * @param {string|Array[]} [queryOrRecords.orderBy] See {@link query.orderBy}. + * @param {object} [opts] Configuration options. + * @returns {(Object[]|Record[])} The removed records, if any. + */ + removeAll: function removeAll(queryOrRecords, opts) { + var _this3 = this; + + // Default values for arguments + opts || (opts = {}); + this.beforeRemoveAll(queryOrRecords, opts); + var records = utils.isArray(queryOrRecords) ? queryOrRecords.slice() : this.filter(queryOrRecords); + + // Remove each selected record from the collection + var optsCopy = utils.plainCopy(opts); + optsCopy.silent = true; + records = records.map(function (record) { + return _this3.remove(record, optsCopy); + }).filter(function (record) { + return record; + }); + if (!opts.silent) { + this.emit('remove', records); + } + return this.afterRemoveAll(queryOrRecords, opts, records) || records; + }, + + + /** + * Skip a number of results. + * + * Shortcut for `collection.query().skip(numberToSkip).run()` + * + * @example + * const posts = collection.skip(10); + * + * @method Collection#skip + * @since 3.0.0 + * @param {number} num The number of records to skip. + * @returns {Array} The result. + */ + skip: function skip(num) { + return this.query().skip(num).run(); + }, + + + /** + * Return the plain JSON representation of all items in this collection. + * Assumes records in this collection have a toJSON method. + * + * @method Collection#toJSON + * @since 3.0.0 + * @param {object} [opts] Configuration options. + * @param {string[]} [opts.with] Array of relation names or relation fields + * to include in the representation. + * @returns {Array} The records. + */ + toJSON: function toJSON(opts) { + return this.mapCall('toJSON', opts); + }, + + + /** + * Return all "unsaved" (not uniquely identifiable) records in this colleciton. + * + * @method Collection#unsaved + * @since 3.0.0 + * @returns {Array} The unsaved records, if any. + */ + unsaved: function unsaved(opts) { + return this.index.get(); + }, + + + /** + * Update a record's position in a single index of this collection. See + * {@link Collection#updateIndexes} to update a record's position in all + * indexes at once. + * + * @method Collection#updateIndex + * @since 3.0.0 + * @param {object} record The record to update. + * @param {object} [opts] Configuration options. + * @param {string} [opts.index] The index in which to update the record's + * position. If you don't specify an index then the record will be updated + * in the main index. + */ + updateIndex: function updateIndex(record, opts) { + opts || (opts = {}); + this.getIndex(opts.index).updateRecord(record); + }, + + + /** + * Updates all indexes in this collection for the provided record. Has no + * effect if the record is not in the collection. + * + * @method Collection#updateIndexes + * @since 3.0.0 + * @param {object} record TODO + */ + updateIndexes: function updateIndexes(record) { + this.index.updateRecord(record); + utils.forOwn(this.indexes, function (index, name) { + index.updateRecord(record); + }); + } +}); + +/** + * Fired when a record changes. Only works for records that have tracked changes. + * See {@link Collection~changeListener} on how to listen for this event. + * + * @event Collection#change + * @see Collection~changeListener + */ + +/** + * Callback signature for the {@link Collection#event:change} event. + * + * @example + * function onChange (record, changes) { + * // do something + * } + * collection.on('change', onChange); + * + * @callback Collection~changeListener + * @param {Record} The Record that changed. + * @param {object} The changes. + * @see Collection#event:change + * @since 3.0.0 + */ + +/** + * Fired when one or more records are added to the Collection. See + * {@link Collection~addListener} on how to listen for this event. + * + * @event Collection#add + * @see Collection~addListener + * @see Collection#event:add + * @see Collection#add + */ + +/** + * Callback signature for the {@link Collection#event:add} event. + * + * @example + * function onAdd (recordOrRecords) { + * // do something + * } + * collection.on('add', onAdd); + * + * @callback Collection~addListener + * @param {Record|Record[]} The Record or Records that were added. + * @see Collection#event:add + * @see Collection#add + * @since 3.0.0 + */ + +/** + * Fired when one or more records are removed from the Collection. See + * {@link Collection~removeListener} for how to listen for this event. + * + * @event Collection#remove + * @see Collection~removeListener + * @see Collection#event:remove + * @see Collection#remove + * @see Collection#removeAll + */ + +/** + * Callback signature for the {@link Collection#event:remove} event. + * + * @example + * function onRemove (recordsOrRecords) { + * // do something + * } + * collection.on('remove', onRemove); + * + * @callback Collection~removeListener + * @param {Record|Record[]} Record or Records that were removed. + * @see Collection#event:remove + * @see Collection#remove + * @see Collection#removeAll + * @since 3.0.0 + */ + +/** + * Create a subclass of this Collection: + * @example Collection.extend + * const JSData = require('js-data'); + * const { Collection } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomCollectionClass extends Collection { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customCollection = new CustomCollectionClass(); + * console.log(customCollection.foo()); + * console.log(CustomCollectionClass.beep()); + * + * // Extend the class using alternate method. + * const OtherCollectionClass = Collection.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherCollection = new OtherCollectionClass(); + * console.log(otherCollection.foo()); + * console.log(OtherCollectionClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherCollectionClass () { + * Collection.call(this); + * this.created_at = new Date().getTime(); + * } + * Collection.extend({ + * constructor: AnotherCollectionClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const anotherCollection = new AnotherCollectionClass(); + * console.log(anotherCollection.created_at); + * console.log(anotherCollection.foo()); + * console.log(AnotherCollectionClass.beep()); + * + * @method Collection.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this Collection class. + * @since 3.0.0 + */ + +var DOMAIN$7 = 'Schema'; + +/** + * A function map for each of the seven primitive JSON types defined by the core specification. + * Each function will check a given value and return true or false if the value is an instance of that type. + * ``` + * types.integer(1) // returns true + * types.string({}) // returns false + * ``` + * http://json-schema.org/latest/json-schema-core.html#anchor8 + * @name Schema.types + * @type {object} + */ +var types = { + array: utils.isArray, + boolean: utils.isBoolean, + integer: utils.isInteger, + 'null': utils.isNull, + number: utils.isNumber, + object: utils.isObject, + string: utils.isString + + /** + * @ignore + */ +};var segmentToString = function segmentToString(segment, prev) { + var str = ''; + if (segment) { + if (utils.isNumber(segment)) { + str += '[' + segment + ']'; + } else if (prev) { + str += '.' + segment; + } else { + str += '' + segment; + } + } + return str; +}; + +/** + * @ignore + */ +var makePath = function makePath(opts) { + opts || (opts = {}); + var path = ''; + var segments = opts.path || []; + segments.forEach(function (segment) { + path += segmentToString(segment, path); + }); + path += segmentToString(opts.prop, path); + return path; +}; + +/** + * @ignore + */ +var makeError = function makeError(actual, expected, opts) { + return { + expected: expected, + actual: '' + actual, + path: makePath(opts) + }; +}; + +/** + * @ignore + */ +var addError = function addError(actual, expected, opts, errors) { + errors.push(makeError(actual, expected, opts)); +}; + +/** + * @ignore + */ +var maxLengthCommon = function maxLengthCommon(keyword, value, schema, opts) { + var max = schema[keyword]; + if (value.length > max) { + return makeError(value.length, 'length no more than ' + max, opts); + } +}; + +/** + * @ignore + */ +var minLengthCommon = function minLengthCommon(keyword, value, schema, opts) { + var min = schema[keyword]; + if (value.length < min) { + return makeError(value.length, 'length no less than ' + min, opts); + } +}; + +/** + * A map of all object member validation functions for each keyword defined in the JSON Schema. + * @name Schema.validationKeywords + * @type {object} + */ +var validationKeywords = { + /** + * Validates the provided value against all schemas defined in the Schemas `allOf` keyword. + * The instance is valid against if and only if it is valid against all the schemas declared in the Schema's value. + * + * The value of this keyword MUST be an array. This array MUST have at least one element. + * Each element of this array MUST be a valid JSON Schema. + * + * see http://json-schema.org/latest/json-schema-validation.html#anchor82 + * + * @name Schema.validationKeywords.allOf + * @method + * @param {*} value Value to be validated. + * @param {object} schema Schema containing the `allOf` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + allOf: function allOf(value, schema, opts) { + var allErrors = []; + schema.allOf.forEach(function (_schema) { + allErrors = allErrors.concat(_validate(value, _schema, opts) || []); + }); + return allErrors.length ? allErrors : undefined; + }, + + + /** + * Validates the provided value against all schemas defined in the Schemas `anyOf` keyword. + * The instance is valid against this keyword if and only if it is valid against + * at least one of the schemas in this keyword's value. + * + * The value of this keyword MUST be an array. This array MUST have at least one element. + * Each element of this array MUST be an object, and each object MUST be a valid JSON Schema. + * see http://json-schema.org/latest/json-schema-validation.html#anchor85 + * + * @name Schema.validationKeywords.anyOf + * @method + * @param {*} value Value to be validated. + * @param {object} schema Schema containing the `anyOf` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + anyOf: function anyOf(value, schema, opts) { + var validated = false; + var allErrors = []; + schema.anyOf.forEach(function (_schema) { + var errors = _validate(value, _schema, opts); + if (errors) { + allErrors = allErrors.concat(errors); + } else { + validated = true; + } + }); + return validated ? undefined : allErrors; + }, + + + /** + * http://json-schema.org/latest/json-schema-validation.html#anchor70 + * + * @name Schema.validationKeywords.dependencies + * @method + * @param {*} value TODO + * @param {object} schema TODO + * @param {object} opts TODO + */ + dependencies: function dependencies(value, schema, opts) { + // TODO + }, + + + /** + * Validates the provided value against an array of possible values defined by the Schema's `enum` keyword + * Validation succeeds if the value is deeply equal to one of the values in the array. + * see http://json-schema.org/latest/json-schema-validation.html#anchor76 + * + * @name Schema.validationKeywords.enum + * @method + * @param {*} value Value to validate + * @param {object} schema Schema containing the `enum` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + enum: function _enum(value, schema, opts) { + var possibleValues = schema['enum']; + if (utils.findIndex(possibleValues, function (item) { + return utils.deepEqual(item, value); + }) === -1) { + return makeError(value, 'one of (' + possibleValues.join(', ') + ')', opts); + } + }, + + + /** + * Validates each of the provided array values against a schema or an array of schemas defined by the Schema's `items` keyword + * see http://json-schema.org/latest/json-schema-validation.html#anchor37 for validation rules. + * + * @name Schema.validationKeywords.items + * @method + * @param {*} value Array to be validated. + * @param {object} schema Schema containing the items keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + items: function items(value, schema, opts) { + opts || (opts = {}); + // TODO: additionalItems + var items = schema.items; + var errors = []; + var checkingTuple = utils.isArray(items); + var length = value.length; + for (var prop = 0; prop < length; prop++) { + if (checkingTuple) { + // Validating a tuple, instead of just checking each item against the + // same schema + items = schema.items[prop]; + } + opts.prop = prop; + errors = errors.concat(_validate(value[prop], items, opts) || []); + } + return errors.length ? errors : undefined; + }, + + + /** + * Validates the provided number against a maximum value defined by the Schema's `maximum` keyword + * Validation succeeds if the value is a number, and is less than, or equal to, the value of this keyword. + * http://json-schema.org/latest/json-schema-validation.html#anchor17 + * + * @name Schema.validationKeywords.maximum + * @method + * @param {*} value Number to validate against the keyword. + * @param {object} schema Schema containing the `maximum` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + maximum: function maximum(value, schema, opts) { + // Must be a number + var maximum = schema.maximum; + // Must be a boolean + // Depends on maximum + // default: false + var exclusiveMaximum = schema.exclusiveMaximum; + if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === (typeof maximum === 'undefined' ? 'undefined' : _typeof(maximum)) && !(exclusiveMaximum ? maximum > value : maximum >= value)) { + return exclusiveMaximum ? makeError(value, 'no more than nor equal to ' + maximum, opts) : makeError(value, 'no more than ' + maximum, opts); + } + }, + + + /** + * Validates the length of the provided array against a maximum value defined by the Schema's `maxItems` keyword. + * Validation succeeds if the length of the array is less than, or equal to the value of this keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor42 + * + * @name Schema.validationKeywords.maxItems + * @method + * @param {*} value Array to be validated. + * @param {object} schema Schema containing the `maxItems` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + maxItems: function maxItems(value, schema, opts) { + if (utils.isArray(value)) { + return maxLengthCommon('maxItems', value, schema, opts); + } + }, + + + /** + * Validates the length of the provided string against a maximum value defined in the Schema's `maxLength` keyword. + * Validation succeeds if the length of the string is less than, or equal to the value of this keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor26 + * + * @name Schema.validationKeywords.maxLength + * @method + * @param {*} value String to be validated. + * @param {object} schema Schema containing the `maxLength` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + maxLength: function maxLength(value, schema, opts) { + return maxLengthCommon('maxLength', value, schema, opts); + }, + + + /** + * Validates the count of the provided object's properties against a maximum value defined in the Schema's `maxProperties` keyword. + * Validation succeeds if the object's property count is less than, or equal to the value of this keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor54 + * + * @name Schema.validationKeywords.maxProperties + * @method + * @param {*} value Object to be validated. + * @param {object} schema Schema containing the `maxProperties` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + maxProperties: function maxProperties(value, schema, opts) { + // validate only objects + if (!utils.isObject(value)) return; + var maxProperties = schema.maxProperties; + var length = Object.keys(value).length; + if (length > maxProperties) { + return makeError(length, 'no more than ' + maxProperties + ' properties', opts); + } + }, + + + /** + * Validates the provided value against a minimum value defined by the Schema's `minimum` keyword + * Validation succeeds if the value is a number and is greater than, or equal to, the value of this keyword. + * http://json-schema.org/latest/json-schema-validation.html#anchor21 + * + * @name Schema.validationKeywords.minimum + * @method + * @param {*} value Number to validate against the keyword. + * @param {object} schema Schema containing the `minimum` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + minimum: function minimum(value, schema, opts) { + // Must be a number + var minimum = schema.minimum; + // Must be a boolean + // Depends on minimum + // default: false + var exclusiveMinimum = schema.exclusiveMinimum; + if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === (typeof minimum === 'undefined' ? 'undefined' : _typeof(minimum)) && !(exclusiveMinimum ? value > minimum : value >= minimum)) { + return exclusiveMinimum ? makeError(value, 'no less than nor equal to ' + minimum, opts) : makeError(value, 'no less than ' + minimum, opts); + } + }, + + + /** + * Validates the length of the provided array against a minimum value defined by the Schema's `minItems` keyword. + * Validation succeeds if the length of the array is greater than, or equal to the value of this keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor45 + * + * @name Schema.validationKeywords.minItems + * @method + * @param {*} value Array to be validated. + * @param {object} schema Schema containing the `minItems` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + minItems: function minItems(value, schema, opts) { + if (utils.isArray(value)) { + return minLengthCommon('minItems', value, schema, opts); + } + }, + + + /** + * Validates the length of the provided string against a minimum value defined in the Schema's `minLength` keyword. + * Validation succeeds if the length of the string is greater than, or equal to the value of this keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor29 + * + * @name Schema.validationKeywords.minLength + * @method + * @param {*} value String to be validated. + * @param {object} schema Schema containing the `minLength` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + minLength: function minLength(value, schema, opts) { + return minLengthCommon('minLength', value, schema, opts); + }, + + + /** + * Validates the count of the provided object's properties against a minimum value defined in the Schema's `minProperties` keyword. + * Validation succeeds if the object's property count is greater than, or equal to the value of this keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor57 + * + * @name Schema.validationKeywords.minProperties + * @method + * @param {*} value Object to be validated. + * @param {object} schema Schema containing the `minProperties` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + minProperties: function minProperties(value, schema, opts) { + // validate only objects + if (!utils.isObject(value)) return; + var minProperties = schema.minProperties; + var length = Object.keys(value).length; + if (length < minProperties) { + return makeError(length, 'no more than ' + minProperties + ' properties', opts); + } + }, + + + /** + * Validates the provided number is a multiple of the number defined in the Schema's `multipleOf` keyword. + * Validation succeeds if the number can be divided equally into the value of this keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor14 + * + * @name Schema.validationKeywords.multipleOf + * @method + * @param {*} value Number to be validated. + * @param {object} schema Schema containing the `multipleOf` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + multipleOf: function multipleOf(value, schema, opts) { + var multipleOf = schema.multipleOf; + if (utils.isNumber(value)) { + if (value / multipleOf % 1 !== 0) { + return makeError(value, 'multipleOf ' + multipleOf, opts); + } + } + }, + + + /** + * Validates the provided value is not valid with any of the schemas defined in the Schema's `not` keyword. + * An instance is valid against this keyword if and only if it is NOT valid against the schemas in this keyword's value. + * + * see http://json-schema.org/latest/json-schema-validation.html#anchor91 + * @name Schema.validationKeywords.not + * @method + * @param {*} value to be checked. + * @param {object} schema Schema containing the not keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + not: function not(value, schema, opts) { + if (!_validate(value, schema.not, opts)) { + // TODO: better messaging + return makeError('succeeded', 'should have failed', opts); + } + }, + + + /** + * Validates the provided value is valid with one and only one of the schemas defined in the Schema's `oneOf` keyword. + * An instance is valid against this keyword if and only if it is valid against a single schemas in this keyword's value. + * + * see http://json-schema.org/latest/json-schema-validation.html#anchor88 + * @name Schema.validationKeywords.oneOf + * @method + * @param {*} value to be checked. + * @param {object} schema Schema containing the `oneOf` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + oneOf: function oneOf(value, schema, opts) { + var validated = false; + var allErrors = []; + schema.oneOf.forEach(function (_schema) { + var errors = _validate(value, _schema, opts); + if (errors) { + allErrors = allErrors.concat(errors); + } else if (validated) { + allErrors = [makeError('valid against more than one', 'valid against only one', opts)]; + validated = false; + return false; + } else { + validated = true; + } + }); + return validated ? undefined : allErrors; + }, + + + /** + * Validates the provided string matches a pattern defined in the Schema's `pattern` keyword. + * Validation succeeds if the string is a match of the regex value of this keyword. + * + * see http://json-schema.org/latest/json-schema-validation.html#anchor33 + * @name Schema.validationKeywords.pattern + * @method + * @param {*} value String to be validated. + * @param {object} schema Schema containing the `pattern` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + pattern: function pattern(value, schema, opts) { + var pattern = schema.pattern; + if (utils.isString(value) && !value.match(pattern)) { + return makeError(value, pattern, opts); + } + }, + + + /** + * Validates the provided object's properties against a map of values defined in the Schema's `properties` keyword. + * Validation succeeds if the object's property are valid with each of the schema's in the provided map. + * Validation also depends on the additionalProperties and or patternProperties. + * + * see http://json-schema.org/latest/json-schema-validation.html#anchor64 for more info. + * + * @name Schema.validationKeywords.properties + * @method + * @param {*} value Object to be validated. + * @param {object} schema Schema containing the `properties` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + properties: function properties(value, schema, opts) { + opts || (opts = {}); + + if (utils.isArray(value)) { + return; + } + + // Can be a boolean or an object + // Technically the default is an "empty schema", but here "true" is + // functionally the same + var additionalProperties = schema.additionalProperties === undefined ? true : schema.additionalProperties; + var validated = []; + // "p": The property set from "properties". + // Default is an object + var properties = schema.properties || {}; + // "pp": The property set from "patternProperties". + // Default is an object + var patternProperties = schema.patternProperties || {}; + var errors = []; + + utils.forOwn(properties, function (_schema, prop) { + opts.prop = prop; + errors = errors.concat(_validate(value[prop], _schema, opts) || []); + validated.push(prop); + }); + + var toValidate = utils.omit(value, validated); + utils.forOwn(patternProperties, function (_schema, pattern) { + utils.forOwn(toValidate, function (undef, prop) { + if (prop.match(pattern)) { + opts.prop = prop; + errors = errors.concat(_validate(value[prop], _schema, opts) || []); + validated.push(prop); + } + }); + }); + var keys = Object.keys(utils.omit(value, validated)); + // If "s" is not empty, validation fails + if (additionalProperties === false) { + if (keys.length) { + var origProp = opts.prop; + opts.prop = ''; + addError('extra fields: ' + keys.join(', '), 'no extra fields', opts, errors); + opts.prop = origProp; + } + } else if (utils.isObject(additionalProperties)) { + // Otherwise, validate according to provided schema + keys.forEach(function (prop) { + opts.prop = prop; + errors = errors.concat(_validate(value[prop], additionalProperties, opts) || []); + }); + } + return errors.length ? errors : undefined; + }, + + + /** + * Validates the provided object's has all properties listed in the Schema's `properties` keyword array. + * Validation succeeds if the object contains all properties provided in the array value of this keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor61 + * + * @name Schema.validationKeywords.required + * @method + * @param {*} value Object to be validated. + * @param {object} schema Schema containing the `required` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + required: function required(value, schema, opts) { + opts || (opts = {}); + var required = schema.required; + var errors = []; + if (!opts.existingOnly) { + required.forEach(function (prop) { + if (utils.get(value, prop) === undefined) { + var prevProp = opts.prop; + opts.prop = prop; + addError(undefined, 'a value', opts, errors); + opts.prop = prevProp; + } + }); + } + return errors.length ? errors : undefined; + }, + + + /** + * Validates the provided value's type is equal to the type, or array of types, defined in the Schema's `type` keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor79 + * + * @name Schema.validationKeywords.type + * @method + * @param {*} value Value to be validated. + * @param {object} schema Schema containing the `type` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + type: function type(value, schema, opts) { + var type = schema.type; + var validType = void 0; + // Can be one of several types + if (utils.isString(type)) { + type = [type]; + } + // Try to match the value against an expected type + type.forEach(function (_type) { + // TODO: throw an error if type is not defined + if (types[_type](value, schema, opts)) { + // Matched a type + validType = _type; + return false; + } + }); + // Value did not match any expected type + if (!validType) { + return makeError(value !== undefined && value !== null ? typeof value === 'undefined' ? 'undefined' : _typeof(value) : '' + value, 'one of (' + type.join(', ') + ')', opts); + } + // Run keyword validators for matched type + // http://json-schema.org/latest/json-schema-validation.html#anchor12 + var validator = typeGroupValidators[validType]; + if (validator) { + return validator(value, schema, opts); + } + }, + + + /** + * Validates the provided array values are unique. + * Validation succeeds if the items in the array are unique, but only if the value of this keyword is true + * see http://json-schema.org/latest/json-schema-validation.html#anchor49 + * + * @name Schema.validationKeywords.uniqueItems + * @method + * @param {*} value Array to be validated. + * @param {object} schema Schema containing the `uniqueItems` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + uniqueItems: function uniqueItems(value, schema, opts) { + if (value && value.length && schema.uniqueItems) { + var length = value.length; + var item = void 0, + i = void 0, + j = void 0; + // Check n - 1 items + for (i = length - 1; i > 0; i--) { + item = value[i]; + // Only compare against unchecked items + for (j = i - 1; j >= 0; j--) { + // Found a duplicate + if (utils.deepEqual(item, value[j])) { + return makeError(item, 'no duplicates', opts); + } + } + } + } + } +}; + +/** + * @ignore + */ +var runOps = function runOps(ops, value, schema, opts) { + var errors = []; + ops.forEach(function (op) { + if (schema[op] !== undefined) { + errors = errors.concat(validationKeywords[op](value, schema, opts) || []); + } + }); + return errors.length ? errors : undefined; +}; + +/** + * Validation keywords validated for any type: + * + * - `enum` + * - `type` + * - `allOf` + * - `anyOf` + * - `oneOf` + * - `not` + * + * @name Schema.ANY_OPS + * @type {string[]} + */ +var ANY_OPS = ['enum', 'type', 'allOf', 'anyOf', 'oneOf', 'not']; + +/** + * Validation keywords validated for array types: + * + * - `items` + * - `maxItems` + * - `minItems` + * - `uniqueItems` + * + * @name Schema.ARRAY_OPS + * @type {string[]} + */ +var ARRAY_OPS = ['items', 'maxItems', 'minItems', 'uniqueItems']; + +/** + * Validation keywords validated for numeric (number and integer) types: + * + * - `multipleOf` + * - `maximum` + * - `minimum` + * + * @name Schema.NUMERIC_OPS + * @type {string[]} + */ +var NUMERIC_OPS = ['multipleOf', 'maximum', 'minimum']; + +/** + * Validation keywords validated for object types: + * + * - `maxProperties` + * - `minProperties` + * - `required` + * - `properties` + * - `dependencies` + * + * @name Schema.OBJECT_OPS + * @type {string[]} + */ +var OBJECT_OPS = ['maxProperties', 'minProperties', 'required', 'properties', 'dependencies']; + +/** + * Validation keywords validated for string types: + * + * - `maxLength` + * - `minLength` + * - `pattern` + * + * @name Schema.STRING_OPS + * @type {string[]} + */ +var STRING_OPS = ['maxLength', 'minLength', 'pattern']; + +/** + * http://json-schema.org/latest/json-schema-validation.html#anchor75 + * @ignore + */ +var validateAny = function validateAny(value, schema, opts) { + return runOps(ANY_OPS, value, schema, opts); +}; + +/** + * Validates the provided value against a given Schema according to the http://json-schema.org/ v4 specification. + * + * @name Schema.validate + * @method + * @param {*} value Value to be validated. + * @param {object} schema Valid Schema according to the http://json-schema.org/ v4 specification. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ +var _validate = function _validate(value, schema, opts) { + var errors = []; + opts || (opts = {}); + opts.ctx || (opts.ctx = { value: value, schema: schema }); + var shouldPop = void 0; + var prevProp = opts.prop; + if (schema === undefined) { + return; + } + if (!utils.isObject(schema)) { + throw utils.err(DOMAIN$7 + '#validate')(500, 'Invalid schema at path: "' + opts.path + '"'); + } + if (opts.path === undefined) { + opts.path = []; + } + // Track our location as we recurse + if (opts.prop !== undefined) { + shouldPop = true; + opts.path.push(opts.prop); + opts.prop = undefined; + } + // Validate against parent schema + if (schema['extends']) { + // opts.path = path + // opts.prop = prop + if (utils.isFunction(schema['extends'].validate)) { + errors = errors.concat(schema['extends'].validate(value, opts) || []); + } else { + errors = errors.concat(_validate(value, schema['extends'], opts) || []); + } + } + if (value === undefined) { + // Check if property is required + if (schema.required === true && !opts.existingOnly) { + addError(value, 'a value', opts, errors); + } + if (shouldPop) { + opts.path.pop(); + opts.prop = prevProp; + } + return errors.length ? errors : undefined; + } + + errors = errors.concat(validateAny(value, schema, opts) || []); + if (shouldPop) { + opts.path.pop(); + opts.prop = prevProp; + } + return errors.length ? errors : undefined; +}; + +// These strings are cached for optimal performance of the change detection +// boolean - Whether a Record is changing in the current execution frame +var changingPath = 'changing'; +// string[] - Properties that have changed in the current execution frame +var changedPath = 'changed'; +// Object[] - History of change records +var changeHistoryPath = 'history'; +// boolean - Whether a Record is currently being instantiated +var creatingPath$1 = 'creating'; +// number - The setTimeout change event id of a Record, if any +var eventIdPath = 'eventId'; +// boolean - Whether to skip validation for a Record's currently changing property +var noValidatePath$2 = 'noValidate'; +// boolean - Whether to preserve Change History for a Record +var keepChangeHistoryPath$1 = 'keepChangeHistory'; +// boolean - Whether to skip change notification for a Record's currently +// changing property +var silentPath = 'silent'; +var validationFailureMsg = 'validation failed'; + +/** + * A map of validation functions grouped by type. + * + * @name Schema.typeGroupValidators + * @type {object} + */ +var typeGroupValidators = { + /** + * Validates the provided value against the schema using all of the validation keywords specific to instances of an array. + * The validation keywords for the type `array` are: + *``` + * ['items', 'maxItems', 'minItems', 'uniqueItems'] + *``` + * see http://json-schema.org/latest/json-schema-validation.html#anchor25 + * + * @name Schema.typeGroupValidators.array + * @method + * @param {*} value Array to be validated. + * @param {object} schema Schema containing at least one array keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + array: function array(value, schema, opts) { + return runOps(ARRAY_OPS, value, schema, opts); + }, + + /** + * Validates the provided value against the schema using all of the validation keywords specific to instances of an integer. + * The validation keywords for the type `integer` are: + *``` + * ['multipleOf', 'maximum', 'minimum'] + *``` + * @name Schema.typeGroupValidators.integer + * @method + * @param {*} value Number to be validated. + * @param {object} schema Schema containing at least one `integer` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + integer: function integer(value, schema, opts) { + // Additional validations for numerics are the same + return typeGroupValidators.numeric(value, schema, opts); + }, + + /** + * Validates the provided value against the schema using all of the validation keywords specific to instances of an number. + * The validation keywords for the type `number` are: + *``` + * ['multipleOf', 'maximum', 'minimum'] + *``` + * @name Schema.typeGroupValidators.number + * @method + * @param {*} value Number to be validated. + * @param {object} schema Schema containing at least one `number` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + number: function number(value, schema, opts) { + // Additional validations for numerics are the same + return typeGroupValidators.numeric(value, schema, opts); + }, + + /** + * Validates the provided value against the schema using all of the validation keywords specific to instances of a number or integer. + * The validation keywords for the type `numeric` are: + *``` + * ['multipleOf', 'maximum', 'minimum'] + *``` + * See http://json-schema.org/latest/json-schema-validation.html#anchor13. + * + * @name Schema.typeGroupValidators.numeric + * @method + * @param {*} value Number to be validated. + * @param {object} schema Schema containing at least one `numeric` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + numeric: function numeric(value, schema, opts) { + return runOps(NUMERIC_OPS, value, schema, opts); + }, + + /** + * Validates the provided value against the schema using all of the validation keywords specific to instances of an object. + * The validation keywords for the type `object` are: + *``` + * ['maxProperties', 'minProperties', 'required', 'properties', 'dependencies'] + *``` + * See http://json-schema.org/latest/json-schema-validation.html#anchor53. + * + * @name Schema.typeGroupValidators.object + * @method + * @param {*} value Object to be validated. + * @param {object} schema Schema containing at least one `object` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + object: function object(value, schema, opts) { + return runOps(OBJECT_OPS, value, schema, opts); + }, + + /** + * Validates the provided value against the schema using all of the validation keywords specific to instances of an string. + * The validation keywords for the type `string` are: + *``` + * ['maxLength', 'minLength', 'pattern'] + *``` + * See http://json-schema.org/latest/json-schema-validation.html#anchor25. + * + * @name Schema.typeGroupValidators.string + * @method + * @param {*} value String to be validated. + * @param {object} schema Schema containing at least one `string` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + string: function string(value, schema, opts) { + return runOps(STRING_OPS, value, schema, opts); + } + + /** + * js-data's Schema class. + * + * @example Schema#constructor + * const JSData = require('js-data'); + * const { Schema } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const PostSchema = new Schema({ + * type: 'object', + * properties: { + * title: { type: 'string' } + * } + * }); + * PostSchema.validate({ title: 1234 }); + * + * @class Schema + * @extends Component + * @param {object} definition Schema definition according to json-schema.org + */ +};function Schema(definition) { + var _this = this; + + definition || (definition = {}); + // TODO: schema validation + utils.fillIn(this, definition); + + if (this.type === 'object') { + this.properties = this.properties || {}; + utils.forOwn(this.properties, function (_definition, prop) { + if (!(_definition instanceof Schema)) { + _this.properties[prop] = new Schema(_definition); + } + }); + } else if (this.type === 'array' && this.items && !(this.items instanceof Schema)) { + this.items = new Schema(this.items); + } + if (this.extends && !(this.extends instanceof Schema)) { + this.extends = new Schema(this.extends); + } + ['allOf', 'anyOf', 'oneOf'].forEach(function (validationKeyword) { + if (_this[validationKeyword]) { + _this[validationKeyword].forEach(function (_definition, i) { + if (!(_definition instanceof Schema)) { + _this[validationKeyword][i] = new Schema(_definition); + } + }); + } + }); +} + +var Schema$1 = Component$1.extend({ + constructor: Schema, + + /** + * This adds ES5 getters/setters to the target based on the "properties" in + * this Schema, which makes possible change tracking and validation on + * property assignment. + * + * @name Schema#apply + * @method + * @param {object} target The prototype to which to apply this schema. + */ + apply: function apply(target, opts) { + var _this2 = this; + + opts || (opts = {}); + opts.getter || (opts.getter = '_get'); + opts.setter || (opts.setter = '_set'); + opts.unsetter || (opts.unsetter = '_unset'); + opts.track || (opts.track = this.track); + var properties = this.properties || {}; + utils.forOwn(properties, function (schema, prop) { + Object.defineProperty(target, prop, _this2.makeDescriptor(prop, schema, opts)); + }); + }, + + + /** + * Apply default values to the target object for missing values. + * + * @name Schema#applyDefaults + * @method + * @param {object} target The target to which to apply values for missing values. + */ + applyDefaults: function applyDefaults(target) { + if (!target) { + return; + } + var properties = this.properties || {}; + var hasSet = utils.isFunction(target.set) || utils.isFunction(target._set); + utils.forOwn(properties, function (schema, prop) { + if (schema.hasOwnProperty('default') && utils.get(target, prop) === undefined) { + if (hasSet) { + target.set(prop, utils.plainCopy(schema['default']), { silent: true }); + } else { + utils.set(target, prop, utils.plainCopy(schema['default'])); + } + } + if (schema.type === 'object' && schema.properties) { + if (hasSet) { + var orig = target._get('noValidate'); + target._set('noValidate', true); + utils.set(target, prop, utils.get(target, prop) || {}, { silent: true }); + target._set('noValidate', orig); + } else { + utils.set(target, prop, utils.get(target, prop) || {}); + } + schema.applyDefaults(utils.get(target, prop)); + } + }); + }, + + + /** + * Assemble a property descriptor for tracking and validating changes to + * a property according to the given schema. This method is called when + * {@link Mapper#applySchema} is set to `true`. + * + * @name Schema#makeDescriptor + * @method + * @param {string} prop The property name. + * @param {(Schema|object)} schema The schema for the property. + * @param {object} [opts] Optional configuration. + * @param {function} [opts.getter] Custom getter function. + * @param {function} [opts.setter] Custom setter function. + * @param {function} [opts.track] Whether to track changes. + * @returns {object} A property descriptor for the given schema. + */ + makeDescriptor: function makeDescriptor(prop, schema, opts) { + var descriptor = { + // Better to allow configurability, but at the user's own risk + configurable: true, + // These properties are enumerable by default, but regardless of their + // enumerability, they won't be "own" properties of individual records + enumerable: schema.enumerable === undefined ? true : !!schema.enumerable + // Cache a few strings for optimal performance + };var keyPath = 'props.' + prop; + var previousPath = 'previous.' + prop; + var getter = opts.getter; + var setter = opts.setter; + var unsetter = opts.unsetter; + var track = utils.isBoolean(opts.track) ? opts.track : schema.track; + + descriptor.get = function () { + return this._get(keyPath); + }; + + if (utils.isFunction(schema.get)) { + var originalGet = descriptor.get; + descriptor.get = function () { + return schema.get.call(this, originalGet); + }; + } + + descriptor.set = function (value) { + var _this3 = this; + + // These are accessed a lot + var _get = this[getter]; + var _set = this[setter]; + var _unset = this[unsetter]; + // Optionally check that the new value passes validation + if (!_get(noValidatePath$2)) { + var errors = schema.validate(value, { path: [prop] }); + if (errors) { + // Immediately throw an error, preventing the record from getting into + // an invalid state + var error = new Error(validationFailureMsg); + error.errors = errors; + throw error; + } + } + // TODO: Make it so tracking can be turned on for all properties instead of + // only per-property + if (track && !_get(creatingPath$1)) { + // previous is versioned on database commit + // props are versioned on set() + var previous = _get(previousPath); + var current = _get(keyPath); + var changing = _get(changingPath); + var changed = _get(changedPath); + + if (!changing) { + // Track properties that are changing in the current event loop + changed = []; + } + + // Add changing properties to this array once at most + var index = changed.indexOf(prop); + if (current !== value && index === -1) { + changed.push(prop); + } + if (previous === value) { + if (index >= 0) { + changed.splice(index, 1); + } + } + // No changes in current event loop + if (!changed.length) { + changing = false; + _unset(changingPath); + _unset(changedPath); + // Cancel pending change event + if (_get(eventIdPath)) { + clearTimeout(_get(eventIdPath)); + _unset(eventIdPath); + } + } + // Changes detected in current event loop + if (!changing && changed.length) { + _set(changedPath, changed); + _set(changingPath, true); + // Saving the timeout id allows us to batch all changes in the same + // event loop into a single "change" + // TODO: Optimize + _set(eventIdPath, setTimeout(function () { + // Previous event loop where changes were gathered has ended, so + // notify any listeners of those changes and prepare for any new + // changes + _unset(changedPath); + _unset(eventIdPath); + _unset(changingPath); + // TODO: Optimize + if (!_get(silentPath)) { + var i = void 0; + for (i = 0; i < changed.length; i++) { + _this3.emit('change:' + changed[i], _this3, utils.get(_this3, changed[i])); + } + + var changes = utils.diffObjects(defineProperty({}, prop, value), defineProperty({}, prop, current)); + + if (_get(keepChangeHistoryPath$1)) { + var changeRecord = utils.plainCopy(changes); + changeRecord.timestamp = new Date().getTime(); + var changeHistory = _get(changeHistoryPath); + !changeHistory && _set(changeHistoryPath, changeHistory = []); + changeHistory.push(changeRecord); + } + _this3.emit('change', _this3, changes); + } + _unset(silentPath); + }, 0)); + } + } + _set(keyPath, value); + return value; + }; + + if (utils.isFunction(schema.set)) { + var originalSet = descriptor.set; + descriptor.set = function (value) { + return schema.set.call(this, value, originalSet); + }; + } + + return descriptor; + }, + + + /** + * Create a copy of the given value that contains only the properties defined + * in this schema. + * + * @name Schema#pick + * @method + * @param {*} value The value to copy. + * @returns {*} The copy. + */ + pick: function pick(value) { + var _this4 = this; + + if (value === undefined) { + return; + } + if (this.type === 'object') { + var copy = {}; + var properties = this.properties; + if (properties) { + utils.forOwn(properties, function (_definition, prop) { + copy[prop] = _definition.pick(value[prop]); + }); + } + if (this.extends) { + utils.fillIn(copy, this.extends.pick(value)); + } + // Conditionally copy properties not defined in "properties" + if (this.additionalProperties) { + for (var key in value) { + if (!properties[key]) { + copy[key] = utils.plainCopy(value[key]); + } + } + } + return copy; + } else if (this.type === 'array') { + return value.map(function (item) { + var _copy = _this4.items ? _this4.items.pick(item) : {}; + if (_this4.extends) { + utils.fillIn(_copy, _this4.extends.pick(item)); + } + return _copy; + }); + } + return utils.plainCopy(value); + }, + + + /** + * Validate the provided value against this schema. + * + * @name Schema#validate + * @method + * @param {*} value Value to validate. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + validate: function validate(value, opts) { + return _validate(value, this, opts); + } +}, { + ANY_OPS: ANY_OPS, + ARRAY_OPS: ARRAY_OPS, + NUMERIC_OPS: NUMERIC_OPS, + OBJECT_OPS: OBJECT_OPS, + STRING_OPS: STRING_OPS, + typeGroupValidators: typeGroupValidators, + types: types, + validate: _validate, + validationKeywords: validationKeywords +}); + +/** + * Create a subclass of this Schema: + * @example Schema.extend + * const JSData = require('js-data'); + * const { Schema } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomSchemaClass extends Schema { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customSchema = new CustomSchemaClass(); + * console.log(customSchema.foo()); + * console.log(CustomSchemaClass.beep()); + * + * // Extend the class using alternate method. + * const OtherSchemaClass = Schema.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherSchema = new OtherSchemaClass(); + * console.log(otherSchema.foo()); + * console.log(OtherSchemaClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherSchemaClass () { + * Schema.call(this); + * this.created_at = new Date().getTime(); + * } + * Schema.extend({ + * constructor: AnotherSchemaClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const anotherSchema = new AnotherSchemaClass(); + * console.log(anotherSchema.created_at); + * console.log(anotherSchema.foo()); + * console.log(AnotherSchemaClass.beep()); + * + * @method Schema.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this Schema class. + * @since 3.0.0 + */ + +var DOMAIN$6 = 'Mapper'; +var applyDefaultsHooks = ['beforeCreate', 'beforeCreateMany']; +var validatingHooks = ['beforeCreate', 'beforeCreateMany', 'beforeUpdate', 'beforeUpdateAll', 'beforeUpdateMany']; +var makeNotify = function makeNotify(num) { + return function () { + var _this = this; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var opts = args[args.length - num]; + var op = opts.op; + this.dbg.apply(this, [op].concat(args)); + + if (applyDefaultsHooks.indexOf(op) !== -1 && opts.applyDefaults !== false) { + var schema = this.getSchema(); + if (schema && schema.applyDefaults) { + var toProcess = args[0]; + if (!utils.isArray(toProcess)) { + toProcess = [toProcess]; + } + toProcess.forEach(function (record) { + schema.applyDefaults(record); + }); + } + } + + // Automatic validation + if (validatingHooks.indexOf(op) !== -1 && !opts.noValidate) { + // Save current value of option + var originalExistingOnly = opts.existingOnly; + + // For updates, ignore required fields if they aren't present + if (op.indexOf('beforeUpdate') === 0 && opts.existingOnly === undefined) { + opts.existingOnly = true; + } + var errors = this.validate(args[op === 'beforeUpdate' ? 1 : 0], utils.pick(opts, ['existingOnly'])); + + // Restore option + opts.existingOnly = originalExistingOnly; + + // Abort lifecycle due to validation errors + if (errors) { + var err = new Error('validation failed'); + err.errors = errors; + return utils.reject(err); + } + } + + // Emit lifecycle event + if (opts.notify || opts.notify === undefined && this.notify) { + setTimeout(function () { + _this.emit.apply(_this, [op].concat(args)); + }); + } + }; +}; + +// These are the default implementations of all of the lifecycle hooks +var notify = makeNotify(1); +var notify2 = makeNotify(2); + +// This object provides meta information used by Mapper#crud to actually +// execute each lifecycle method +var LIFECYCLE_METHODS = { + count: { + defaults: [{}, {}], + skip: true, + types: [] + }, + destroy: { + defaults: [{}, {}], + skip: true, + types: [] + }, + destroyAll: { + defaults: [{}, {}], + skip: true, + types: [] + }, + find: { + defaults: [undefined, {}], + types: [] + }, + findAll: { + defaults: [{}, {}], + types: [] + }, + sum: { + defaults: [undefined, {}, {}], + skip: true, + types: [] + }, + update: { + adapterArgs: function adapterArgs(mapper, id, props, opts) { + return [id, mapper.toJSON(props, opts), opts]; + }, + + beforeAssign: 1, + defaults: [undefined, {}, {}], + types: [] + }, + updateAll: { + adapterArgs: function adapterArgs(mapper, props, query, opts) { + return [mapper.toJSON(props, opts), query, opts]; + }, + + beforeAssign: 0, + defaults: [{}, {}, {}], + types: [] + }, + updateMany: { + adapterArgs: function adapterArgs(mapper, records, opts) { + return [records.map(function (record) { + return mapper.toJSON(record, opts); + }), opts]; + }, + + beforeAssign: 0, + defaults: [[], {}], + types: [] + } +}; + +var MAPPER_DEFAULTS = { + /** + * Hash of registered adapters. Don't modify directly. Use + * {@link Mapper#registerAdapter} instead. + * + * @default {} + * @name Mapper#_adapters + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/connecting-to-a-data-source","Connecting to a data source"] + */ + _adapters: {}, + + /** + * Whether {@link Mapper#beforeCreate} and {@link Mapper#beforeCreateMany} + * should automatically receive default values according to the Mapper's schema. + * + * @default true + * @name Mapper#applyDefaults + * @since 3.0.0 + * @type {boolean} + */ + applyDefaults: true, + + /** + * Whether to augment {@link Mapper#recordClass} with ES5 getters and setters + * according to the properties defined in {@link Mapper#schema}. This makes + * possible validation and change tracking on individual properties + * when using the dot (e.g. `user.name = "Bob"`) operator to modify a + * property, and is `true` by default. + * + * @default true + * @name Mapper#applySchema + * @since 3.0.0 + * @type {boolean} + */ + applySchema: true, + + /** + * The name of the registered adapter that this Mapper should used by default. + * + * @default "http" + * @name Mapper#defaultAdapter + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/connecting-to-a-data-source","Connecting to a data source"] + * @type {string} + */ + defaultAdapter: 'http', + + /** + * The field used as the unique identifier on records handled by this Mapper. + * + * @default id + * @name Mapper#idAttribute + * @since 3.0.0 + * @type {string} + */ + idAttribute: 'id', + + /** + * Whether records created from this mapper keep changeHistory on property changes. + * + * @default true + * @name Mapper#keepChangeHistory + * @since 3.0.0 + * @type {boolean} + */ + keepChangeHistory: true, + + /** + * Whether this Mapper should emit operational events. + * + * @default true + * @name Mapper#notify + * @since 3.0.0 + * @type {boolean} + */ + notify: true, + + /** + * Whether to skip validation when the Record instances are created. + * + * @default false + * @name Mapper#noValidate + * @since 3.0.0 + * @type {boolean} + */ + noValidate: false, + + /** + * Whether {@link Mapper#create}, {@link Mapper#createMany}, + * {@link Mapper#update}, {@link Mapper#updateAll}, {@link Mapper#updateMany}, + * {@link Mapper#find}, {@link Mapper#findAll}, {@link Mapper#destroy}, + * {@link Mapper#destroyAll}, {@link Mapper#count}, and {@link Mapper#sum} + * should return a raw result object that contains both the instance data + * returned by the adapter _and_ metadata about the operation. + * + * The default is to NOT return the result object, and instead return just the + * instance data. + * + * @default false + * @name Mapper#raw + * @since 3.0.0 + * @type {boolean} + */ + raw: false, + + /** + * Whether records created from this mapper automatically validate their properties + * when their properties are modified. + * + * @default true + * @name Mapper#validateOnSet + * @since 3.0.0 + * @type {boolean} + */ + validateOnSet: true + + /** + * The core of JSData's [ORM/ODM][orm] implementation. Given a minimum amout of + * meta information about a resource, a Mapper can perform generic CRUD + * operations against that resource. Apart from its configuration, a Mapper is + * stateless. The particulars of various persistence layers have been abstracted + * into adapters, which a Mapper uses to perform its operations. + * + * The term "Mapper" comes from the [Data Mapper Pattern][pattern] described in + * Martin Fowler's [Patterns of Enterprise Application Architecture][book]. A + * Data Mapper moves data between [in-memory object instances][record] and a + * relational or document-based database. JSData's Mapper can work with any + * persistence layer you can write an adapter for. + * + * _("Model" is a heavily overloaded term and is avoided in this documentation + * to prevent confusion.)_ + * + * [orm]: https://en.wikipedia.org/wiki/Object-relational_mapping + * + * @example + * [pattern]: https://en.wikipedia.org/wiki/Data_mapper_pattern + * [book]: http://martinfowler.com/books/eaa.html + * [record]: Record.html + * // Import and instantiate + * import { Mapper } from 'js-data'; + * const UserMapper = new Mapper({ name: 'user' }); + * + * @example + * // Define a Mapper using the Container component + * import { Container } from 'js-data'; + * const store = new Container(); + * store.defineMapper('user'); + * + * @class Mapper + * @extends Component + * @param {object} opts Configuration options. + * @param {boolean} [opts.applySchema=true] See {@link Mapper#applySchema}. + * @param {boolean} [opts.debug=false] See {@link Component#debug}. + * @param {string} [opts.defaultAdapter=http] See {@link Mapper#defaultAdapter}. + * @param {string} [opts.idAttribute=id] See {@link Mapper#idAttribute}. + * @param {object} [opts.methods] See {@link Mapper#methods}. + * @param {string} opts.name See {@link Mapper#name}. + * @param {boolean} [opts.notify] See {@link Mapper#notify}. + * @param {boolean} [opts.raw=false] See {@link Mapper#raw}. + * @param {Function|boolean} [opts.recordClass] See {@link Mapper#recordClass}. + * @param {Object|Schema} [opts.schema] See {@link Mapper#schema}. + * @returns {Mapper} A new {@link Mapper} instance. + * @see http://www.js-data.io/v3.0/docs/components-of-jsdata#mapper + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#mapper","Components of JSData: Mapper"] + * @tutorial ["http://www.js-data.io/v3.0/docs/modeling-your-data","Modeling your data"] + */ +};function Mapper(opts) { + utils.classCallCheck(this, Mapper); + Component$1.call(this); + opts || (opts = {}); + + // Prepare certain properties to be non-enumerable + Object.defineProperties(this, { + _adapters: { + value: undefined, + writable: true + }, + + /** + * The {@link Container} that holds this Mapper. __Do not modify.__ + * + * @name Mapper#lifecycleMethods + * @since 3.0.0 + * @type {Object} + */ + datastore: { + value: undefined, + writable: true + }, + + /** + * The meta information describing this Mapper's available lifecycle + * methods. __Do not modify.__ + * + * @name Mapper#lifecycleMethods + * @since 3.0.0 + * @type {Object} + */ + lifecycleMethods: { + value: LIFECYCLE_METHODS + }, + + /** + * Set to `false` to force the Mapper to work with POJO objects only. + * + * @example + * // Use POJOs only. + * import { Mapper, Record } from 'js-data'; + * const UserMapper = new Mapper({ recordClass: false }); + * UserMapper.recordClass // false; + * const user = UserMapper.createRecord(); + * user instanceof Record; // false + * + * @example + * // Set to a custom class to have records wrapped in your custom class. + * import { Mapper, Record } from 'js-data'; + * // Custom class + * class User { + * constructor (props = {}) { + * for (var key in props) { + * if (props.hasOwnProperty(key)) { + * this[key] = props[key]; + * } + * } + * } + * } + * const UserMapper = new Mapper({ recordClass: User }); + * UserMapper.recordClass; // function User() {} + * const user = UserMapper.createRecord(); + * user instanceof Record; // false + * user instanceof User; // true + * + * + * @example + * // Extend the {@link Record} class. + * import { Mapper, Record } from 'js-data'; + * // Custom class + * class User extends Record { + * constructor () { + * super(props); + * } + * } + * const UserMapper = new Mapper({ recordClass: User }); + * UserMapper.recordClass; // function User() {} + * const user = UserMapper.createRecord(); + * user instanceof Record; // true + * user instanceof User; // true + * + * @name Mapper#recordClass + * @default {@link Record} + * @see Record + * @since 3.0.0 + */ + recordClass: { + value: undefined, + writable: true + }, + + /** + * This Mapper's {@link Schema}. + * + * @example Mapper#schema + * const JSData = require('js-data'); + * const { Mapper } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const UserMapper = new Mapper({ + * name: 'user', + * schema: { + * properties: { + * id: { type: 'number' }, + * first: { type: 'string', track: true }, + * last: { type: 'string', track: true }, + * role: { type: 'string', track: true, required: true }, + * age: { type: 'integer', track: true }, + * is_active: { type: 'number' } + * } + * } + * }); + * const user = UserMapper.createRecord({ + * id: 1, + * name: 'John', + * role: 'admin' + * }); + * user.on('change', function (user, changes) { + * console.log(changes); + * }); + * user.on('change:role', function (user, value) { + * console.log('change:role - ' + value); + * }); + * user.role = 'owner'; + * + * @name Mapper#schema + * @see Schema + * @since 3.0.0 + * @type {Schema} + */ + schema: { + value: undefined, + writable: true + } + }); + + // Apply user-provided configuration + utils.fillIn(this, opts); + // Fill in any missing options with the defaults + utils.fillIn(this, utils.copy(MAPPER_DEFAULTS)); + + /** + * The name for this Mapper. This is the minimum amount of meta information + * required for a Mapper to be able to execute CRUD operations for a + * Resource. + * + * @name Mapper#name + * @since 3.0.0 + * @type {string} + */ + if (!this.name) { + throw utils.err('new ' + DOMAIN$6, 'opts.name')(400, 'string', this.name); + } + + // Setup schema, with an empty default schema if necessary + if (this.schema) { + this.schema.type || (this.schema.type = 'object'); + if (!(this.schema instanceof Schema$1)) { + this.schema = new Schema$1(this.schema || { type: 'object' }); + } + } + + // Create a subclass of Record that's tied to this Mapper + if (this.recordClass === undefined) { + var superClass = Record$1; + this.recordClass = superClass.extend({ + constructor: function Record() { + var subClass = function Record(props, opts) { + utils.classCallCheck(this, subClass); + superClass.call(this, props, opts); + }; + return subClass; + }() + }); + } + + if (this.recordClass) { + this.recordClass.mapper = this; + + /** + * Functions that should be added to the prototype of {@link Mapper#recordClass}. + * + * @name Mapper#methods + * @since 3.0.0 + * @type {Object} + */ + if (utils.isObject(this.methods)) { + utils.addHiddenPropsToTarget(this.recordClass.prototype, this.methods); + } + + // We can only apply the schema to the prototype of this.recordClass if the + // class extends Record + if (Record$1.prototype.isPrototypeOf(Object.create(this.recordClass.prototype)) && this.schema && this.schema.apply && this.applySchema) { + this.schema.apply(this.recordClass.prototype); + } + } +} + +var Mapper$1 = Component$1.extend({ + constructor: Mapper, + + /** + * Mapper lifecycle hook called by {@link Mapper#count}. If this method + * returns a promise then {@link Mapper#count} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterCount + * @param {object} query The `query` argument passed to {@link Mapper#count}. + * @param {object} opts The `opts` argument passed to {@link Mapper#count}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterCount: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#create}. If this method + * returns a promise then {@link Mapper#create} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterCreate + * @param {object} props The `props` argument passed to {@link Mapper#create}. + * @param {object} opts The `opts` argument passed to {@link Mapper#create}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterCreate: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#createMany}. If this method + * returns a promise then {@link Mapper#createMany} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterCreateMany + * @param {array} records The `records` argument passed to {@link Mapper#createMany}. + * @param {object} opts The `opts` argument passed to {@link Mapper#createMany}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterCreateMany: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#destroy}. If this method + * returns a promise then {@link Mapper#destroy} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterDestroy + * @param {(string|number)} id The `id` argument passed to {@link Mapper#destroy}. + * @param {object} opts The `opts` argument passed to {@link Mapper#destroy}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterDestroy: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#destroyAll}. If this method + * returns a promise then {@link Mapper#destroyAll} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterDestroyAll + * @param {*} data The `data` returned by the adapter. + * @param {query} query The `query` argument passed to {@link Mapper#destroyAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#destroyAll}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterDestroyAll: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#find}. If this method + * returns a promise then {@link Mapper#find} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterFind + * @param {(string|number)} id The `id` argument passed to {@link Mapper#find}. + * @param {object} opts The `opts` argument passed to {@link Mapper#find}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterFind: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#findAll}. If this method + * returns a promise then {@link Mapper#findAll} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterFindAll + * @param {object} query The `query` argument passed to {@link Mapper#findAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#findAll}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterFindAll: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#sum}. If this method + * returns a promise then {@link Mapper#sum} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterSum + * @param {object} query The `query` argument passed to {@link Mapper#sum}. + * @param {object} opts The `opts` argument passed to {@link Mapper#sum}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterSum: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#update}. If this method + * returns a promise then {@link Mapper#update} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterUpdate + * @param {(string|number)} id The `id` argument passed to {@link Mapper#update}. + * @param {props} props The `props` argument passed to {@link Mapper#update}. + * @param {object} opts The `opts` argument passed to {@link Mapper#update}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterUpdate: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#updateAll}. If this method + * returns a promise then {@link Mapper#updateAll} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterUpdateAll + * @param {object} props The `props` argument passed to {@link Mapper#updateAll}. + * @param {object} query The `query` argument passed to {@link Mapper#updateAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#updateAll}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterUpdateAll: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#updateMany}. If this method + * returns a promise then {@link Mapper#updateMany} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterUpdateMany + * @param {array} records The `records` argument passed to {@link Mapper#updateMany}. + * @param {object} opts The `opts` argument passed to {@link Mapper#updateMany}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterUpdateMany: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#create}. If this method + * returns a promise then {@link Mapper#create} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeCreate + * @param {object} props The `props` argument passed to {@link Mapper#create}. + * @param {object} opts The `opts` argument passed to {@link Mapper#create}. + * @since 3.0.0 + */ + beforeCreate: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#createMany}. If this method + * returns a promise then {@link Mapper#createMany} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeCreateMany + * @param {array} records The `records` argument passed to {@link Mapper#createMany}. + * @param {object} opts The `opts` argument passed to {@link Mapper#createMany}. + * @since 3.0.0 + */ + beforeCreateMany: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#count}. If this method + * returns a promise then {@link Mapper#count} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeCount + * @param {object} query The `query` argument passed to {@link Mapper#count}. + * @param {object} opts The `opts` argument passed to {@link Mapper#count}. + * @since 3.0.0 + */ + beforeCount: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#destroy}. If this method + * returns a promise then {@link Mapper#destroy} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeDestroy + * @param {(string|number)} id The `id` argument passed to {@link Mapper#destroy}. + * @param {object} opts The `opts` argument passed to {@link Mapper#destroy}. + * @since 3.0.0 + */ + beforeDestroy: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#destroyAll}. If this method + * returns a promise then {@link Mapper#destroyAll} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeDestroyAll + * @param {query} query The `query` argument passed to {@link Mapper#destroyAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#destroyAll}. + * @since 3.0.0 + */ + beforeDestroyAll: notify, + + /** + * Mappers lifecycle hook called by {@link Mapper#find}. If this method + * returns a promise then {@link Mapper#find} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeFind + * @param {(string|number)} id The `id` argument passed to {@link Mapper#find}. + * @param {object} opts The `opts` argument passed to {@link Mapper#find}. + * @since 3.0.0 + */ + beforeFind: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#findAll}. If this method + * returns a promise then {@link Mapper#findAll} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeFindAll + * @param {object} query The `query` argument passed to {@link Mapper#findAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#findAll}. + * @since 3.0.0 + */ + beforeFindAll: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#sum}. If this method + * returns a promise then {@link Mapper#sum} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeSum + * @param {string} field The `field` argument passed to {@link Mapper#sum}. + * @param {object} query The `query` argument passed to {@link Mapper#sum}. + * @param {object} opts The `opts` argument passed to {@link Mapper#sum}. + * @since 3.0.0 + */ + beforeSum: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#update}. If this method + * returns a promise then {@link Mapper#update} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeUpdate + * @param {(string|number)} id The `id` argument passed to {@link Mapper#update}. + * @param {props} props The `props` argument passed to {@link Mapper#update}. + * @param {object} opts The `opts` argument passed to {@link Mapper#update}. + * @since 3.0.0 + */ + beforeUpdate: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#updateAll}. If this method + * returns a promise then {@link Mapper#updateAll} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeUpdateAll + * @param {object} props The `props` argument passed to {@link Mapper#updateAll}. + * @param {object} query The `query` argument passed to {@link Mapper#updateAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#updateAll}. + * @since 3.0.0 + */ + beforeUpdateAll: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#updateMany}. If this method + * returns a promise then {@link Mapper#updateMany} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeUpdateMany + * @param {array} records The `records` argument passed to {@link Mapper#updateMany}. + * @param {object} opts The `opts` argument passed to {@link Mapper#updateMany}. + * @since 3.0.0 + */ + beforeUpdateMany: notify, + + /** + * This method is called at the end of most lifecycle methods. It does the + * following: + * + * 1. If `opts.raw` is `true`, add this Mapper's configuration to the `opts` + * argument as metadata for the operation. + * 2. Wrap the result data appropriately using {@link Mapper#wrap}, which + * calls {@link Mapper#createRecord}. + * + * @method Mapper#_end + * @private + * @since 3.0.0 + */ + _end: function _end(result, opts, skip) { + if (opts.raw) { + utils._(result, opts); + } + if (skip) { + return result; + } + var _data = opts.raw ? result.data : result; + if (_data && utils.isFunction(this.wrap)) { + _data = this.wrap(_data, opts); + if (opts.raw) { + result.data = _data; + } else { + result = _data; + } + } + return result; + }, + + + /** + * Define a belongsTo relationship. Only useful if you're managing your + * Mappers manually and not using a Container or DataStore component. + * + * @example + * PostMapper.belongsTo(UserMapper, { + * // post.user_id points to user.id + * foreignKey: 'user_id' + * // user records will be attached to post records at "post.user" + * localField: 'user' + * }); + * + * CommentMapper.belongsTo(UserMapper, { + * // comment.user_id points to user.id + * foreignKey: 'user_id' + * // user records will be attached to comment records at "comment.user" + * localField: 'user' + * }); + * CommentMapper.belongsTo(PostMapper, { + * // comment.post_id points to post.id + * foreignKey: 'post_id' + * // post records will be attached to comment records at "comment.post" + * localField: 'post' + * }); + * + * @method Mapper#belongsTo + * @see http://www.js-data.io/v3.0/docs/relations + * @since 3.0.0 + */ + belongsTo: function belongsTo$$1(relatedMapper, opts) { + return belongsTo(relatedMapper, opts)(this); + }, + + + /** + * Select records according to the `query` argument and return the count. + * + * {@link Mapper#beforeCount} will be called before calling the adapter. + * {@link Mapper#afterCount} will be called after calling the adapter. + * + * @example + * // Get the number of published blog posts + * PostMapper.count({ status: 'published' }).then((numPublished) => { + * console.log(numPublished); // e.g. 45 + * }); + * + * @method Mapper#count + * @param {object} [query={}] Selection query. See {@link query}. + * @param {object} [query.where] See {@link query.where}. + * @param {number} [query.offset] See {@link query.offset}. + * @param {number} [query.limit] See {@link query.limit}. + * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}. + * @param {object} [opts] Configuration options. Refer to the `count` method + * of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @returns {Promise} Resolves with the count of the selected records. + * @since 3.0.0 + */ + count: function count(query, opts) { + return this.crud('count', query, opts); + }, + + + /** + * Fired during {@link Mapper#create}. See + * {@link Mapper~beforeCreateListener} for how to listen for this event. + * + * @event Mapper#beforeCreate + * @see Mapper~beforeCreateListener + * @see Mapper#create + */ + /** + * Callback signature for the {@link Mapper#event:beforeCreate} event. + * + * @example + * function onBeforeCreate (props, opts) { + * // do something + * } + * store.on('beforeCreate', onBeforeCreate); + * + * @callback Mapper~beforeCreateListener + * @param {object} props The `props` argument passed to {@link Mapper#beforeCreate}. + * @param {object} opts The `opts` argument passed to {@link Mapper#beforeCreate}. + * @see Mapper#event:beforeCreate + * @see Mapper#create + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#create}. See + * {@link Mapper~afterCreateListener} for how to listen for this event. + * + * @event Mapper#afterCreate + * @see Mapper~afterCreateListener + * @see Mapper#create + */ + /** + * Callback signature for the {@link Mapper#event:afterCreate} event. + * + * @example + * function onAfterCreate (props, opts, result) { + * // do something + * } + * store.on('afterCreate', onAfterCreate); + * + * @callback Mapper~afterCreateListener + * @param {object} props The `props` argument passed to {@link Mapper#afterCreate}. + * @param {object} opts The `opts` argument passed to {@link Mapper#afterCreate}. + * @param {object} result The `result` argument passed to {@link Mapper#afterCreate}. + * @see Mapper#event:afterCreate + * @see Mapper#create + * @since 3.0.0 + */ + /** + * Create and save a new the record using the provided `props`. + * + * {@link Mapper#beforeCreate} will be called before calling the adapter. + * {@link Mapper#afterCreate} will be called after calling the adapter. + * + * @example + * // Create and save a new blog post + * PostMapper.create({ + * title: 'Modeling your data', + * status: 'draft' + * }).then((post) => { + * console.log(post); // { id: 1234, status: 'draft', ... } + * }); + * + * @fires Mapper#beforeCreate + * @fires Mapper#afterCreate + * @method Mapper#create + * @param {object} props The properties for the new record. + * @param {object} [opts] Configuration options. Refer to the `create` method + * of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @param {string[]} [opts.with=[]] Relations to create in a cascading + * create if `props` contains nested relations. NOT performed in a + * transaction. Each nested create will result in another {@link Mapper#create} + * or {@link Mapper#createMany} call. + * @param {string[]} [opts.pass=[]] Relations to send to the adapter as part + * of the payload. Normally relations are not sent. + * @returns {Promise} Resolves with the created record. + * @since 3.0.0 + */ + create: function create(props, opts) { + var _this2 = this; + + // Default values for arguments + props || (props = {}); + opts || (opts = {}); + var originalRecord = props; + var parentRelationMap = {}; + var adapterResponse = {}; + + // Fill in "opts" with the Mapper's configuration + utils._(opts, this); + opts.adapter = this.getAdapterName(opts); + + opts.op = 'beforeCreate'; + return this._runHook(opts.op, props, opts).then(function (props) { + opts.with || (opts.with = []); + return _this2._createParentRecordIfRequired(props, opts); + }).then(function (relationMap) { + parentRelationMap = relationMap; + }).then(function () { + opts.op = 'create'; + return _this2._invokeAdapterMethod(opts.op, props, opts); + }).then(function (result) { + adapterResponse = result; + }).then(function () { + var createdProps = opts.raw ? adapterResponse.data : adapterResponse; + + return _this2._createOrAssignChildRecordIfRequired(createdProps, { + opts: opts, + parentRelationMap: parentRelationMap, + originalProps: props + }); + }).then(function (createdProps) { + return _this2._commitChanges(originalRecord, createdProps); + }).then(function (record) { + if (opts.raw) { + adapterResponse.data = record; + } else { + adapterResponse = record; + } + var result = _this2._end(adapterResponse, opts); + opts.op = 'afterCreate'; + return _this2._runHook(opts.op, props, opts, result); + }); + }, + _commitChanges: function _commitChanges(recordOrRecords, newValues) { + var _this3 = this; + + if (utils.isArray(recordOrRecords)) { + return recordOrRecords.map(function (record, i) { + return _this3._commitChanges(record, newValues[i]); + }); + } + + utils.set(recordOrRecords, newValues, { silent: true }); + + if (utils.isFunction(recordOrRecords.commit)) { + recordOrRecords.commit(); + } + + return recordOrRecords; + }, + + + /** + * Use {@link Mapper#createRecord} instead. + * @deprecated + * @method Mapper#createInstance + * @param {Object|Array} props See {@link Mapper#createRecord}. + * @param {object} [opts] See {@link Mapper#createRecord}. + * @returns {Object|Array} See {@link Mapper#createRecord}. + * @see Mapper#createRecord + * @since 3.0.0 + */ + createInstance: function createInstance(props, opts) { + return this.createRecord(props, opts); + }, + + + /** + * Creates parent record for relation types like BelongsTo or HasMany with localKeys + * in order to satisfy foreignKey dependency (so called child records). + * @param {object} props See {@link Mapper#create}. + * @param {object} opts See {@link Mapper#create}. + * @returns {Object} cached parent records map + * @see Mapper#create + * @since 3.0.0 + */ + _createParentRecordIfRequired: function _createParentRecordIfRequired(props, opts) { + var tasks = []; + var relations = []; + + utils.forEachRelation(this, opts, function (def, optsCopy) { + if (!def.isRequiresParentId() || !def.getLocalField(props)) { + return; + } + + optsCopy.raw = false; + relations.push(def); + tasks.push(def.createParentRecord(props, optsCopy)); + }); + + return utils.Promise.all(tasks).then(function (records) { + return relations.reduce(function (map, relation, index) { + relation.setLocalField(map, records[index]); + return map; + }, {}); + }); + }, + + + /** + * Creates child record for relation types like HasOne or HasMany with foreignKey + * in order to satisfy foreignKey dependency (so called parent records). + * @param {object} props See {@link Mapper#create}. + * @param {object} context contains collected information. + * @param {object} context.opts See {@link Mapper#create}. + * @param {object} context.parentRelationMap contains parent records map + * @param {object} context.originalProps contains data passed into {@link Mapper#create} method + * @return {Promise} updated props + * @see Mapper#create + * @since 3.0.0 + */ + _createOrAssignChildRecordIfRequired: function _createOrAssignChildRecordIfRequired(props, context) { + var tasks = []; + + utils.forEachRelation(this, context.opts, function (def, optsCopy) { + var relationData = def.getLocalField(context.originalProps); + + if (!relationData) { + return; + } + + optsCopy.raw = false; + // Create hasMany and hasOne after the main create because we needed + // a generated id to attach to these items + if (def.isRequiresChildId()) { + tasks.push(def.createChildRecord(props, relationData, optsCopy)); + } else if (def.isRequiresParentId()) { + var parent = def.getLocalField(context.parentRelationMap); + + if (parent) { + def.setLocalField(props, parent); + } + } + }); + + return utils.Promise.all(tasks).then(function () { + return props; + }); + }, + + + /** + * Fired during {@link Mapper#createMany}. See + * {@link Mapper~beforeCreateManyListener} for how to listen for this event. + * + * @event Mapper#beforeCreateMany + * @see Mapper~beforeCreateManyListener + * @see Mapper#createMany + */ + /** + * Callback signature for the {@link Mapper#event:beforeCreateMany} event. + * + * @example + * function onBeforeCreateMany (records, opts) { + * // do something + * } + * store.on('beforeCreateMany', onBeforeCreateMany); + * + * @callback Mapper~beforeCreateManyListener + * @param {object} records The `records` argument received by {@link Mapper#beforeCreateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreateMany}. + * @see Mapper#event:beforeCreateMany + * @see Mapper#createMany + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#createMany}. See + * {@link Mapper~afterCreateManyListener} for how to listen for this event. + * + * @event Mapper#afterCreateMany + * @see Mapper~afterCreateManyListener + * @see Mapper#createMany + */ + /** + * Callback signature for the {@link Mapper#event:afterCreateMany} event. + * + * @example + * function onAfterCreateMany (records, opts, result) { + * // do something + * } + * store.on('afterCreateMany', onAfterCreateMany); + * + * @callback Mapper~afterCreateManyListener + * @param {object} records The `records` argument received by {@link Mapper#afterCreateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterCreateMany}. + * @param {object} result The `result` argument received by {@link Mapper#afterCreateMany}. + * @see Mapper#event:afterCreateMany + * @see Mapper#createMany + * @since 3.0.0 + */ + /** + * Given an array of records, batch create them via an adapter. + * + * {@link Mapper#beforeCreateMany} will be called before calling the adapter. + * {@link Mapper#afterCreateMany} will be called after calling the adapter. + * + * @example + * // Create and save several new blog posts + * PostMapper.createMany([{ + * title: 'Modeling your data', + * status: 'draft' + * }, { + * title: 'Reading data', + * status: 'draft' + * }]).then((posts) => { + * console.log(posts[0]); // { id: 1234, status: 'draft', ... } + * console.log(posts[1]); // { id: 1235, status: 'draft', ... } + * }); + * + * @fires Mapper#beforeCreate + * @fires Mapper#afterCreate + * @method Mapper#createMany + * @param {Record[]} records Array of records to be created in one batch. + * @param {object} [opts] Configuration options. Refer to the `createMany` + * method of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @param {string[]} [opts.with=[]] Relations to create in a cascading + * create if `records` contains nested relations. NOT performed in a + * transaction. Each nested create will result in another {@link Mapper#createMany} + * call. + * @param {string[]} [opts.pass=[]] Relations to send to the adapter as part + * of the payload. Normally relations are not sent. + * @returns {Promise} Resolves with the created records. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/saving-data","Saving data"] + */ + createMany: function createMany(records, opts) { + var _this4 = this; + + // Default values for arguments + records || (records = []); + opts || (opts = {}); + var originalRecords = records; + var adapterResponse = void 0; + + // Fill in "opts" with the Mapper's configuration + utils._(opts, this); + opts.adapter = this.getAdapterName(opts); + + // beforeCreateMany lifecycle hook + opts.op = 'beforeCreateMany'; + return this._runHook(opts.op, records, opts).then(function (records) { + // Deep pre-create belongsTo relations + var belongsToRelationData = {}; + opts.with || (opts.with = []); + var tasks = []; + utils.forEachRelation(_this4, opts, function (def, optsCopy) { + var relationData = records.map(function (record) { + return def.getLocalField(record); + }).filter(Boolean); + if (def.type === belongsToType && relationData.length === records.length) { + // Create belongsTo relation first because we need a generated id to + // attach to the child + optsCopy.raw = false; + tasks.push(def.createLinked(relationData, optsCopy).then(function (relatedRecords) { + records.forEach(function (record, i) { + return def.setForeignKey(record, relatedRecords[i]); + }); + }).then(function (relatedRecords) { + def.setLocalField(belongsToRelationData, relatedRecords); + })); + } + }); + return utils.Promise.all(tasks).then(function () { + opts.op = 'createMany'; + return _this4._invokeAdapterMethod(opts.op, records, opts); + }).then(function (result) { + adapterResponse = result; + }).then(function () { + var createdRecordsData = opts.raw ? adapterResponse.data : adapterResponse; + + // Deep post-create hasOne relations + tasks = []; + utils.forEachRelation(_this4, opts, function (def, optsCopy) { + var relationData = records.map(function (record) { + return def.getLocalField(record); + }).filter(Boolean); + if (relationData.length !== records.length) { + return; + } + + optsCopy.raw = false; + var belongsToData = def.getLocalField(belongsToRelationData); + var task = void 0; + // Create hasMany and hasOne after the main create because we needed + // a generated id to attach to these items + if (def.type === hasManyType) { + // Not supported + _this4.log('warn', 'deep createMany of hasMany type not supported!'); + } else if (def.type === hasOneType) { + createdRecordsData.forEach(function (createdRecordData, i) { + def.setForeignKey(createdRecordData, relationData[i]); + }); + task = def.getRelation().createMany(relationData, optsCopy).then(function (relatedData) { + createdRecordsData.forEach(function (createdRecordData, i) { + def.setLocalField(createdRecordData, relatedData[i]); + }); + }); + } else if (def.type === belongsToType && belongsToData && belongsToData.length === createdRecordsData.length) { + createdRecordsData.forEach(function (createdRecordData, i) { + def.setLocalField(createdRecordData, belongsToData[i]); + }); + } + if (task) { + tasks.push(task); + } + }); + return utils.Promise.all(tasks).then(function () { + return _this4._commitChanges(originalRecords, createdRecordsData); + }); + }); + }).then(function (records) { + if (opts.raw) { + adapterResponse.data = records; + } else { + adapterResponse = records; + } + var result = _this4._end(adapterResponse, opts); + opts.op = 'afterCreateMany'; + return _this4._runHook(opts.op, records, opts, result); + }); + }, + + + /** + * Create an unsaved, uncached instance of this Mapper's + * {@link Mapper#recordClass}. + * + * Returns `props` if `props` is already an instance of + * {@link Mapper#recordClass}. + * + * __Note:__ This method does __not__ interact with any adapter, and does + * __not__ save any data. It only creates new objects in memory. + * + * @example + * // Create empty unsaved record instance + * const post = PostMapper.createRecord(); + * + * @example + * // Create an unsaved record instance with inital properties + * const post = PostMapper.createRecord({ + * title: 'Modeling your data', + * status: 'draft' + * }); + * + * @example + * // Create a record instance that corresponds to a saved record + * const post = PostMapper.createRecord({ + * // JSData thinks this record has been saved if it has a primary key + * id: 1234, + * title: 'Modeling your data', + * status: 'draft' + * }); + * + * @example + * // Create record instances from an array + * const posts = PostMapper.createRecord([{ + * title: 'Modeling your data', + * status: 'draft' + * }, { + * title: 'Reading data', + * status: 'draft' + * }]); + * + * @example + * // Records are validated by default + * import { Mapper } from 'js-data'; + * const PostMapper = new Mapper({ + * name: 'post', + * schema: { properties: { title: { type: 'string' } } } + * }); + * try { + * const post = PostMapper.createRecord({ + * title: 1234, + * }); + * } catch (err) { + * console.log(err.errors); // [{ expected: 'one of (string)', actual: 'number', path: 'title' }] + * } + * + * @example + * // Skip validation + * import { Mapper } from 'js-data'; + * const PostMapper = new Mapper({ + * name: 'post', + * schema: { properties: { title: { type: 'string' } } } + * }); + * const post = PostMapper.createRecord({ + * title: 1234, + * }, { noValidate: true }); + * console.log(post.isValid()); // false + * + * @method Mapper#createRecord + * @param {Object|Object[]} props The properties for the Record instance or an + * array of property objects for the Record instances. + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}. + * @returns {Record|Record[]} The Record instance or Record instances. + * @since 3.0.0 + */ + createRecord: function createRecord(props, opts) { + var _this5 = this; + + props || (props = {}); + if (utils.isArray(props)) { + return props.map(function (_props) { + return _this5.createRecord(_props, opts); + }); + } + if (!utils.isObject(props)) { + throw utils.err(DOMAIN$6 + '#createRecord', 'props')(400, 'array or object', props); + } + + if (this.relationList) { + this.relationList.forEach(function (def) { + def.ensureLinkedDataHasProperType(props, opts); + }); + } + var RecordCtor = this.recordClass; + + return !RecordCtor || props instanceof RecordCtor ? props : new RecordCtor(props, opts); + }, + + + /** + * Lifecycle invocation method. You probably won't call this method directly. + * + * @method Mapper#crud + * @param {string} method Name of the lifecycle method to invoke. + * @param {...*} args Arguments to pass to the lifecycle method. + * @returns {Promise} + * @since 3.0.0 + */ + crud: function crud(method) { + var _this6 = this; + + for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + var config = this.lifecycleMethods[method]; + if (!config) { + throw utils.err(DOMAIN$6 + '#crud', method)(404, 'method'); + } + + var upper = '' + method.charAt(0).toUpperCase() + method.substr(1); + var before = 'before' + upper; + var after = 'after' + upper; + + var op = void 0, + adapter = void 0; + + // Default values for arguments + config.defaults.forEach(function (value, i) { + if (args[i] === undefined) { + args[i] = utils.copy(value); + } + }); + + var opts = args[args.length - 1]; + + // Fill in "opts" with the Mapper's configuration + utils._(opts, this); + adapter = opts.adapter = this.getAdapterName(opts); + + // before lifecycle hook + op = opts.op = before; + return utils.resolve(this[op].apply(this, toConsumableArray(args))).then(function (_value) { + var _getAdapter; + + if (args[config.beforeAssign] !== undefined) { + // Allow for re-assignment from lifecycle hook + args[config.beforeAssign] = _value === undefined ? args[config.beforeAssign] : _value; + } + // Now delegate to the adapter + op = opts.op = method; + args = config.adapterArgs ? config.adapterArgs.apply(config, [_this6].concat(toConsumableArray(args))) : args; + _this6.dbg.apply(_this6, [op].concat(toConsumableArray(args))); + return utils.resolve((_getAdapter = _this6.getAdapter(adapter))[op].apply(_getAdapter, [_this6].concat(toConsumableArray(args)))); + }).then(function (result) { + result = _this6._end(result, opts, !!config.skip); + args.push(result); + // after lifecycle hook + op = opts.op = after; + return utils.resolve(_this6[op].apply(_this6, toConsumableArray(args))).then(function (_result) { + // Allow for re-assignment from lifecycle hook + return _result === undefined ? result : _result; + }); + }); + }, + + + /** + * Fired during {@link Mapper#destroy}. See + * {@link Mapper~beforeDestroyListener} for how to listen for this event. + * + * @event Mapper#beforeDestroy + * @see Mapper~beforeDestroyListener + * @see Mapper#destroy + */ + /** + * Callback signature for the {@link Mapper#event:beforeDestroy} event. + * + * @example + * function onBeforeDestroy (id, opts) { + * // do something + * } + * store.on('beforeDestroy', onBeforeDestroy); + * + * @callback Mapper~beforeDestroyListener + * @param {string|number} id The `id` argument passed to {@link Mapper#beforeDestroy}. + * @param {object} opts The `opts` argument passed to {@link Mapper#beforeDestroy}. + * @see Mapper#event:beforeDestroy + * @see Mapper#destroy + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#destroy}. See + * {@link Mapper~afterDestroyListener} for how to listen for this event. + * + * @event Mapper#afterDestroy + * @see Mapper~afterDestroyListener + * @see Mapper#destroy + */ + /** + * Callback signature for the {@link Mapper#event:afterDestroy} event. + * + * @example + * function onAfterDestroy (id, opts, result) { + * // do something + * } + * store.on('afterDestroy', onAfterDestroy); + * + * @callback Mapper~afterDestroyListener + * @param {string|number} id The `id` argument passed to {@link Mapper#afterDestroy}. + * @param {object} opts The `opts` argument passed to {@link Mapper#afterDestroy}. + * @param {object} result The `result` argument passed to {@link Mapper#afterDestroy}. + * @see Mapper#event:afterDestroy + * @see Mapper#destroy + * @since 3.0.0 + */ + /** + * Using an adapter, destroy the record with the given primary key. + * + * {@link Mapper#beforeDestroy} will be called before destroying the record. + * {@link Mapper#afterDestroy} will be called after destroying the record. + * + * @example + * // Destroy a specific blog post + * PostMapper.destroy(1234).then(() => { + * // Blog post #1234 has been destroyed + * }); + * + * @example + * // Get full response + * PostMapper.destroy(1234, { raw: true }).then((result) => { + * console.log(result.deleted); e.g. 1 + * console.log(...); // etc., more metadata can be found on the result + * }); + * + * @fires Mapper#beforeDestroy + * @fires Mapper#afterDestroy + * @method Mapper#destroy + * @param {(string|number)} id The primary key of the record to destroy. + * @param {object} [opts] Configuration options. Refer to the `destroy` method + * of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @returns {Promise} Resolves when the record has been destroyed. Resolves + * even if no record was found to be destroyed. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/saving-data","Saving data"] + */ + destroy: function destroy(id, opts) { + return this.crud('destroy', id, opts); + }, + + + /** + * Fired during {@link Mapper#destroyAll}. See + * {@link Mapper~beforeDestroyAllListener} for how to listen for this event. + * + * @event Mapper#beforeDestroyAll + * @see Mapper~beforeDestroyAllListener + * @see Mapper#destroyAll + */ + /** + * Callback signature for the {@link Mapper#event:beforeDestroyAll} event. + * + * @example + * function onBeforeDestroyAll (query, opts) { + * // do something + * } + * store.on('beforeDestroyAll', onBeforeDestroyAll); + * + * @callback Mapper~beforeDestroyAllListener + * @param {object} query The `query` argument passed to {@link Mapper#beforeDestroyAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#beforeDestroyAll}. + * @see Mapper#event:beforeDestroyAll + * @see Mapper#destroyAll + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#destroyAll}. See + * {@link Mapper~afterDestroyAllListener} for how to listen for this event. + * + * @event Mapper#afterDestroyAll + * @see Mapper~afterDestroyAllListener + * @see Mapper#destroyAll + */ + /** + * Callback signature for the {@link Mapper#event:afterDestroyAll} event. + * + * @example + * function onAfterDestroyAll (query, opts, result) { + * // do something + * } + * store.on('afterDestroyAll', onAfterDestroyAll); + * + * @callback Mapper~afterDestroyAllListener + * @param {object} query The `query` argument passed to {@link Mapper#afterDestroyAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#afterDestroyAll}. + * @param {object} result The `result` argument passed to {@link Mapper#afterDestroyAll}. + * @see Mapper#event:afterDestroyAll + * @see Mapper#destroyAll + * @since 3.0.0 + */ + /** + * Destroy the records selected by `query` via an adapter. If no `query` is + * provided then all records will be destroyed. + * + * {@link Mapper#beforeDestroyAll} will be called before destroying the records. + * {@link Mapper#afterDestroyAll} will be called after destroying the records. + * + * @example + * // Destroy all blog posts + * PostMapper.destroyAll().then(() => { + * // All blog posts have been destroyed + * }); + * + * @example + * // Destroy all "draft" blog posts + * PostMapper.destroyAll({ status: 'draft' }).then(() => { + * // All "draft" blog posts have been destroyed + * }); + * + * @example + * // Get full response + * const query = null; + * const options = { raw: true }; + * PostMapper.destroyAll(query, options).then((result) => { + * console.log(result.deleted); e.g. 14 + * console.log(...); // etc., more metadata can be found on the result + * }); + * + * @fires Mapper#beforeDestroyAll + * @fires Mapper#afterDestroyAll + * @method Mapper#destroyAll + * @param {object} [query={}] Selection query. See {@link query}. + * @param {object} [query.where] See {@link query.where}. + * @param {number} [query.offset] See {@link query.offset}. + * @param {number} [query.limit] See {@link query.limit}. + * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}. + * @param {object} [opts] Configuration options. Refer to the `destroyAll` + * method of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @returns {Promise} Resolves when the records have been destroyed. Resolves + * even if no records were found to be destroyed. + * @see query + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/saving-data","Saving data"] + */ + destroyAll: function destroyAll(query, opts) { + return this.crud('destroyAll', query, opts); + }, + + + /** + * Fired during {@link Mapper#find}. See + * {@link Mapper~beforeFindListener} for how to listen for this event. + * + * @event Mapper#beforeFind + * @see Mapper~beforeFindListener + * @see Mapper#find + */ + /** + * Callback signature for the {@link Mapper#event:beforeFind} event. + * + * @example + * function onBeforeFind (id, opts) { + * // do something + * } + * store.on('beforeFind', onBeforeFind); + * + * @callback Mapper~beforeFindListener + * @param {string|number} id The `id` argument passed to {@link Mapper#beforeFind}. + * @param {object} opts The `opts` argument passed to {@link Mapper#beforeFind}. + * @see Mapper#event:beforeFind + * @see Mapper#find + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#find}. See + * {@link Mapper~afterFindListener} for how to listen for this event. + * + * @event Mapper#afterFind + * @see Mapper~afterFindListener + * @see Mapper#find + */ + /** + * Callback signature for the {@link Mapper#event:afterFind} event. + * + * @example + * function onAfterFind (id, opts, result) { + * // do something + * } + * store.on('afterFind', onAfterFind); + * + * @callback Mapper~afterFindListener + * @param {string|number} id The `id` argument passed to {@link Mapper#afterFind}. + * @param {object} opts The `opts` argument passed to {@link Mapper#afterFind}. + * @param {object} result The `result` argument passed to {@link Mapper#afterFind}. + * @see Mapper#event:afterFind + * @see Mapper#find + * @since 3.0.0 + */ + /** + * Retrieve via an adapter the record with the given primary key. + * + * {@link Mapper#beforeFind} will be called before calling the adapter. + * {@link Mapper#afterFind} will be called after calling the adapter. + * + * @example + * PostMapper.find(1).then((post) => { + * console.log(post); // { id: 1, ...} + * }); + * + * @example + * // Get full response + * PostMapper.find(1, { raw: true }).then((result) => { + * console.log(result.data); // { id: 1, ...} + * console.log(result.found); // 1 + * console.log(...); // etc., more metadata can be found on the result + * }); + * + * @fires Mapper#beforeFind + * @fires Mapper#afterFind + * @method Mapper#find + * @param {(string|number)} id The primary key of the record to retrieve. + * @param {object} [opts] Configuration options. Refer to the `find` method + * of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @param {string[]} [opts.with=[]] Relations to eager load in the request. + * @returns {Promise} Resolves with the found record. Resolves with + * `undefined` if no record was found. + * @see http://www.js-data.io/v3.0/docs/reading-data + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/reading-data","Reading data"] + */ + find: function find(id, opts) { + return this.crud('find', id, opts); + }, + + + /** + * Fired during {@link Mapper#findAll}. See + * {@link Mapper~beforeFindAllListener} for how to listen for this event. + * + * @event Mapper#beforeFindAll + * @see Mapper~beforeFindAllListener + * @see Mapper#findAll + */ + /** + * Callback signature for the {@link Mapper#event:beforeFindAll} event. + * + * @example + * function onBeforeFindAll (query, opts) { + * // do something + * } + * store.on('beforeFindAll', onBeforeFindAll); + * + * @callback Mapper~beforeFindAllListener + * @param {object} query The `query` argument passed to {@link Mapper#beforeFindAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#beforeFindAll}. + * @see Mapper#event:beforeFindAll + * @see Mapper#findAll + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#findAll}. See + * {@link Mapper~afterFindAllListener} for how to listen for this event. + * + * @event Mapper#afterFindAll + * @see Mapper~afterFindAllListener + * @see Mapper#findAll + */ + /** + * Callback signature for the {@link Mapper#event:afterFindAll} event. + * + * @example + * function onAfterFindAll (query, opts, result) { + * // do something + * } + * store.on('afterFindAll', onAfterFindAll); + * + * @callback Mapper~afterFindAllListener + * @param {object} query The `query` argument passed to {@link Mapper#afterFindAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#afterFindAll}. + * @param {object} result The `result` argument passed to {@link Mapper#afterFindAll}. + * @see Mapper#event:afterFindAll + * @see Mapper#findAll + * @since 3.0.0 + */ + /** + * Using the `query` argument, select records to retrieve via an adapter. + * + * {@link Mapper#beforeFindAll} will be called before calling the adapter. + * {@link Mapper#afterFindAll} will be called after calling the adapter. + * + * @example + * // Find all "published" blog posts + * PostMapper.findAll({ status: 'published' }).then((posts) => { + * console.log(posts); // [{ id: 1, status: 'published', ...}, ...] + * }); + * + * @example + * // Get full response + * PostMapper.findAll({ status: 'published' }, { raw: true }).then((result) => { + * console.log(result.data); // [{ id: 1, status: 'published', ...}, ...] + * console.log(result.found); // e.g. 13 + * console.log(...); // etc., more metadata can be found on the result + * }); + * + * @fires Mapper#beforeFindAll + * @fires Mapper#afterFindAll + * @method Mapper#findAll + * @param {object} [query={}] Selection query. See {@link query}. + * @param {object} [query.where] See {@link query.where}. + * @param {number} [query.offset] See {@link query.offset}. + * @param {number} [query.limit] See {@link query.limit}. + * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}. + * @param {object} [opts] Configuration options. Refer to the `findAll` method + * of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @param {string[]} [opts.with=[]] Relations to eager load in the request. + * @returns {Promise} Resolves with the found records, if any. + * @see query + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/reading-data","Reading data"] + */ + findAll: function findAll(query, opts) { + return this.crud('findAll', query, opts); + }, + + + /** + * Return the registered adapter with the given name or the default adapter if + * no name is provided. + * + * @method Mapper#getAdapter + * @param {string} [name] The name of the adapter to retrieve. + * @returns {Adapter} The adapter. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/connecting-to-a-data-source","Connecting to a data source"] + */ + getAdapter: function getAdapter(name) { + this.dbg('getAdapter', 'name:', name); + var adapter = this.getAdapterName(name); + if (!adapter) { + throw utils.err(DOMAIN$6 + '#getAdapter', 'name')(400, 'string', name); + } + return this.getAdapters()[adapter]; + }, + + + /** + * Return the name of a registered adapter based on the given name or options, + * or the name of the default adapter if no name provided. + * + * @method Mapper#getAdapterName + * @param {(Object|string)} [opts] The name of an adapter or options, if any. + * @returns {string} The name of the adapter. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/connecting-to-a-data-source","Connecting to a data source"] + */ + getAdapterName: function getAdapterName(opts) { + opts || (opts = {}); + if (utils.isString(opts)) { + opts = { adapter: opts }; + } + return opts.adapter || opts.defaultAdapter; + }, + + + /** + * Get the object of registered adapters for this Mapper. + * + * @method Mapper#getAdapters + * @returns {Object} {@link Mapper#_adapters} + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/connecting-to-a-data-source","Connecting to a data source"] + */ + getAdapters: function getAdapters() { + return this._adapters; + }, + + + /** + * Returns this Mapper's {@link Schema}. + * + * @method Mapper#getSchema + * @returns {Schema} This Mapper's {@link Schema}. + * @see Mapper#schema + * @since 3.0.0 + */ + getSchema: function getSchema() { + return this.schema; + }, + + + /** + * Defines a hasMany relationship. Only useful if you're managing your + * Mappers manually and not using a Container or DataStore component. + * + * @example + * UserMapper.hasMany(PostMapper, { + * // post.user_id points to user.id + * foreignKey: 'user_id' + * // post records will be attached to user records at "user.posts" + * localField: 'posts' + * }); + * + * @method Mapper#hasMany + * @see http://www.js-data.io/v3.0/docs/relations + * @since 3.0.0 + */ + hasMany: function hasMany$$1(relatedMapper, opts) { + return hasMany(relatedMapper, opts)(this); + }, + + + /** + * Defines a hasOne relationship. Only useful if you're managing your Mappers + * manually and not using a {@link Container} or {@link DataStore} component. + * + * @example + * UserMapper.hasOne(ProfileMapper, { + * // profile.user_id points to user.id + * foreignKey: 'user_id' + * // profile records will be attached to user records at "user.profile" + * localField: 'profile' + * }); + * + * @method Mapper#hasOne + * @see http://www.js-data.io/v3.0/docs/relations + * @since 3.0.0 + */ + hasOne: function hasOne$$1(relatedMapper, opts) { + return hasOne(relatedMapper, opts)(this); + }, + + + /** + * Return whether `record` is an instance of this Mapper's recordClass. + * + * @example + * const post = PostMapper.createRecord(); + * + * console.log(PostMapper.is(post)); // true + * // Equivalent to what's above + * console.log(post instanceof PostMapper.recordClass); // true + * + * @method Mapper#is + * @param {Object|Record} record The record to check. + * @returns {boolean} Whether `record` is an instance of this Mapper's + * {@link Mapper#recordClass}. + * @since 3.0.0 + */ + is: function is(record) { + var recordClass = this.recordClass; + return recordClass ? record instanceof recordClass : false; + }, + + + /** + * Register an adapter on this Mapper under the given name. + * + * @method Mapper#registerAdapter + * @param {string} name The name of the adapter to register. + * @param {Adapter} adapter The adapter to register. + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.default=false] Whether to make the adapter the + * default adapter for this Mapper. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/connecting-to-a-data-source","Connecting to a data source"] + */ + registerAdapter: function registerAdapter(name, adapter, opts) { + opts || (opts = {}); + this.getAdapters()[name] = adapter; + // Optionally make it the default adapter for the target. + if (opts === true || opts.default) { + this.defaultAdapter = name; + } + }, + _runHook: function _runHook(hookName) { + for (var _len3 = arguments.length, hookArgs = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + hookArgs[_key3 - 1] = arguments[_key3]; + } + + var defaultValueIndex = hookName.indexOf('after') === 0 ? hookArgs.length - 1 : 0; + + return utils.resolve(this[hookName].apply(this, hookArgs)).then(function (overridenResult) { + return overridenResult === undefined ? hookArgs[defaultValueIndex] : overridenResult; + }); + }, + _invokeAdapterMethod: function _invokeAdapterMethod(method, propsOrRecords, opts) { + var _this7 = this; + + var conversionOptions = { with: opts.pass || [] }; + var object = void 0; + + this.dbg(opts.op, propsOrRecords, opts); + + if (utils.isArray(propsOrRecords)) { + object = propsOrRecords.map(function (record) { + return _this7.toJSON(record, conversionOptions); + }); + } else { + object = this.toJSON(propsOrRecords, conversionOptions); + } + + return this.getAdapter(opts.adapter)[method](this, object, opts); + }, + + + /** + * Select records according to the `query` argument, and aggregate the sum + * value of the property specified by `field`. + * + * {@link Mapper#beforeSum} will be called before calling the adapter. + * {@link Mapper#afterSum} will be called after calling the adapter. + * + * @example + * PurchaseOrderMapper.sum('amount', { status: 'paid' }).then((amountPaid) => { + * console.log(amountPaid); // e.g. 451125.34 + * }); + * + * @method Mapper#sum + * @param {string} field The field to sum. + * @param {object} [query={}] Selection query. See {@link query}. + * @param {object} [query.where] See {@link query.where}. + * @param {number} [query.offset] See {@link query.offset}. + * @param {number} [query.limit] See {@link query.limit}. + * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}. + * @param {object} [opts] Configuration options. Refer to the `sum` method + * of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @returns {Promise} Resolves with the aggregated sum. + * @since 3.0.0 + */ + sum: function sum(field, query, opts) { + return this.crud('sum', field, query, opts); + }, + + + /** + * Return a plain object representation of the given record. Relations can + * be optionally be included. Non-schema properties can be excluded. + * + * @example + * import { Mapper, Schema } from 'js-data'; + * const PersonMapper = new Mapper({ + * name: 'person', + * schema: { + * properties: { + * name: { type: 'string' }, + * id: { type: 'string' } + * } + * } + * }); + * const person = PersonMapper.createRecord({ id: 1, name: 'John', foo: 'bar' }); + * // "foo" is stripped by toJSON() + * console.log(PersonMapper.toJSON(person)); // {"id":1,"name":"John"} + * + * const PersonRelaxedMapper = new Mapper({ + * name: 'personRelaxed', + * schema: { + * properties: { + * name: { type: 'string' }, + * id: { type: 'string' } + * }, + * additionalProperties: true + * } + * }); + * const person2 = PersonRelaxedMapper.createRecord({ id: 1, name: 'John', foo: 'bar' }); + * // "foo" is not stripped by toJSON + * console.log(PersonRelaxedMapper.toJSON(person2)); // {"id":1,"name":"John","foo":"bar"} + * + * @method Mapper#toJSON + * @param {Record|Record[]} records Record or records from which to create a + * POJO representation. + * @param {object} [opts] Configuration options. + * @param {string[]} [opts.with] Array of relation names or relation fields + * to include in the POJO representation. + * @param {boolean} [opts.withAll] Whether to simply include all relations in + * the representation. Overrides `opts.with`. + * @returns {Object|Object[]} POJO representation of the record or records. + * @since 3.0.0 + */ + toJSON: function toJSON(records, opts) { + var _this8 = this; + + var record = void 0; + opts || (opts = {}); + if (utils.isArray(records)) { + return records.map(function (record) { + return _this8.toJSON(record, opts); + }); + } else { + record = records; + } + var relationFields = (this ? this.relationFields : []) || []; + var json = {}; + + // Copy properties defined in the schema + if (this && this.schema) { + json = this.schema.pick(record); + } else { + for (var key in record) { + if (relationFields.indexOf(key) === -1) { + json[key] = utils.plainCopy(record[key]); + } + } + } + + // The user wants to include relations in the resulting plain object representation + if (this && opts.withAll) { + opts.with = relationFields.slice(); + } + if (this && opts.with) { + if (utils.isString(opts.with)) { + opts.with = [opts.with]; + } + utils.forEachRelation(this, opts, function (def, optsCopy) { + var relationData = def.getLocalField(record); + if (relationData) { + // The actual recursion + if (utils.isArray(relationData)) { + def.setLocalField(json, relationData.map(function (item) { + return def.getRelation().toJSON(item, optsCopy); + })); + } else { + def.setLocalField(json, def.getRelation().toJSON(relationData, optsCopy)); + } + } + }); + } + return json; + }, + + + /** + * Fired during {@link Mapper#update}. See + * {@link Mapper~beforeUpdateListener} for how to listen for this event. + * + * @event Mapper#beforeUpdate + * @see Mapper~beforeUpdateListener + * @see Mapper#update + */ + /** + * Callback signature for the {@link Mapper#event:beforeUpdate} event. + * + * @example + * function onBeforeUpdate (id, props, opts) { + * // do something + * } + * store.on('beforeUpdate', onBeforeUpdate); + * + * @callback Mapper~beforeUpdateListener + * @param {string|number} id The `id` argument passed to {@link Mapper#beforeUpdate}. + * @param {object} props The `props` argument passed to {@link Mapper#beforeUpdate}. + * @param {object} opts The `opts` argument passed to {@link Mapper#beforeUpdate}. + * @see Mapper#event:beforeUpdate + * @see Mapper#update + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#update}. See + * {@link Mapper~afterUpdateListener} for how to listen for this event. + * + * @event Mapper#afterUpdate + * @see Mapper~afterUpdateListener + * @see Mapper#update + */ + /** + * Callback signature for the {@link Mapper#event:afterUpdate} event. + * + * @example + * function onAfterUpdate (id, props, opts, result) { + * // do something + * } + * store.on('afterUpdate', onAfterUpdate); + * + * @callback Mapper~afterUpdateListener + * @param {string|number} id The `id` argument passed to {@link Mapper#afterUpdate}. + * @param {object} props The `props` argument passed to {@link Mapper#afterUpdate}. + * @param {object} opts The `opts` argument passed to {@link Mapper#afterUpdate}. + * @param {object} result The `result` argument passed to {@link Mapper#afterUpdate}. + * @see Mapper#event:afterUpdate + * @see Mapper#update + * @since 3.0.0 + */ + /** + * Using an adapter, update the record with the primary key specified by the + * `id` argument. + * + * {@link Mapper#beforeUpdate} will be called before updating the record. + * {@link Mapper#afterUpdate} will be called after updating the record. + * + * @example + * // Update a specific post + * PostMapper.update(1234, { + * status: 'published', + * published_at: new Date() + * }).then((post) => { + * console.log(post); // { id: 1234, status: 'published', ... } + * }); + * + * @fires Mapper#beforeUpdate + * @fires Mapper#afterUpdate + * @method Mapper#update + * @param {(string|number)} id The primary key of the record to update. + * @param {object} props The update to apply to the record. + * @param {object} [opts] Configuration options. Refer to the `update` method + * of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * transaction. + * @returns {Promise} Resolves with the updated record. Rejects if the record + * could not be found. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/saving-data","Saving data"] + */ + update: function update(id, props, opts) { + return this.crud('update', id, props, opts); + }, + + + /** + * Fired during {@link Mapper#updateAll}. See + * {@link Mapper~beforeUpdateAllListener} for how to listen for this event. + * + * @event Mapper#beforeUpdateAll + * @see Mapper~beforeUpdateAllListener + * @see Mapper#updateAll + */ + /** + * Callback signature for the {@link Mapper#event:beforeUpdateAll} event. + * + * @example + * function onBeforeUpdateAll (props, query, opts) { + * // do something + * } + * store.on('beforeUpdateAll', onBeforeUpdateAll); + * + * @callback Mapper~beforeUpdateAllListener + * @param {object} props The `props` argument received by {@link Mapper#beforeUpdateAll}. + * @param {object} query The `query` argument received by {@link Mapper#beforeUpdateAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateAll}. + * @see Mapper#event:beforeUpdateAll + * @see Mapper#updateAll + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#updateAll}. See + * {@link Mapper~afterUpdateAllListener} for how to listen for this event. + * + * @event Mapper#afterUpdateAll + * @see Mapper~afterUpdateAllListener + * @see Mapper#updateAll + */ + /** + * Callback signature for the {@link Mapper#event:afterUpdateAll} event. + * + * @example + * function onAfterUpdateAll (props, query, opts, result) { + * // do something + * } + * store.on('afterUpdateAll', onAfterUpdateAll); + * + * @callback Mapper~afterUpdateAllListener + * @param {object} props The `props` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} query The `query` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} result The `result` argument received by {@link Mapper#afterUpdateAll}. + * @see Mapper#event:afterUpdateAll + * @see Mapper#updateAll + * @since 3.0.0 + */ + /** + * Using the `query` argument, perform the a single updated to the selected + * records. + * + * {@link Mapper#beforeUpdateAll} will be called before making the update. + * {@link Mapper#afterUpdateAll} will be called after making the update. + * + * @example + * // Turn all of John's blog posts into drafts. + * const update = { status: draft: published_at: null }; + * const query = { userId: 1234 }; + * PostMapper.updateAll(update, query).then((posts) => { + * console.log(posts); // [...] + * }); + * + * @fires Mapper#beforeUpdateAll + * @fires Mapper#afterUpdateAll + * @method Mapper#updateAll + * @param {object} props Update to apply to selected records. + * @param {object} [query={}] Selection query. See {@link query}. + * @param {object} [query.where] See {@link query.where}. + * @param {number} [query.offset] See {@link query.offset}. + * @param {number} [query.limit] See {@link query.limit}. + * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}. + * @param {object} [opts] Configuration options. Refer to the `updateAll` + * method of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @returns {Promise} Resolves with the update records, if any. + * @see query + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/saving-data","Saving data"] + */ + updateAll: function updateAll(props, query, opts) { + return this.crud('updateAll', props, query, opts); + }, + + + /** + * Fired during {@link Mapper#updateMany}. See + * {@link Mapper~beforeUpdateManyListener} for how to listen for this event. + * + * @event Mapper#beforeUpdateMany + * @see Mapper~beforeUpdateManyListener + * @see Mapper#updateMany + */ + /** + * Callback signature for the {@link Mapper#event:beforeUpdateMany} event. + * + * @example + * function onBeforeUpdateMany (records, opts) { + * // do something + * } + * store.on('beforeUpdateMany', onBeforeUpdateMany); + * + * @callback Mapper~beforeUpdateManyListener + * @param {object} records The `records` argument received by {@link Mapper#beforeUpdateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateMany}. + * @see Mapper#event:beforeUpdateMany + * @see Mapper#updateMany + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#updateMany}. See + * {@link Mapper~afterUpdateManyListener} for how to listen for this event. + * + * @event Mapper#afterUpdateMany + * @see Mapper~afterUpdateManyListener + * @see Mapper#updateMany + */ + /** + * Callback signature for the {@link Mapper#event:afterUpdateMany} event. + * + * @example + * function onAfterUpdateMany (records, opts, result) { + * // do something + * } + * store.on('afterUpdateMany', onAfterUpdateMany); + * + * @callback Mapper~afterUpdateManyListener + * @param {object} records The `records` argument received by {@link Mapper#afterUpdateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateMany}. + * @param {object} result The `result` argument received by {@link Mapper#afterUpdateMany}. + * @see Mapper#event:afterUpdateMany + * @see Mapper#updateMany + * @since 3.0.0 + */ + /** + * Given an array of updates, perform each of the updates via an adapter. Each + * "update" is a hash of properties with which to update an record. Each + * update must contain the primary key of the record to be updated. + * + * {@link Mapper#beforeUpdateMany} will be called before making the update. + * {@link Mapper#afterUpdateMany} will be called after making the update. + * + * @example + * PostMapper.updateMany([ + * { id: 1234, status: 'draft' }, + * { id: 2468, status: 'published', published_at: new Date() } + * ]).then((posts) => { + * console.log(posts); // [...] + * }); + * + * @fires Mapper#beforeUpdateMany + * @fires Mapper#afterUpdateMany + * @method Mapper#updateMany + * @param {Record[]} records Array up record updates. + * @param {object} [opts] Configuration options. Refer to the `updateMany` + * method of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @returns {Promise} Resolves with the updated records. Rejects if any of the + * records could be found. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/saving-data","Saving data"] + */ + updateMany: function updateMany(records, opts) { + return this.crud('updateMany', records, opts); + }, + + + /** + * Validate the given record or records according to this Mapper's + * {@link Schema}. If there are no validation errors then the return value + * will be `undefined`. + * + * @example + * import {Mapper, Schema} from 'js-data' + * const PersonSchema = new Schema({ + * properties: { + * name: { type: 'string' }, + * id: { type: 'string' } + * } + * }); + * const PersonMapper = new Mapper({ + * name: 'person', + * schema: PersonSchema + * }); + * let errors = PersonMapper.validate({ name: 'John' }); + * console.log(errors); // undefined + * errors = PersonMapper.validate({ name: 123 }); + * console.log(errors); // [{ expected: 'one of (string)', actual: 'number', path: 'name' }] + * + * @method Mapper#validate + * @param {Object|Object[]} record The record or records to validate. + * @param {object} [opts] Configuration options. Passed to + * {@link Schema#validate}. + * @returns {Object[]} Array of errors or `undefined` if no errors. + * @since 3.0.0 + */ + validate: function validate(record, opts) { + opts || (opts = {}); + var schema = this.getSchema(); + if (!schema) { + return; + } + var _opts = utils.pick(opts, ['existingOnly']); + if (utils.isArray(record)) { + var errors = record.map(function (_record) { + return schema.validate(_record, utils.pick(_opts, ['existingOnly'])); + }); + + return errors.some(Boolean) ? errors : undefined; + } + return schema.validate(record, _opts); + }, + + + /** + * Method used to wrap data returned by an adapter with this Mapper's + * {@link Mapper#recordClass}. This method is used by all of a Mapper's CRUD + * methods. The provided implementation of this method assumes that the `data` + * passed to it is a record or records that need to be wrapped with + * {@link Mapper#createRecord}. Override with care. + * + * Provided implementation of {@link Mapper#wrap}: + * + * ``` + * function (data, opts) { + * return this.createRecord(data, opts); + * } + * ``` + * + * @example + * const PostMapper = new Mapper({ + * name: 'post', + * // Override to customize behavior + * wrap (data, opts) { + * const originalWrap = this.constructor.prototype.wrap; + * // Let's say "GET /post" doesn't return JSON quite like JSData expects, + * // but the actual post records are nested under a "posts" field. So, + * // we override Mapper#wrap to handle this special case. + * if (opts.op === 'findAll') { + * return originalWrap.call(this, data.posts, opts); + * } + * // Otherwise perform original behavior + * return originalWrap.call(this, data, opts); + * } + * }); + * + * @method Mapper#wrap + * @param {Object|Object[]} data The record or records to be wrapped. + * @param {object} [opts] Configuration options. Passed to {@link Mapper#createRecord}. + * @returns {Record|Record[]} The wrapped record or records. + * @since 3.0.0 + */ + wrap: function wrap(data, opts) { + return this.createRecord(data, opts); + }, + + + /** + * @ignore + */ + defineRelations: function defineRelations() { + var _this9 = this; + + // Setup the mapper's relations, including generating Mapper#relationList + // and Mapper#relationFields + utils.forOwn(this.relations, function (group, type) { + utils.forOwn(group, function (relations, _name) { + if (utils.isObject(relations)) { + relations = [relations]; + } + relations.forEach(function (def) { + var relatedMapper = _this9.datastore.getMapperByName(_name) || _name; + def.getRelation = function () { + return _this9.datastore.getMapper(_name); + }; + + if (typeof Relation[type] !== 'function') { + throw utils.err(DOMAIN$6, 'defineRelations')(400, 'relation type (hasOne, hasMany, etc)', type, true); + } + + _this9[type](relatedMapper, def); + }); + }); + }); + } +}); + +/** + * Create a subclass of this Mapper: + * + * @example Mapper.extend + * const JSData = require('js-data'); + * const { Mapper } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomMapperClass extends Mapper { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * }; + * const customMapper = new CustomMapperClass(); + * console.log(customMapper.foo()); + * console.log(CustomMapperClass.beep()); + * + * // Extend the class using alternate method. + * const OtherMapperClass = Mapper.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherMapper = new OtherMapperClass(); + * console.log(otherMapper.foo()); + * console.log(OtherMapperClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherMapperClass () { + * Mapper.call(this); + * this.created_at = new Date().getTime(); + * } + * Mapper.extend({ + * constructor: AnotherMapperClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }) + * const anotherMapper = new AnotherMapperClass(); + * console.log(anotherMapper.created_at); + * console.log(anotherMapper.foo()); + * console.log(AnotherMapperClass.beep()); + * + * @method Mapper.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this Mapper class. + * @since 3.0.0 + */ + +var DOMAIN$5 = 'Container'; + +var proxiedMapperMethods = [ +/** + * Wrapper for {@link Mapper#count}. + * + * @example + * // Get the number of published blog posts + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.count('post', { status: 'published' }).then((numPublished) => { + * console.log(numPublished); // e.g. 45 + * }); + * + * @method Container#count + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} [query] See {@link Mapper#count}. + * @param {object} [opts] See {@link Mapper#count}. + * @returns {Promise} See {@link Mapper#count}. + * @see Mapper#count + * @since 3.0.0 + */ +'count', + +/** + * Fired during {@link Container#create}. See + * {@link Container~beforeCreateListener} for how to listen for this event. + * + * @event Container#beforeCreate + * @see Container~beforeCreateListener + * @see Container#create + */ +/** + * Callback signature for the {@link Container#event:beforeCreate} event. + * + * @example + * function onBeforeCreate (mapperName, props, opts) { + * // do something + * } + * store.on('beforeCreate', onBeforeCreate); + * + * @callback Container~beforeCreateListener + * @param {string} name The `name` argument received by {@link Mapper#beforeCreate}. + * @param {object} props The `props` argument received by {@link Mapper#beforeCreate}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreate}. + * @see Container#event:beforeCreate + * @see Container#create + * @since 3.0.0 + */ +/** + * Fired during {@link Container#create}. See + * {@link Container~afterCreateListener} for how to listen for this event. + * + * @event Container#afterCreate + * @see Container~afterCreateListener + * @see Container#create + */ +/** + * Callback signature for the {@link Container#event:afterCreate} event. + * + * @example + * function onAfterCreate (mapperName, props, opts, result) { + * // do something + * } + * store.on('afterCreate', onAfterCreate); + * + * @callback Container~afterCreateListener + * @param {string} name The `name` argument received by {@link Mapper#afterCreate}. + * @param {object} props The `props` argument received by {@link Mapper#afterCreate}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterCreate}. + * @param {object} result The `result` argument received by {@link Mapper#afterCreate}. + * @see Container#event:afterCreate + * @see Container#create + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#create}. + * + * @example + * // Create and save a new blog post + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.create('post', { + * title: 'Modeling your data', + * status: 'draft' + * }).then((post) => { + * console.log(post); // { id: 1234, status: 'draft', ... } + * }); + * + * @fires Container#beforeCreate + * @fires Container#afterCreate + * @method Container#create + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} props See {@link Mapper#create}. + * @param {object} [opts] See {@link Mapper#create}. + * @returns {Promise} See {@link Mapper#create}. + * @see Mapper#create + * @since 3.0.0 + */ +'create', + +/** + * Fired during {@link Container#createMany}. See + * {@link Container~beforeCreateManyListener} for how to listen for this event. + * + * @event Container#beforeCreateMany + * @see Container~beforeCreateManyListener + * @see Container#createMany + */ +/** + * Callback signature for the {@link Container#event:beforeCreateMany} event. + * + * @example + * function onBeforeCreateMany (mapperName, records, opts) { + * // do something + * } + * store.on('beforeCreateMany', onBeforeCreateMany); + * + * @callback Container~beforeCreateManyListener + * @param {string} name The `name` argument received by {@link Mapper#beforeCreateMany}. + * @param {object} records The `records` argument received by {@link Mapper#beforeCreateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreateMany}. + * @see Container#event:beforeCreateMany + * @see Container#createMany + * @since 3.0.0 + */ +/** + * Fired during {@link Container#createMany}. See + * {@link Container~afterCreateManyListener} for how to listen for this event. + * + * @event Container#afterCreateMany + * @see Container~afterCreateManyListener + * @see Container#createMany + */ +/** + * Callback signature for the {@link Container#event:afterCreateMany} event. + * + * @example + * function onAfterCreateMany (mapperName, records, opts, result) { + * // do something + * } + * store.on('afterCreateMany', onAfterCreateMany); + * + * @callback Container~afterCreateManyListener + * @param {string} name The `name` argument received by {@link Mapper#afterCreateMany}. + * @param {object} records The `records` argument received by {@link Mapper#afterCreateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterCreateMany}. + * @param {object} result The `result` argument received by {@link Mapper#afterCreateMany}. + * @see Container#event:afterCreateMany + * @see Container#createMany + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#createMany}. + * + * @example + * // Create and save several new blog posts + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.createMany('post', [{ + * title: 'Modeling your data', + * status: 'draft' + * }, { + * title: 'Reading data', + * status: 'draft' + * }]).then((posts) => { + * console.log(posts[0]); // { id: 1234, status: 'draft', ... } + * console.log(posts[1]); // { id: 1235, status: 'draft', ... } + * }); + * + * @fires Container#beforeCreateMany + * @fires Container#afterCreateMany + * @method Container#createMany + * @param {string} name Name of the {@link Mapper} to target. + * @param {Record[]} records See {@link Mapper#createMany}. + * @param {object} [opts] See {@link Mapper#createMany}. + * @returns {Promise} See {@link Mapper#createMany}. + * @see Mapper#createMany + * @since 3.0.0 + */ +'createMany', + +/** + * Wrapper for {@link Mapper#createRecord}. + * + * __Note:__ This method does __not__ interact with any adapter, and does + * __not__ save any data. It only creates new objects in memory. + * + * @example + * // Create empty unsaved record instance + * import { Container } from 'js-data'; + * const store = new Container(); + * store.defineMapper('post'); + * const post = PostMapper.createRecord(); + * + * @method Container#createRecord + * @param {string} name Name of the {@link Mapper} to target. + * @param {Object|Object[]} props See {@link Mapper#createRecord}. + * @param {object} [opts] See {@link Mapper#createRecord}. + * @returns {Promise} See {@link Mapper#createRecord}. + * @see Mapper#createRecord + * @since 3.0.0 + */ +'createRecord', + +/** + * Fired during {@link Container#destroy}. See + * {@link Container~beforeDestroyListener} for how to listen for this event. + * + * @event Container#beforeDestroy + * @see Container~beforeDestroyListener + * @see Container#destroy + */ +/** + * Callback signature for the {@link Container#event:beforeDestroy} event. + * + * @example + * function onBeforeDestroy (mapperName, id, opts) { + * // do something + * } + * store.on('beforeDestroy', onBeforeDestroy); + * + * @callback Container~beforeDestroyListener + * @param {string} name The `name` argument received by {@link Mapper#beforeDestroy}. + * @param {string|number} id The `id` argument received by {@link Mapper#beforeDestroy}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroy}. + * @see Container#event:beforeDestroy + * @see Container#destroy + * @since 3.0.0 + */ +/** + * Fired during {@link Container#destroy}. See + * {@link Container~afterDestroyListener} for how to listen for this event. + * + * @event Container#afterDestroy + * @see Container~afterDestroyListener + * @see Container#destroy + */ +/** + * Callback signature for the {@link Container#event:afterDestroy} event. + * + * @example + * function onAfterDestroy (mapperName, id, opts, result) { + * // do something + * } + * store.on('afterDestroy', onAfterDestroy); + * + * @callback Container~afterDestroyListener + * @param {string} name The `name` argument received by {@link Mapper#afterDestroy}. + * @param {string|number} id The `id` argument received by {@link Mapper#afterDestroy}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterDestroy}. + * @param {object} result The `result` argument received by {@link Mapper#afterDestroy}. + * @see Container#event:afterDestroy + * @see Container#destroy + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#destroy}. + * + * @example + * // Destroy a specific blog post + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.destroy('post', 1234).then(() => { + * // Blog post #1234 has been destroyed + * }); + * + * @fires Container#beforeDestroy + * @fires Container#afterDestroy + * @method Container#destroy + * @param {string} name Name of the {@link Mapper} to target. + * @param {(string|number)} id See {@link Mapper#destroy}. + * @param {object} [opts] See {@link Mapper#destroy}. + * @returns {Promise} See {@link Mapper#destroy}. + * @see Mapper#destroy + * @since 3.0.0 + */ +'destroy', + +/** + * Fired during {@link Container#destroyAll}. See + * {@link Container~beforeDestroyAllListener} for how to listen for this event. + * + * @event Container#beforeDestroyAll + * @see Container~beforeDestroyAllListener + * @see Container#destroyAll + */ +/** + * Callback signature for the {@link Container#event:beforeDestroyAll} event. + * + * @example + * function onBeforeDestroyAll (mapperName, query, opts) { + * // do something + * } + * store.on('beforeDestroyAll', onBeforeDestroyAll); + * + * @callback Container~beforeDestroyAllListener + * @param {string} name The `name` argument received by {@link Mapper#beforeDestroyAll}. + * @param {object} query The `query` argument received by {@link Mapper#beforeDestroyAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroyAll}. + * @see Container#event:beforeDestroyAll + * @see Container#destroyAll + * @since 3.0.0 + */ +/** + * Fired during {@link Container#destroyAll}. See + * {@link Container~afterDestroyAllListener} for how to listen for this event. + * + * @event Container#afterDestroyAll + * @see Container~afterDestroyAllListener + * @see Container#destroyAll + */ +/** + * Callback signature for the {@link Container#event:afterDestroyAll} event. + * + * @example + * function onAfterDestroyAll (mapperName, query, opts, result) { + * // do something + * } + * store.on('afterDestroyAll', onAfterDestroyAll); + * + * @callback Container~afterDestroyAllListener + * @param {string} name The `name` argument received by {@link Mapper#afterDestroyAll}. + * @param {object} query The `query` argument received by {@link Mapper#afterDestroyAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterDestroyAll}. + * @param {object} result The `result` argument received by {@link Mapper#afterDestroyAll}. + * @see Container#event:afterDestroyAll + * @see Container#destroyAll + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#destroyAll}. + * + * @example + * // Destroy all "draft" blog posts + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.destroyAll('post', { status: 'draft' }).then(() => { + * // All "draft" blog posts have been destroyed + * }); + * + * @fires Container#beforeDestroyAll + * @fires Container#afterDestroyAll + * @method Container#destroyAll + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} [query] See {@link Mapper#destroyAll}. + * @param {object} [opts] See {@link Mapper#destroyAll}. + * @returns {Promise} See {@link Mapper#destroyAll}. + * @see Mapper#destroyAll + * @since 3.0.0 + */ +'destroyAll', + +/** + * Fired during {@link Container#find}. See + * {@link Container~beforeFindListener} for how to listen for this event. + * + * @event Container#beforeFind + * @see Container~beforeFindListener + * @see Container#find + */ +/** + * Callback signature for the {@link Container#event:beforeFind} event. + * + * @example + * function onBeforeFind (mapperName, id, opts) { + * // do something + * } + * store.on('beforeFind', onBeforeFind); + * + * @callback Container~beforeFindListener + * @param {string} name The `name` argument received by {@link Mapper#beforeFind}. + * @param {string|number} id The `id` argument received by {@link Mapper#beforeFind}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeFind}. + * @see Container#event:beforeFind + * @see Container#find + * @since 3.0.0 + */ +/** + * Fired during {@link Container#find}. See + * {@link Container~afterFindListener} for how to listen for this event. + * + * @event Container#afterFind + * @see Container~afterFindListener + * @see Container#find + */ +/** + * Callback signature for the {@link Container#event:afterFind} event. + * + * @example + * function onAfterFind (mapperName, id, opts, result) { + * // do something + * } + * store.on('afterFind', onAfterFind); + * + * @callback Container~afterFindListener + * @param {string} name The `name` argument received by {@link Mapper#afterFind}. + * @param {string|number} id The `id` argument received by {@link Mapper#afterFind}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterFind}. + * @param {object} result The `result` argument received by {@link Mapper#afterFind}. + * @see Container#event:afterFind + * @see Container#find + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#find}. + * + * @example + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.find('post', 1).then((post) => { + * console.log(post) // { id: 1, ...} + * }); + * + * @fires Container#beforeFind + * @fires Container#afterFind + * @method Container#find + * @param {string} name Name of the {@link Mapper} to target. + * @param {(string|number)} id See {@link Mapper#find}. + * @param {object} [opts] See {@link Mapper#find}. + * @returns {Promise} See {@link Mapper#find}. + * @see Mapper#find + * @since 3.0.0 + */ +'find', + +/** + * Fired during {@link Container#findAll}. See + * {@link Container~beforeFindAllListener} for how to listen for this event. + * + * @event Container#beforeFindAll + * @see Container~beforeFindAllListener + * @see Container#findAll + */ +/** + * Callback signature for the {@link Container#event:beforeFindAll} event. + * + * @example + * function onBeforeFindAll (mapperName, query, opts) { + * // do something + * } + * store.on('beforeFindAll', onBeforeFindAll); + * + * @callback Container~beforeFindAllListener + * @param {string} name The `name` argument received by {@link Mapper#beforeFindAll}. + * @param {object} query The `query` argument received by {@link Mapper#beforeFindAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeFindAll}. + * @see Container#event:beforeFindAll + * @see Container#findAll + * @since 3.0.0 + */ +/** + * Fired during {@link Container#findAll}. See + * {@link Container~afterFindAllListener} for how to listen for this event. + * + * @event Container#afterFindAll + * @see Container~afterFindAllListener + * @see Container#findAll + */ +/** + * Callback signature for the {@link Container#event:afterFindAll} event. + * + * @example + * function onAfterFindAll (mapperName, query, opts, result) { + * // do something + * } + * store.on('afterFindAll', onAfterFindAll); + * + * @callback Container~afterFindAllListener + * @param {string} name The `name` argument received by {@link Mapper#afterFindAll}. + * @param {object} query The `query` argument received by {@link Mapper#afterFindAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterFindAll}. + * @param {object} result The `result` argument received by {@link Mapper#afterFindAll}. + * @see Container#event:afterFindAll + * @see Container#findAll + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#createRecord}. + * + * @example + * // Find all "published" blog posts + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.findAll('post', { status: 'published' }).then((posts) => { + * console.log(posts); // [{ id: 1, ...}, ...] + * }); + * + * @fires Container#beforeFindAll + * @fires Container#afterFindAll + * @method Container#findAll + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} [query] See {@link Mapper#findAll}. + * @param {object} [opts] See {@link Mapper#findAll}. + * @returns {Promise} See {@link Mapper#findAll}. + * @see Mapper#findAll + * @since 3.0.0 + */ +'findAll', + +/** + * Wrapper for {@link Mapper#getSchema}. + * + * @method Container#getSchema + * @param {string} name Name of the {@link Mapper} to target. + * @returns {Schema} See {@link Mapper#getSchema}. + * @see Mapper#getSchema + * @since 3.0.0 + */ +'getSchema', + +/** + * Wrapper for {@link Mapper#is}. + * + * @example + * import { Container } from 'js-data'; + * const store = new Container(); + * store.defineMapper('post'); + * const post = store.createRecord(); + * + * console.log(store.is('post', post)); // true + * // Equivalent to what's above + * console.log(post instanceof store.getMapper('post').recordClass); // true + * + * @method Container#is + * @param {string} name Name of the {@link Mapper} to target. + * @param {Object|Record} record See {@link Mapper#is}. + * @returns {boolean} See {@link Mapper#is}. + * @see Mapper#is + * @since 3.0.0 + */ +'is', + +/** + * Wrapper for {@link Mapper#sum}. + * + * @example + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('purchase_order'); + * + * store.sum('purchase_order', 'amount', { status: 'paid' }).then((amountPaid) => { + * console.log(amountPaid); // e.g. 451125.34 + * }); + * + * @method Container#sum + * @param {string} name Name of the {@link Mapper} to target. + * @param {string} field See {@link Mapper#sum}. + * @param {object} [query] See {@link Mapper#sum}. + * @param {object} [opts] See {@link Mapper#sum}. + * @returns {Promise} See {@link Mapper#sum}. + * @see Mapper#sum + * @since 3.0.0 + */ +'sum', + +/** + * Wrapper for {@link Mapper#toJSON}. + * + * @example + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('person', { + * schema: { + * properties: { + * name: { type: 'string' }, + * id: { type: 'string' } + * } + * } + * }); + * const person = store.createRecord('person', { id: 1, name: 'John', foo: 'bar' }); + * // "foo" is stripped by toJSON() + * console.log(store.toJSON('person', person)); // {"id":1,"name":"John"} + * + * store.defineMapper('personRelaxed', { + * schema: { + * properties: { + * name: { type: 'string' }, + * id: { type: 'string' } + * }, + * additionalProperties: true + * } + * }); + * const person2 = store.createRecord('personRelaxed', { id: 1, name: 'John', foo: 'bar' }); + * // "foo" is not stripped by toJSON + * console.log(store.toJSON('personRelaxed', person2)); // {"id":1,"name":"John","foo":"bar"} + * + * @method Container#toJSON + * @param {string} name Name of the {@link Mapper} to target. + * @param {Record|Record[]} records See {@link Mapper#toJSON}. + * @param {object} [opts] See {@link Mapper#toJSON}. + * @returns {Object|Object[]} See {@link Mapper#toJSON}. + * @see Mapper#toJSON + * @since 3.0.0 + */ +'toJSON', + +/** + * Fired during {@link Container#update}. See + * {@link Container~beforeUpdateListener} for how to listen for this event. + * + * @event Container#beforeUpdate + * @see Container~beforeUpdateListener + * @see Container#update + */ +/** + * Callback signature for the {@link Container#event:beforeUpdate} event. + * + * @example + * function onBeforeUpdate (mapperName, id, props, opts) { + * // do something + * } + * store.on('beforeUpdate', onBeforeUpdate); + * + * @callback Container~beforeUpdateListener + * @param {string} name The `name` argument received by {@link Mapper#beforeUpdate}. + * @param {string|number} id The `id` argument received by {@link Mapper#beforeUpdate}. + * @param {object} props The `props` argument received by {@link Mapper#beforeUpdate}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdate}. + * @see Container#event:beforeUpdate + * @see Container#update + * @since 3.0.0 + */ +/** + * Fired during {@link Container#update}. See + * {@link Container~afterUpdateListener} for how to listen for this event. + * + * @event Container#afterUpdate + * @see Container~afterUpdateListener + * @see Container#update + */ +/** + * Callback signature for the {@link Container#event:afterUpdate} event. + * + * @example + * function onAfterUpdate (mapperName, id, props, opts, result) { + * // do something + * } + * store.on('afterUpdate', onAfterUpdate); + * + * @callback Container~afterUpdateListener + * @param {string} name The `name` argument received by {@link Mapper#afterUpdate}. + * @param {string|number} id The `id` argument received by {@link Mapper#afterUpdate}. + * @param {object} props The `props` argument received by {@link Mapper#afterUpdate}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdate}. + * @param {object} result The `result` argument received by {@link Mapper#afterUpdate}. + * @see Container#event:afterUpdate + * @see Container#update + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#update}. + * + * @example + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.update('post', 1234, { + * status: 'published', + * published_at: new Date() + * }).then((post) => { + * console.log(post); // { id: 1234, status: 'published', ... } + * }); + * + * @fires Container#beforeUpdate + * @fires Container#afterUpdate + * @method Container#update + * @param {string} name Name of the {@link Mapper} to target. + * @param {(string|number)} id See {@link Mapper#update}. + * @param {object} record See {@link Mapper#update}. + * @param {object} [opts] See {@link Mapper#update}. + * @returns {Promise} See {@link Mapper#update}. + * @see Mapper#update + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/saving-data","Saving data"] + */ +'update', + +/** + * Fired during {@link Container#updateAll}. See + * {@link Container~beforeUpdateAllListener} for how to listen for this event. + * + * @event Container#beforeUpdateAll + * @see Container~beforeUpdateAllListener + * @see Container#updateAll + */ +/** + * Callback signature for the {@link Container#event:beforeUpdateAll} event. + * + * @example + * function onBeforeUpdateAll (mapperName, props, query, opts) { + * // do something + * } + * store.on('beforeUpdateAll', onBeforeUpdateAll); + * + * @callback Container~beforeUpdateAllListener + * @param {string} name The `name` argument received by {@link Mapper#beforeUpdateAll}. + * @param {object} props The `props` argument received by {@link Mapper#beforeUpdateAll}. + * @param {object} query The `query` argument received by {@link Mapper#beforeUpdateAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateAll}. + * @see Container#event:beforeUpdateAll + * @see Container#updateAll + * @since 3.0.0 + */ +/** + * Fired during {@link Container#updateAll}. See + * {@link Container~afterUpdateAllListener} for how to listen for this event. + * + * @event Container#afterUpdateAll + * @see Container~afterUpdateAllListener + * @see Container#updateAll + */ +/** + * Callback signature for the {@link Container#event:afterUpdateAll} event. + * + * @example + * function onAfterUpdateAll (mapperName, props, query, opts, result) { + * // do something + * } + * store.on('afterUpdateAll', onAfterUpdateAll); + * + * @callback Container~afterUpdateAllListener + * @param {string} name The `name` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} props The `props` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} query The `query` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} result The `result` argument received by {@link Mapper#afterUpdateAll}. + * @see Container#event:afterUpdateAll + * @see Container#updateAll + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#updateAll}. + * + * @example + * // Turn all of John's blog posts into drafts. + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * const update = { status: draft: published_at: null }; + * const query = { userId: 1234 }; + * store.updateAll('post', update, query).then((posts) => { + * console.log(posts); // [...] + * }); + * + * @fires Container#beforeUpdateAll + * @fires Container#afterUpdateAll + * @method Container#updateAll + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} update See {@link Mapper#updateAll}. + * @param {object} [query] See {@link Mapper#updateAll}. + * @param {object} [opts] See {@link Mapper#updateAll}. + * @returns {Promise} See {@link Mapper#updateAll}. + * @see Mapper#updateAll + * @since 3.0.0 + */ +'updateAll', + +/** + * Fired during {@link Container#updateMany}. See + * {@link Container~beforeUpdateManyListener} for how to listen for this event. + * + * @event Container#beforeUpdateMany + * @see Container~beforeUpdateManyListener + * @see Container#updateMany + */ +/** + * Callback signature for the {@link Container#event:beforeUpdateMany} event. + * + * @example + * function onBeforeUpdateMany (mapperName, records, opts) { + * // do something + * } + * store.on('beforeUpdateMany', onBeforeUpdateMany); + * + * @callback Container~beforeUpdateManyListener + * @param {string} name The `name` argument received by {@link Mapper#beforeUpdateMany}. + * @param {object} records The `records` argument received by {@link Mapper#beforeUpdateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateMany}. + * @see Container#event:beforeUpdateMany + * @see Container#updateMany + * @since 3.0.0 + */ +/** + * Fired during {@link Container#updateMany}. See + * {@link Container~afterUpdateManyListener} for how to listen for this event. + * + * @event Container#afterUpdateMany + * @see Container~afterUpdateManyListener + * @see Container#updateMany + */ +/** + * Callback signature for the {@link Container#event:afterUpdateMany} event. + * + * @example + * function onAfterUpdateMany (mapperName, records, opts, result) { + * // do something + * } + * store.on('afterUpdateMany', onAfterUpdateMany); + * + * @callback Container~afterUpdateManyListener + * @param {string} name The `name` argument received by {@link Mapper#afterUpdateMany}. + * @param {object} records The `records` argument received by {@link Mapper#afterUpdateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateMany}. + * @param {object} result The `result` argument received by {@link Mapper#afterUpdateMany}. + * @see Container#event:afterUpdateMany + * @see Container#updateMany + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#updateMany}. + * + * @example + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.updateMany('post', [ + * { id: 1234, status: 'draft' }, + * { id: 2468, status: 'published', published_at: new Date() } + * ]).then((posts) => { + * console.log(posts); // [...] + * }); + * + * @fires Container#beforeUpdateMany + * @fires Container#afterUpdateMany + * @method Container#updateMany + * @param {string} name Name of the {@link Mapper} to target. + * @param {(Object[]|Record[])} records See {@link Mapper#updateMany}. + * @param {object} [opts] See {@link Mapper#updateMany}. + * @returns {Promise} See {@link Mapper#updateMany}. + * @see Mapper#updateMany + * @since 3.0.0 + */ +'updateMany', + +/** + * Wrapper for {@link Mapper#validate}. + * + * @example + * import { Container } from 'js-data'; + * const store = new Container(); + * store.defineMapper('post', { + * schema: { + * properties: { + * name: { type: 'string' }, + * id: { type: 'string' } + * } + * } + * }); + * let errors = store.validate('post', { name: 'John' }); + * console.log(errors); // undefined + * errors = store.validate('post', { name: 123 }); + * console.log(errors); // [{ expected: 'one of (string)', actual: 'number', path: 'name' }] + * + * @method Container#validate + * @param {string} name Name of the {@link Mapper} to target. + * @param {(Object[]|Record[])} records See {@link Mapper#validate}. + * @param {object} [opts] See {@link Mapper#validate}. + * @returns {Promise} See {@link Mapper#validate}. + * @see Mapper#validate + * @since 3.0.0 + */ +'validate']; + +/** + * The `Container` class is a place to define and store {@link Mapper} instances. + * + * `Container` makes it easy to manage your Mappers. Without a container, you + * need to manage Mappers yourself, including resolving circular dependencies + * among relations. All Mappers in a container share the same adapters, so you + * don't have to register adapters for every single Mapper. + * + * @example Container#constructor + * // import { Container } from 'js-data'; + * const JSData = require('js-data'); + * const {Container} = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * + * @class Container + * @extends Component + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.debug=false] See {@link Component#debug}. + * @param {Constructor} [opts.mapperClass] See {@link Container#mapperClass}. + * @param {object} [opts.mapperDefaults] See {@link Container#mapperDefaults}. + * @since 3.0.0 + */ +function Container(opts) { + utils.classCallCheck(this, Container); + Component$1.call(this); + opts || (opts = {}); + + Object.defineProperties(this, { + /** + * The adapters registered with this Container, which are also shared by all + * Mappers in this Container. + * + * @name Container#_adapters + * @see Container#registerAdapter + * @since 3.0.0 + * @type {Object} + */ + _adapters: { + value: {} + }, + + /** + * The the mappers in this container + * + * @name Container#_mappers + * @see Mapper + * @since 3.0.0 + * @type {Object} + */ + _mappers: { + value: {} + }, + + /** + * Constructor function to use in {@link Container#defineMapper} to create new + * {@link Mapper} instances. {@link Container#mapperClass} should extend + * {@link Mapper}. By default {@link Mapper} is used to instantiate Mappers. + * + * @example Container#mapperClass + * // import { Container, Mapper } from 'js-data'; + * const JSData = require('js-data'); + * const { Container, Mapper } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * class MyMapperClass extends Mapper { + * foo () { return 'bar' } + * } + * const store = new Container({ + * mapperClass: MyMapperClass + * }); + * store.defineMapper('user'); + * console.log(store.getMapper('user').foo()); + * + * @name Container#mapperClass + * @see Mapper + * @since 3.0.0 + * @type {Constructor} + */ + mapperClass: { + value: undefined, + writable: true + } + }); + + // Apply options provided by the user + utils.fillIn(this, opts); + + /** + * Defaults options to pass to {@link Container#mapperClass} when creating a + * new {@link Mapper}. + * + * @example Container#mapperDefaults + * // import { Container } from 'js-data'; + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container({ + * mapperDefaults: { + * idAttribute: '_id' + * } + * }); + * store.defineMapper('user'); + * console.log(store.getMapper('user').idAttribute); + * + * @default {} + * @name Container#mapperDefaults + * @since 3.0.0 + * @type {Object} + */ + this.mapperDefaults = this.mapperDefaults || {}; + + // Use the Mapper class if the user didn't provide a mapperClass + this.mapperClass || (this.mapperClass = Mapper$1); +} + +var props = { + constructor: Container, + + /** + * Register a new event listener on this Container. + * + * Proxy for {@link Component#on}. If an event was emitted by a {@link Mapper} + * in the Container, then the name of the {@link Mapper} will be prepended to + * the arugments passed to the listener. + * + * @example Container#on + * // import { Container } from 'js-data'; + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * store.on('foo', function (...args) { console.log(args.join(':')) }); + * store.defineMapper('user'); + * store.emit('foo', 'arg1', 'arg2'); + * store.getMapper('user').emit('foo', 'arg1', 'arg2'); + * + * @method Container#on + * @param {string} event Name of event to subsribe to. + * @param {Function} listener Listener function to handle the event. + * @param {*} [ctx] Optional content in which to invoke the listener. + * @since 3.0.0 + */ + + /** + * Used to bind to events emitted by mappers in this container. + * + * @method Container#_onMapperEvent + * @param {string} name Name of the mapper that emitted the event. + * @param {...*} [args] Args See {@link Mapper#emit}. + * @private + * @since 3.0.0 + */ + _onMapperEvent: function _onMapperEvent(name) { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + var type = args.shift(); + this.emit.apply(this, [type, name].concat(args)); + }, + + + /** + * Return a container scoped to a particular mapper. + * + * @example Container#as + * // import { Container } from 'js-data'; + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * const UserMapper = store.defineMapper('user'); + * const UserStore = store.as('user'); + * + * const user1 = store.createRecord('user', { name: 'John' }); + * const user2 = UserStore.createRecord({ name: 'John' }); + * const user3 = UserMapper.createRecord({ name: 'John' }); + * console.log(user1 === user2); + * console.log(user2 === user3); + * console.log(user1 === user3); + * + * @method Container#as + * @param {string} name Name of the {@link Mapper}. + * @returns {Object} A container scoped to a particular mapper. + * @since 3.0.0 + */ + as: function as(name) { + var props = {}; + var original = this; + proxiedMapperMethods.forEach(function (method) { + props[method] = { + writable: true, + value: function value() { + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + return original[method].apply(original, [name].concat(args)); + } + }; + }); + props.getMapper = { + writable: true, + value: function value() { + return original.getMapper(name); + } + }; + return Object.create(this, props); + }, + + + /** + * Create a new mapper and register it in this container. + * + * @example Container#defineMapper + * // import { Container } from 'js-data'; + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container({ + * mapperDefaults: { foo: 'bar' } + * }); + * // Container#defineMapper returns a direct reference to the newly created + * // Mapper. + * const UserMapper = store.defineMapper('user'); + * console.log(UserMapper === store.getMapper('user')); + * console.log(UserMapper === store.as('user').getMapper()); + * console.log(UserMapper.foo); + * + * @method Container#defineMapper + * @param {string} name Name under which to register the new {@link Mapper}. + * {@link Mapper#name} will be set to this value. + * @param {object} [opts] Configuration options. Passed to + * {@link Container#mapperClass} when creating the new {@link Mapper}. + * @returns {Mapper} The newly created instance of {@link Mapper}. + * @see Container#as + * @since 3.0.0 + */ + defineMapper: function defineMapper(name, opts) { + var _this = this; + + // For backwards compatibility with defineResource + if (utils.isObject(name)) { + opts = name; + name = opts.name; + } + if (!utils.isString(name)) { + throw utils.err(DOMAIN$5 + '#defineMapper', 'name')(400, 'string', name); + } + + // Default values for arguments + opts || (opts = {}); + // Set Mapper#name + opts.name = name; + opts.relations || (opts.relations = {}); + + // Check if the user is overriding the datastore's default mapperClass + var mapperClass = opts.mapperClass || this.mapperClass; + delete opts.mapperClass; + + // Apply the datastore's defaults to the options going into the mapper + utils.fillIn(opts, this.mapperDefaults); + + // Instantiate a mapper + var mapper = this._mappers[name] = new mapperClass(opts); // eslint-disable-line + mapper.relations || (mapper.relations = {}); + // Make sure the mapper's name is set + mapper.name = name; + // All mappers in this datastore will share adapters + mapper._adapters = this.getAdapters(); + + mapper.datastore = this; + + mapper.on('all', function () { + for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + return _this._onMapperEvent.apply(_this, [name].concat(args)); + }); + mapper.defineRelations(); + + return mapper; + }, + defineResource: function defineResource(name, opts) { + console.warn('DEPRECATED: defineResource is deprecated, use defineMapper instead'); + return this.defineMapper(name, opts); + }, + + + /** + * Return the registered adapter with the given name or the default adapter if + * no name is provided. + * + * @method Container#getAdapter + * @param {string} [name] The name of the adapter to retrieve. + * @returns {Adapter} The adapter. + * @since 3.0.0 + */ + getAdapter: function getAdapter(name) { + var adapter = this.getAdapterName(name); + if (!adapter) { + throw utils.err(DOMAIN$5 + '#getAdapter', 'name')(400, 'string', name); + } + return this.getAdapters()[adapter]; + }, + + + /** + * Return the name of a registered adapter based on the given name or options, + * or the name of the default adapter if no name provided. + * + * @method Container#getAdapterName + * @param {(Object|string)} [opts] The name of an adapter or options, if any. + * @returns {string} The name of the adapter. + * @since 3.0.0 + */ + getAdapterName: function getAdapterName(opts) { + opts || (opts = {}); + if (utils.isString(opts)) { + opts = { adapter: opts }; + } + return opts.adapter || this.mapperDefaults.defaultAdapter; + }, + + + /** + * Return the registered adapters of this container. + * + * @method Container#getAdapters + * @returns {Adapter} + * @since 3.0.0 + */ + getAdapters: function getAdapters() { + return this._adapters; + }, + + + /** + * Return the mapper registered under the specified name. + * + * @example Container#getMapper + * // import { Container } from 'js-data'; + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * // Container#defineMapper returns a direct reference to the newly created + * // Mapper. + * const UserMapper = store.defineMapper('user'); + * console.log(UserMapper === store.getMapper('user')); + * console.log(UserMapper === store.as('user').getMapper()); + * store.getMapper('profile'); // throws Error, there is no mapper with name "profile" + * + * @method Container#getMapper + * @param {string} name {@link Mapper#name}. + * @returns {Mapper} + * @since 3.0.0 + */ + getMapper: function getMapper(name) { + var mapper = this.getMapperByName(name); + if (!mapper) { + throw utils.err(DOMAIN$5 + '#getMapper', name)(404, 'mapper'); + } + return mapper; + }, + + + /** + * Return the mapper registered under the specified name. + * Doesn't throw error if mapper doesn't exist. + * + * @example Container#getMapperByName + * // import { Container } from 'js-data'; + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * // Container#defineMapper returns a direct reference to the newly created + * // Mapper. + * const UserMapper = store.defineMapper('user'); + * console.log(UserMapper === store.getMapper('user')); + * console.log(UserMapper === store.as('user').getMapper()); + * console.log(store.getMapper('profile')); // Does NOT throw an error + * + * @method Container#getMapperByName + * @param {string} name {@link Mapper#name}. + * @returns {Mapper} + * @since 3.0.0 + */ + getMapperByName: function getMapperByName(name) { + return this._mappers[name]; + }, + + + /** + * Register an adapter on this container under the given name. Adapters + * registered on a container are shared by all mappers in the container. + * + * @example + * import { Container } from 'js-data'; + * import { RethinkDBAdapter } from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * + * @method Container#registerAdapter + * @param {string} name The name of the adapter to register. + * @param {Adapter} adapter The adapter to register. + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.default=false] Whether to make the adapter the + * default adapter for all Mappers in this container. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/connecting-to-a-data-source","Connecting to a data source"] + */ + registerAdapter: function registerAdapter(name, adapter, opts) { + opts || (opts = {}); + this.getAdapters()[name] = adapter; + // Optionally make it the default adapter for the target. + if (opts === true || opts.default) { + this.mapperDefaults.defaultAdapter = name; + utils.forOwn(this._mappers, function (mapper) { + mapper.defaultAdapter = name; + }); + } + } +}; + +proxiedMapperMethods.forEach(function (method) { + props[method] = function (name) { + var _getMapper; + + for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + + return (_getMapper = this.getMapper(name))[method].apply(_getMapper, args); + }; +}); + +Component$1.extend(props); + +/** + * Create a subclass of this Container: + * @example Container.extend + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomContainerClass extends Container { + * foo () { return 'bar' } + * static beep () { return 'boop' } + * } + * const customContainer = new CustomContainerClass(); + * console.log(customContainer.foo()); + * console.log(CustomContainerClass.beep()); + * + * // Extend the class using alternate method. + * const OtherContainerClass = Container.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherContainer = new OtherContainerClass(); + * console.log(otherContainer.foo()); + * console.log(OtherContainerClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherContainerClass () { + * Container.call(this); + * this.created_at = new Date().getTime(); + * } + * Container.extend({ + * constructor: AnotherContainerClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }) + * const anotherContainer = new AnotherContainerClass(); + * console.log(anotherContainer.created_at); + * console.log(anotherContainer.foo()); + * console.log(AnotherContainerClass.beep()); + * + * @method Container.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this Container class. + * @since 3.0.0 + */ + +var DOMAIN$8 = 'SimpleStore'; +var proxiedCollectionMethods = [ +/** + * Wrapper for {@link Collection#add}. + * + * @example SimpleStore#add + * const JSData = require('js-data'); + * const { SimpleStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new SimpleStore(); + * store.defineMapper('book'); + * + * // Add one book to the in-memory store: + * store.add('book', { id: 1, title: 'Respect your Data' }); + * // Add multiple books to the in-memory store: + * store.add('book', [ + * { id: 2, title: 'Easy data recipes' }, + * { id: 3, title: 'Active Record 101' } + * ]); + * + * @fires SimpleStore#add + * @method SimpleStore#add + * @param {(string|number)} name Name of the {@link Mapper} to target. + * @param {(Object|Object[]|Record|Record[])} data See {@link Collection#add}. + * @param {object} [opts] Configuration options. See {@link Collection#add}. + * @returns {(Object|Object[]|Record|Record[])} See {@link Collection#add}. + * @see Collection#add + * @see Collection#add + * @since 3.0.0 + */ +'add', + +/** + * Wrapper for {@link Collection#between}. + * + * @example + * // Get all users ages 18 to 30 + * const users = store.between('user', 18, 30, { index: 'age' }); + * + * @example + * // Same as above + * const users = store.between('user', [18], [30], { index: 'age' }); + * + * @method SimpleStore#between + * @param {(string|number)} name Name of the {@link Mapper} to target. + * @param {array} leftKeys See {@link Collection#between}. + * @param {array} rightKeys See {@link Collection#between}. + * @param {object} [opts] Configuration options. See {@link Collection#between}. + * @returns {Object[]|Record[]} See {@link Collection#between}. + * @see Collection#between + * @see Collection#between + * @since 3.0.0 + */ +'between', + +/** + * Wrapper for {@link Collection#createIndex}. + * + * @example + * // Index users by age + * store.createIndex('user', 'age'); + * + * @example + * // Index users by status and role + * store.createIndex('user', 'statusAndRole', ['status', 'role']); + * + * @method SimpleStore#createIndex + * @param {(string|number)} name Name of the {@link Mapper} to target. + * @param {string} name See {@link Collection#createIndex}. + * @param {string[]} [fieldList] See {@link Collection#createIndex}. + * @see Collection#createIndex + * @see Collection#createIndex + * @since 3.0.0 + */ +'createIndex', + +/** + * Wrapper for {@link Collection#filter}. + * + * @example SimpleStore#filter + * const JSData = require('js-data'); + * const { SimpleStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new SimpleStore(); + * store.defineMapper('post'); + * store.add('post', [ + * { id: 1, status: 'draft', created_at_timestamp: new Date().getTime() } + * ]); + * + * // Get the draft posts created less than three months ago + * let posts = store.filter('post', { + * where: { + * status: { + * '==': 'draft' + * }, + * created_at_timestamp: { + * '>=': (new Date().getTime() - (1000 \* 60 \* 60 \* 24 \* 30 \* 3)) // 3 months ago + * } + * } + * }); + * console.log(posts); + * + * // Use a custom filter function + * posts = store.filter('post', function (post) { return post.id % 2 === 0 }); + * + * @method SimpleStore#filter + * @param {(string|number)} name Name of the {@link Mapper} to target. + * @param {(Object|Function)} [queryOrFn={}] See {@link Collection#filter}. + * @param {object} [thisArg] See {@link Collection#filter}. + * @returns {Array} See {@link Collection#filter}. + * @see Collection#filter + * @see Collection#filter + * @since 3.0.0 + */ +'filter', + +/** + * Wrapper for {@link Collection#get}. + * + * @example SimpleStore#get + * const JSData = require('js-data'); + * const { SimpleStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new SimpleStore(); + * store.defineMapper('post'); + * store.add('post', [ + * { id: 1, status: 'draft', created_at_timestamp: new Date().getTime() } + * ]); + * + * console.log(store.get('post', 1)); // {...} + * console.log(store.get('post', 2)); // undefined + * + * @method SimpleStore#get + * @param {(string|number)} name Name of the {@link Mapper} to target. + * @param {(string|number)} id See {@link Collection#get}. + * @returns {(Object|Record)} See {@link Collection#get}. + * @see Collection#get + * @see Collection#get + * @since 3.0.0 + */ +'get', + +/** + * Wrapper for {@link Collection#getAll}. + * + * @example + * // Get the posts where "status" is "draft" or "inReview" + * const posts = store.getAll('post', 'draft', 'inReview', { index: 'status' }); + * + * @example + * // Same as above + * const posts = store.getAll('post', ['draft'], ['inReview'], { index: 'status' }); + * + * @method SimpleStore#getAll + * @param {(string|number)} name Name of the {@link Mapper} to target. + * @param {...Array} [keyList] See {@link Collection#getAll}. + * @param {object} [opts] See {@link Collection#getAll}. + * @returns {Array} See {@link Collection#getAll}. + * @see Collection#getAll + * @see Collection#getAll + * @since 3.0.0 + */ +'getAll', + +/** + * Wrapper for {@link Collection#prune}. + * + * @method SimpleStore#prune + * @param {object} [opts] See {@link Collection#prune}. + * @returns {Array} See {@link Collection#prune}. + * @see Collection#prune + * @see Collection#prune + * @since 3.0.0 + */ +'prune', + +/** + * Wrapper for {@link Collection#query}. + * + * @example + * // Grab page 2 of users between ages 18 and 30 + * store.query('user') + * .between(18, 30, { index: 'age' }) // between ages 18 and 30 + * .skip(10) // second page + * .limit(10) // page size + * .run(); + * + * @method SimpleStore#query + * @param {(string|number)} name Name of the {@link Mapper} to target. + * @returns {Query} See {@link Collection#query}. + * @see Collection#query + * @see Collection#query + * @since 3.0.0 + */ +'query', + +/** + * Wrapper for {@link Collection#toJSON}. + * + * @example + * store.defineMapper('post', { + * schema: { + * properties: { + * id: { type: 'number' }, + * title: { type: 'string' } + * } + * } + * }); + * store.add('post', [ + * { id: 1, status: 'published', title: 'Respect your Data' }, + * { id: 2, status: 'draft', title: 'Connecting to a data source' } + * ]); + * console.log(store.toJSON('post')); + * const draftsJSON = store.query('post') + * .filter({ status: 'draft' }) + * .mapCall('toJSON') + * .run(); + * + * @method SimpleStore#toJSON + * @param {(string|number)} name Name of the {@link Mapper} to target. + * @param {object} [opts] See {@link Collection#toJSON}. + * @returns {Array} See {@link Collection#toJSON}. + * @see Collection#toJSON + * @see Collection#toJSON + * @since 3.0.0 + */ +'toJSON', + +/** + * Wrapper for {@link Collection#unsaved}. + * + * @method SimpleStore#unsaved + * @returns {Array} See {@link Collection#unsaved}. + * @see Collection#unsaved + * @see Collection#unsaved + * @since 3.0.0 + */ +'unsaved']; +var ownMethodsForScoping = ['addToCache', 'cachedFind', 'cachedFindAll', 'cacheFind', 'cacheFindAll', 'hashQuery']; + +var cachedFn = function cachedFn(name, hashOrId, opts) { + var cached = this._completedQueries[name][hashOrId]; + if (utils.isFunction(cached)) { + return cached(name, hashOrId, opts); + } + return cached; +}; + +var SIMPLESTORE_DEFAULTS = { + /** + * Whether to use the pending query if a `find` request for the specified + * record is currently underway. Can be set to `true`, `false`, or to a + * function that returns `true` or `false`. + * + * @default true + * @name SimpleStore#usePendingFind + * @since 3.0.0 + * @type {boolean|Function} + */ + usePendingFind: true, + + /** + * Whether to use the pending query if a `findAll` request for the given query + * is currently underway. Can be set to `true`, `false`, or to a function that + * returns `true` or `false`. + * + * @default true + * @name SimpleStore#usePendingFindAll + * @since 3.0.0 + * @type {boolean|Function} + */ + usePendingFindAll: true + + /** + * The `SimpleStore` class is an extension of {@link Container}. Not only does + * `SimpleStore` manage mappers, but also collections. `SimpleStore` implements the + * asynchronous {@link Mapper} methods, such as {@link Mapper#find} and + * {@link Mapper#create}. If you use the asynchronous `SimpleStore` methods + * instead of calling them directly on the mappers, then the results of the + * method calls will be inserted into the store's collections. You can think of + * a `SimpleStore` as an [Identity Map](https://en.wikipedia.org/wiki/Identity_map_pattern) + * for the [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping) + * (the Mappers). + * + * ```javascript + * import { SimpleStore } from 'js-data'; + * ``` + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * const store = new SimpleStore(); + * + * // SimpleStore#defineMapper returns a direct reference to the newly created + * // Mapper. + * const UserMapper = store.defineMapper('user'); + * + * // SimpleStore#as returns the store scoped to a particular Mapper. + * const UserStore = store.as('user'); + * + * // Call "find" on "UserMapper" (Stateless ORM) + * UserMapper.find(1).then((user) => { + * // retrieved a "user" record via the http adapter, but that's it + * + * // Call "find" on "store" targeting "user" (Stateful SimpleStore) + * return store.find('user', 1); // same as "UserStore.find(1)" + * }).then((user) => { + * // not only was a "user" record retrieved, but it was added to the + * // store's "user" collection + * const cachedUser = store.getCollection('user').get(1); + * console.log(user === cachedUser); // true + * }); + * + * @class SimpleStore + * @extends Container + * @param {object} [opts] Configuration options. See {@link Container}. + * @param {boolean} [opts.collectionClass={@link Collection}] See {@link SimpleStore#collectionClass}. + * @param {boolean} [opts.debug=false] See {@link Component#debug}. + * @param {boolean|Function} [opts.usePendingFind=true] See {@link SimpleStore#usePendingFind}. + * @param {boolean|Function} [opts.usePendingFindAll=true] See {@link SimpleStore#usePendingFindAll}. + * @returns {SimpleStore} + * @see Container + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#SimpleStore","Components of JSData: SimpleStore"] + * @tutorial ["http://www.js-data.io/v3.0/docs/working-with-the-SimpleStore","Working with the SimpleStore"] + * @tutorial ["http://www.js-data.io/v3.0/docs/jsdata-and-the-browser","Notes on using JSData in the Browser"] + */ +};function SimpleStore(opts) { + utils.classCallCheck(this, SimpleStore); + + opts || (opts = {}); + // Fill in any missing options with the defaults + utils.fillIn(opts, SIMPLESTORE_DEFAULTS); + Container.call(this, opts); + + this.collectionClass = this.collectionClass || Collection$1; + this._collections = {}; + this._pendingQueries = {}; + this._completedQueries = {}; +} + +var props$2 = { + constructor: SimpleStore, + + /** + * Internal method used to handle Mapper responses. + * + * @method SimpleStore#_end + * @private + * @param {string} name Name of the {@link Collection} to which to + * add the data. + * @param {object} result The result from a Mapper. + * @param {object} [opts] Configuration options. + * @returns {(Object|Array)} Result. + */ + _end: function _end(name, result, opts) { + var data = opts.raw ? result.data : result; + if (data && utils.isFunction(this.addToCache)) { + data = this.addToCache(name, data, opts); + if (opts.raw) { + result.data = data; + } else { + result = data; + } + } + return result; + }, + + + /** + * Register a new event listener on this SimpleStore. + * + * Proxy for {@link Container#on}. If an event was emitted by a Mapper or + * Collection in the SimpleStore, then the name of the Mapper or Collection will + * be prepended to the arugments passed to the provided event handler. + * + * @example + * // Listen for all "afterCreate" events in a SimpleStore + * store.on('afterCreate', (mapperName, props, opts, result) => { + * console.log(mapperName); // "post" + * console.log(props.id); // undefined + * console.log(result.id); // 1234 + * }); + * store.create('post', { title: 'Modeling your data' }).then((post) => { + * console.log(post.id); // 1234 + * }); + * + * @example + * // Listen for the "add" event on a collection + * store.on('add', (mapperName, records) => { + * console.log(records); // [...] + * }); + * + * @example + * // Listen for "change" events on a record + * store.on('change', (mapperName, record, changes) => { + * console.log(changes); // { changed: { title: 'Modeling your data' } } + * }); + * post.title = 'Modeling your data'; + * + * @method SimpleStore#on + * @param {string} event Name of event to subsribe to. + * @param {Function} listener Listener function to handle the event. + * @param {*} [ctx] Optional content in which to invoke the listener. + */ + + /** + * Used to bind to events emitted by collections in this store. + * + * @method SimpleStore#_onCollectionEvent + * @private + * @param {string} name Name of the collection that emitted the event. + * @param {...*} [args] Args passed to {@link Collection#emit}. + */ + _onCollectionEvent: function _onCollectionEvent(name) { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + var type = args.shift(); + this.emit.apply(this, [type, name].concat(args)); + }, + + + /** + * This method takes the data received from {@link SimpleStore#find}, + * {@link SimpleStore#findAll}, {@link SimpleStore#update}, etc., and adds the + * data to the store. _You don't need to call this method directly._ + * + * If you're using the http adapter and your response data is in an unexpected + * format, you may need to override this method so the right data gets added + * to the store. + * + * @example + * const store = new SimpleStore({ + * addToCache (mapperName, data, opts) { + * // Let's say for a particular Resource, response data is in a weird format + * if (name === 'comment') { + * // Re-assign the variable to add the correct records into the stores + * data = data.items; + * } + * // Now perform default behavior + * return SimpleStore.prototype.addToCache.call(this, mapperName, data, opts); + * } + * }); + * + * @example + * // Extend using ES2015 class syntax. + * class MyStore extends SimpleStore { + * addToCache (mapperName, data, opts) { + * // Let's say for a particular Resource, response data is in a weird format + * if (name === 'comment') { + * // Re-assign the variable to add the correct records into the stores + * data = data.items; + * } + * // Now perform default behavior + * return super.addToCache(mapperName, data, opts); + * } + * } + * const store = new MyStore(); + * + * @method SimpleStore#addToCache + * @param {string} name Name of the {@link Mapper} to target. + * @param {*} data Data from which data should be selected for add. + * @param {object} [opts] Configuration options. + */ + addToCache: function addToCache(name, data, opts) { + return this.getCollection(name).add(data, opts); + }, + + + /** + * Return the store scoped to a particular mapper/collection pair. + * + * @example SimpleStore.as + * const JSData = require('js-data'); + * const { SimpleStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new SimpleStore(); + * const UserMapper = store.defineMapper('user'); + * const UserStore = store.as('user'); + * + * const user1 = store.createRecord('user', { name: 'John' }); + * const user2 = UserStore.createRecord({ name: 'John' }); + * const user3 = UserMapper.createRecord({ name: 'John' }); + * console.log(user1 === user2); + * console.log(user2 === user3); + * console.log(user1 === user3); + * + * @method SimpleStore#as + * @param {string} name Name of the {@link Mapper}. + * @returns {Object} The store, scoped to a particular Mapper/Collection pair. + * @since 3.0.0 + */ + as: function as(name) { + var props = {}; + var original = this; + var methods = ownMethodsForScoping.concat(proxiedMapperMethods).concat(proxiedCollectionMethods); + + methods.forEach(function (method) { + props[method] = { + writable: true, + value: function value() { + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + return original[method].apply(original, [name].concat(args)); + } + }; + }); + props.getMapper = { + writable: true, + value: function value() { + return original.getMapper(name); + } + }; + props.getCollection = { + writable: true, + value: function value() { + return original.getCollection(name); + } + }; + return Object.create(this, props); + }, + + + /** + * Retrieve a cached `find` result, if any. This method is called during + * {@link SimpleStore#find} to determine if {@link Mapper#find} needs to be + * called. If this method returns `undefined` then {@link Mapper#find} will + * be called. Otherwise {@link SimpleStore#find} will immediately resolve with + * the return value of this method. + * + * When using {@link SimpleStore} in the browser, you can override this method + * to implement your own cache-busting strategy. + * + * @example + * const store = new SimpleStore({ + * cachedFind (mapperName, id, opts) { + * // Let's say for a particular Resource, we always want to pull fresh from the server + * if (mapperName === 'schedule') { + * // Return undefined to trigger a Mapper#find call + * return; + * } + * // Otherwise perform default behavior + * return SimpleStore.prototype.cachedFind.call(this, mapperName, id, opts); + * } + * }); + * + * @example + * // Extend using ES2015 class syntax. + * class MyStore extends SimpleStore { + * cachedFind (mapperName, id, opts) { + * // Let's say for a particular Resource, we always want to pull fresh from the server + * if (mapperName === 'schedule') { + * // Return undefined to trigger a Mapper#find call + * return; + * } + * // Otherwise perform default behavior + * return super.cachedFind(mapperName, id, opts); + * } + * } + * const store = new MyStore(); + * + * @method SimpleStore#cachedFind + * @param {string} name The `name` argument passed to {@link SimpleStore#find}. + * @param {(string|number)} id The `id` argument passed to {@link SimpleStore#find}. + * @param {object} opts The `opts` argument passed to {@link SimpleStore#find}. + * @since 3.0.0 + */ + cachedFind: cachedFn, + + /** + * Retrieve a cached `findAll` result, if any. This method is called during + * {@link SimpleStore#findAll} to determine if {@link Mapper#findAll} needs to be + * called. If this method returns `undefined` then {@link Mapper#findAll} will + * be called. Otherwise {@link SimpleStore#findAll} will immediately resolve with + * the return value of this method. + * + * When using {@link SimpleStore} in the browser, you can override this method + * to implement your own cache-busting strategy. + * + * @example + * const store = new SimpleStore({ + * cachedFindAll (mapperName, hash, opts) { + * // Let's say for a particular Resource, we always want to pull fresh from the server + * if (mapperName === 'schedule') { + * // Return undefined to trigger a Mapper#findAll call + * return undefined; + * } + * // Otherwise perform default behavior + * return SimpleStore.prototype.cachedFindAll.call(this, mapperName, hash, opts); + * } + * }); + * + * @example + * // Extend using ES2015 class syntax. + * class MyStore extends SimpleStore { + * cachedFindAll (mapperName, hash, opts) { + * // Let's say for a particular Resource, we always want to pull fresh from the server + * if (mapperName === 'schedule') { + * // Return undefined to trigger a Mapper#findAll call + * return undefined; + * } + * // Otherwise perform default behavior + * return super.cachedFindAll(mapperName, hash, opts); + * } + * } + * const store = new MyStore(); + * + * @method SimpleStore#cachedFindAll + * @param {string} name The `name` argument passed to {@link SimpleStore#findAll}. + * @param {string} hash The result of calling {@link SimpleStore#hashQuery} on + * the `query` argument passed to {@link SimpleStore#findAll}. + * @param {object} opts The `opts` argument passed to {@link SimpleStore#findAll}. + * @since 3.0.0 + */ + cachedFindAll: cachedFn, + + /** + * Mark a {@link Mapper#find} result as cached by adding an entry to + * {@link SimpleStore#_completedQueries}. By default, once a `find` entry is + * added it means subsequent calls to the same Resource with the same `id` + * argument will immediately resolve with the result of calling + * {@link SimpleStore#get} instead of delegating to {@link Mapper#find}. + * + * As part of implementing your own caching strategy, you may choose to + * override this method. + * + * @example + * const store = new SimpleStore({ + * cacheFind (mapperName, data, id, opts) { + * // Let's say for a particular Resource, we always want to pull fresh from the server + * if (mapperName === 'schedule') { + * // Return without saving an entry to SimpleStore#_completedQueries + * return; + * } + * // Otherwise perform default behavior + * return SimpleStore.prototype.cacheFind.call(this, mapperName, data, id, opts); + * } + * }); + * + * @example + * // Extend using ES2015 class syntax. + * class MyStore extends SimpleStore { + * cacheFind (mapperName, data, id, opts) { + * // Let's say for a particular Resource, we always want to pull fresh from the server + * if (mapperName === 'schedule') { + * // Return without saving an entry to SimpleStore#_completedQueries + * return; + * } + * // Otherwise perform default behavior + * return super.cacheFind(mapperName, data, id, opts); + * } + * } + * const store = new MyStore(); + * + * @method SimpleStore#cacheFind + * @param {string} name The `name` argument passed to {@link SimpleStore#find}. + * @param {*} data The result to cache. + * @param {(string|number)} id The `id` argument passed to {@link SimpleStore#find}. + * @param {object} opts The `opts` argument passed to {@link SimpleStore#find}. + * @since 3.0.0 + */ + cacheFind: function cacheFind(name, data, id, opts) { + var _this = this; + + this._completedQueries[name][id] = function (name, id, opts) { + return _this.get(name, id); + }; + }, + + + /** + * Mark a {@link Mapper#findAll} result as cached by adding an entry to + * {@link SimpleStore#_completedQueries}. By default, once a `findAll` entry is + * added it means subsequent calls to the same Resource with the same `query` + * argument will immediately resolve with the result of calling + * {@link SimpleStore#filter} instead of delegating to {@link Mapper#findAll}. + * + * As part of implementing your own caching strategy, you may choose to + * override this method. + * + * @example + * const store = new SimpleStore({ + * cachedFindAll (mapperName, data, hash, opts) { + * // Let's say for a particular Resource, we always want to pull fresh from the server + * if (mapperName === 'schedule') { + * // Return without saving an entry to SimpleStore#_completedQueries + * return; + * } + * // Otherwise perform default behavior. + * return SimpleStore.prototype.cachedFindAll.call(this, mapperName, data, hash, opts); + * } + * }); + * + * @example + * // Extend using ES2015 class syntax. + * class MyStore extends SimpleStore { + * cachedFindAll (mapperName, data, hash, opts) { + * // Let's say for a particular Resource, we always want to pull fresh from the server + * if (mapperName === 'schedule') { + * // Return without saving an entry to SimpleStore#_completedQueries + * return; + * } + * // Otherwise perform default behavior. + * return super.cachedFindAll(mapperName, data, hash, opts); + * } + * } + * const store = new MyStore(); + * + * @method SimpleStore#cacheFindAll + * @param {string} name The `name` argument passed to {@link SimpleStore#findAll}. + * @param {*} data The result to cache. + * @param {string} hash The result of calling {@link SimpleStore#hashQuery} on + * the `query` argument passed to {@link SimpleStore#findAll}. + * @param {object} opts The `opts` argument passed to {@link SimpleStore#findAll}. + * @since 3.0.0 + */ + cacheFindAll: function cacheFindAll(name, data, hash, opts) { + var _this2 = this; + + this._completedQueries[name][hash] = function (name, hash, opts) { + return _this2.filter(name, utils.fromJson(hash)); + }; + }, + + + /** + * Remove __all__ records from the in-memory store and reset + * {@link SimpleStore#_completedQueries}. + * + * @method SimpleStore#clear + * @returns {Object} Object containing all records that were in the store. + * @see SimpleStore#remove + * @see SimpleStore#removeAll + * @since 3.0.0 + */ + clear: function clear() { + var _this3 = this; + + var removed = {}; + utils.forOwn(this._collections, function (collection, name) { + removed[name] = collection.removeAll(); + _this3._completedQueries[name] = {}; + }); + return removed; + }, + + + /** + * Fired during {@link SimpleStore#create}. See + * {@link SimpleStore~beforeCreateListener} for how to listen for this event. + * + * @event SimpleStore#beforeCreate + * @see SimpleStore~beforeCreateListener + * @see SimpleStore#create + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeCreate} event. + * + * @example + * function onBeforeCreate (mapperName, props, opts) { + * // do something + * } + * store.on('beforeCreate', onBeforeCreate); + * + * @callback SimpleStore~beforeCreateListener + * @param {string} name The `name` argument received by {@link Mapper#beforeCreate}. + * @param {object} props The `props` argument received by {@link Mapper#beforeCreate}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreate}. + * @see SimpleStore#event:beforeCreate + * @see SimpleStore#create + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#create}. See + * {@link SimpleStore~afterCreateListener} for how to listen for this event. + * + * @event SimpleStore#afterCreate + * @see SimpleStore~afterCreateListener + * @see SimpleStore#create + */ + /** + * Callback signature for the {@link SimpleStore#event:afterCreate} event. + * + * @example + * function onAfterCreate (mapperName, props, opts, result) { + * // do something + * } + * store.on('afterCreate', onAfterCreate); + * + * @callback SimpleStore~afterCreateListener + * @param {string} name The `name` argument received by {@link Mapper#afterCreate}. + * @param {object} props The `props` argument received by {@link Mapper#afterCreate}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterCreate}. + * @param {object} result The `result` argument received by {@link Mapper#afterCreate}. + * @see SimpleStore#event:afterCreate + * @see SimpleStore#create + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#create}. Adds the created record to the store. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('book'); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // POST /book {"author_id":1234,...} + * store.create('book', { + * author_id: 1234, + * edition: 'First Edition', + * title: 'Respect your Data' + * }).then((book) => { + * console.log(book.id); // 120392 + * console.log(book.title); // "Respect your Data" + * }); + * + * @fires SimpleStore#beforeCreate + * @fires SimpleStore#afterCreate + * @fires SimpleStore#add + * @method SimpleStore#create + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} record Passed to {@link Mapper#create}. + * @param {object} [opts] Passed to {@link Mapper#create}. See + * {@link Mapper#create} for more configuration options. + * @returns {Promise} Resolves with the result of the create. + * @since 3.0.0 + */ + create: function create(name, record, opts) { + var _this4 = this; + + opts || (opts = {}); + return Container.prototype.create.call(this, name, record, opts).then(function (result) { + return _this4._end(name, result, opts); + }); + }, + + + /** + * Fired during {@link SimpleStore#createMany}. See + * {@link SimpleStore~beforeCreateManyListener} for how to listen for this event. + * + * @event SimpleStore#beforeCreateMany + * @see SimpleStore~beforeCreateManyListener + * @see SimpleStore#createMany + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeCreateMany} event. + * + * @example + * function onBeforeCreateMany (mapperName, records, opts) { + * // do something + * } + * store.on('beforeCreateMany', onBeforeCreateMany); + * + * @callback SimpleStore~beforeCreateManyListener + * @param {string} name The `name` argument received by {@link Mapper#beforeCreateMany}. + * @param {object} records The `records` argument received by {@link Mapper#beforeCreateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreateMany}. + * @see SimpleStore#event:beforeCreateMany + * @see SimpleStore#createMany + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#createMany}. See + * {@link SimpleStore~afterCreateManyListener} for how to listen for this event. + * + * @event SimpleStore#afterCreateMany + * @see SimpleStore~afterCreateManyListener + * @see SimpleStore#createMany + */ + /** + * Callback signature for the {@link SimpleStore#event:afterCreateMany} event. + * + * @example + * function onAfterCreateMany (mapperName, records, opts, result) { + * // do something + * } + * store.on('afterCreateMany', onAfterCreateMany); + * + * @callback SimpleStore~afterCreateManyListener + * @param {string} name The `name` argument received by {@link Mapper#afterCreateMany}. + * @param {object} records The `records` argument received by {@link Mapper#afterCreateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterCreateMany}. + * @param {object} result The `result` argument received by {@link Mapper#afterCreateMany}. + * @see SimpleStore#event:afterCreateMany + * @see SimpleStore#createMany + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#createMany}. Adds the created records to the + * store. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('book'); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // POST /book [{"author_id":1234,...},{...}] + * store.createMany('book', [{ + * author_id: 1234, + * edition: 'First Edition', + * title: 'Respect your Data' + * }, { + * author_id: 1234, + * edition: 'Second Edition', + * title: 'Respect your Data' + * }]).then((books) => { + * console.log(books[0].id); // 142394 + * console.log(books[0].title); // "Respect your Data" + * }); + * + * @fires SimpleStore#beforeCreateMany + * @fires SimpleStore#afterCreateMany + * @fires SimpleStore#add + * @method SimpleStore#createMany + * @param {string} name Name of the {@link Mapper} to target. + * @param {array} records Passed to {@link Mapper#createMany}. + * @param {object} [opts] Passed to {@link Mapper#createMany}. See + * {@link Mapper#createMany} for more configuration options. + * @returns {Promise} Resolves with the result of the create. + * @since 3.0.0 + */ + createMany: function createMany(name, records, opts) { + var _this5 = this; + + opts || (opts = {}); + return Container.prototype.createMany.call(this, name, records, opts).then(function (result) { + return _this5._end(name, result, opts); + }); + }, + defineMapper: function defineMapper(name, opts) { + var self = this; + var mapper = Container.prototype.defineMapper.call(self, name, opts); + self._pendingQueries[name] = {}; + self._completedQueries[name] = {}; + mapper.relationList || Object.defineProperty(mapper, 'relationList', { value: [] }); + + var collectionOpts = { + // Make sure the collection has somewhere to store "added" timestamps + _added: {}, + // Give the collection a reference to this SimpleStore + datastore: self, + // The mapper tied to the collection + mapper: mapper + }; + + if (opts && 'onConflict' in opts) { + collectionOpts.onConflict = opts.onConflict; + } + + // The SimpleStore uses a subclass of Collection that is "SimpleStore-aware" + var collection = self._collections[name] = new self.collectionClass(null, collectionOpts); // eslint-disable-line + + var schema = mapper.schema || {}; + var properties = schema.properties || {}; + // TODO: Make it possible index nested properties? + utils.forOwn(properties, function (opts, prop) { + if (opts.indexed) { + collection.createIndex(prop); + } + }); + + // Create a secondary index on the "added" timestamps of records in the + // collection + collection.createIndex('addedTimestamps', ['$'], { + fieldGetter: function fieldGetter(obj) { + return collection._added[collection.recordId(obj)]; + } + }); + + collection.on('all', function () { + for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + self._onCollectionEvent.apply(self, [name].concat(args)); + }); + + return mapper; + }, + + + /** + * Fired during {@link SimpleStore#destroy}. See + * {@link SimpleStore~beforeDestroyListener} for how to listen for this event. + * + * @event SimpleStore#beforeDestroy + * @see SimpleStore~beforeDestroyListener + * @see SimpleStore#destroy + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeDestroy} event. + * + * @example + * function onBeforeDestroy (mapperName, id, opts) { + * // do something + * } + * store.on('beforeDestroy', onBeforeDestroy); + * + * @callback SimpleStore~beforeDestroyListener + * @param {string} name The `name` argument received by {@link Mapper#beforeDestroy}. + * @param {string|number} id The `id` argument received by {@link Mapper#beforeDestroy}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroy}. + * @see SimpleStore#event:beforeDestroy + * @see SimpleStore#destroy + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#destroy}. See + * {@link SimpleStore~afterDestroyListener} for how to listen for this event. + * + * @event SimpleStore#afterDestroy + * @see SimpleStore~afterDestroyListener + * @see SimpleStore#destroy + */ + /** + * Callback signature for the {@link SimpleStore#event:afterDestroy} event. + * + * @example + * function onAfterDestroy (mapperName, id, opts, result) { + * // do something + * } + * store.on('afterDestroy', onAfterDestroy); + * + * @callback SimpleStore~afterDestroyListener + * @param {string} name The `name` argument received by {@link Mapper#afterDestroy}. + * @param {string|number} id The `id` argument received by {@link Mapper#afterDestroy}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterDestroy}. + * @param {object} result The `result` argument received by {@link Mapper#afterDestroy}. + * @see SimpleStore#event:afterDestroy + * @see SimpleStore#destroy + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#destroy}. Removes any destroyed record from the + * in-memory store. Clears out any {@link SimpleStore#_completedQueries} entries + * associated with the provided `id`. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('book'); + * + * store.add('book', { id: 1234, title: 'Data Management is Hard' }); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // DELETE /book/1234 + * store.destroy('book', 1234).then(() => { + * // The book record is no longer in the in-memory store + * console.log(store.get('book', 1234)); // undefined + * + * return store.find('book', 1234); + * }).then((book) { + * // The book was deleted from the database too + * console.log(book); // undefined + * }); + * + * @fires SimpleStore#beforeDestroy + * @fires SimpleStore#afterDestroy + * @fires SimpleStore#remove + * @method SimpleStore#destroy + * @param {string} name Name of the {@link Mapper} to target. + * @param {(string|number)} id Passed to {@link Mapper#destroy}. + * @param {object} [opts] Passed to {@link Mapper#destroy}. See + * {@link Mapper#destroy} for more configuration options. + * @returns {Promise} Resolves when the destroy operation completes. + * @since 3.0.0 + */ + destroy: function destroy(name, id, opts) { + var _this6 = this; + + opts || (opts = {}); + return Container.prototype.destroy.call(this, name, id, opts).then(function (result) { + var record = _this6.getCollection(name).remove(id, opts); + + if (opts.raw) { + result.data = record; + } else { + result = record; + } + delete _this6._pendingQueries[name][id]; + delete _this6._completedQueries[name][id]; + return result; + }); + }, + + + /** + * Fired during {@link SimpleStore#destroyAll}. See + * {@link SimpleStore~beforeDestroyAllListener} for how to listen for this event. + * + * @event SimpleStore#beforeDestroyAll + * @see SimpleStore~beforeDestroyAllListener + * @see SimpleStore#destroyAll + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeDestroyAll} event. + * + * @example + * function onBeforeDestroyAll (mapperName, query, opts) { + * // do something + * } + * store.on('beforeDestroyAll', onBeforeDestroyAll); + * + * @callback SimpleStore~beforeDestroyAllListener + * @param {string} name The `name` argument received by {@link Mapper#beforeDestroyAll}. + * @param {object} query The `query` argument received by {@link Mapper#beforeDestroyAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroyAll}. + * @see SimpleStore#event:beforeDestroyAll + * @see SimpleStore#destroyAll + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#destroyAll}. See + * {@link SimpleStore~afterDestroyAllListener} for how to listen for this event. + * + * @event SimpleStore#afterDestroyAll + * @see SimpleStore~afterDestroyAllListener + * @see SimpleStore#destroyAll + */ + /** + * Callback signature for the {@link SimpleStore#event:afterDestroyAll} event. + * + * @example + * function onAfterDestroyAll (mapperName, query, opts, result) { + * // do something + * } + * store.on('afterDestroyAll', onAfterDestroyAll); + * + * @callback SimpleStore~afterDestroyAllListener + * @param {string} name The `name` argument received by {@link Mapper#afterDestroyAll}. + * @param {object} query The `query` argument received by {@link Mapper#afterDestroyAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterDestroyAll}. + * @param {object} result The `result` argument received by {@link Mapper#afterDestroyAll}. + * @see SimpleStore#event:afterDestroyAll + * @see SimpleStore#destroyAll + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#destroyAll}. Removes any destroyed records from + * the in-memory store. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('book'); + * + * store.add('book', { id: 1234, title: 'Data Management is Hard' }); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // DELETE /book/1234 + * store.destroy('book', 1234).then(() => { + * // The book record is gone from the in-memory store + * console.log(store.get('book', 1234)); // undefined + * return store.find('book', 1234); + * }).then((book) { + * // The book was deleted from the database too + * console.log(book); // undefined + * }); + * + * @fires SimpleStore#beforeDestroyAll + * @fires SimpleStore#afterDestroyAll + * @fires SimpleStore#remove + * @method SimpleStore#destroyAll + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} [query] Passed to {@link Mapper#destroyAll}. + * @param {object} [opts] Passed to {@link Mapper#destroyAll}. See + * {@link Mapper#destroyAll} for more configuration options. + * @returns {Promise} Resolves when the delete completes. + * @since 3.0.0 + */ + destroyAll: function destroyAll(name, query, opts) { + var _this7 = this; + + opts || (opts = {}); + return Container.prototype.destroyAll.call(this, name, query, opts).then(function (result) { + var records = _this7.getCollection(name).removeAll(query, opts); + + if (opts.raw) { + result.data = records; + } else { + result = records; + } + var hash = _this7.hashQuery(name, query, opts); + delete _this7._pendingQueries[name][hash]; + delete _this7._completedQueries[name][hash]; + return result; + }); + }, + eject: function eject(name, id, opts) { + console.warn('DEPRECATED: "eject" is deprecated, use "remove" instead'); + return this.remove(name, id, opts); + }, + ejectAll: function ejectAll(name, query, opts) { + console.warn('DEPRECATED: "ejectAll" is deprecated, use "removeAll" instead'); + return this.removeAll(name, query, opts); + }, + + + /** + * Fired during {@link SimpleStore#find}. See + * {@link SimpleStore~beforeFindListener} for how to listen for this event. + * + * @event SimpleStore#beforeFind + * @see SimpleStore~beforeFindListener + * @see SimpleStore#find + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeFind} event. + * + * @example + * function onBeforeFind (mapperName, id, opts) { + * // do something + * } + * store.on('beforeFind', onBeforeFind); + * + * @callback SimpleStore~beforeFindListener + * @param {string} name The `name` argument received by {@link Mapper#beforeFind}. + * @param {string|number} id The `id` argument received by {@link Mapper#beforeFind}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeFind}. + * @see SimpleStore#event:beforeFind + * @see SimpleStore#find + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#find}. See + * {@link SimpleStore~afterFindListener} for how to listen for this event. + * + * @event SimpleStore#afterFind + * @see SimpleStore~afterFindListener + * @see SimpleStore#find + */ + /** + * Callback signature for the {@link SimpleStore#event:afterFind} event. + * + * @example + * function onAfterFind (mapperName, id, opts, result) { + * // do something + * } + * store.on('afterFind', onAfterFind); + * + * @callback SimpleStore~afterFindListener + * @param {string} name The `name` argument received by {@link Mapper#afterFind}. + * @param {string|number} id The `id` argument received by {@link Mapper#afterFind}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterFind}. + * @param {object} result The `result` argument received by {@link Mapper#afterFind}. + * @see SimpleStore#event:afterFind + * @see SimpleStore#find + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#find}. Adds any found record to the store. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('book'); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // GET /book/1234 + * store.find('book', 1234).then((book) => { + * // The book record is now in the in-memory store + * console.log(store.get('book', 1234) === book); // true + * }); + * + * @fires SimpleStore#beforeFind + * @fires SimpleStore#afterFind + * @fires SimpleStore#add + * @method SimpleStore#find + * @param {string} name Name of the {@link Mapper} to target. + * @param {(string|number)} id Passed to {@link Mapper#find}. + * @param {object} [opts] Passed to {@link Mapper#find}. + * @param {boolean} [opts.force] Bypass cacheFind + * @param {boolean|Function} [opts.usePendingFind] See {@link SimpleStore#usePendingFind} + * @returns {Promise} Resolves with the result, if any. + * @since 3.0.0 + */ + find: function find(name, id, opts) { + var _this8 = this; + + opts || (opts = {}); + var mapper = this.getMapper(name); + var pendingQuery = this._pendingQueries[name][id]; + var usePendingFind = opts.usePendingFind === undefined ? this.usePendingFind : opts.usePendingFind; + utils._(opts, mapper); + + if (pendingQuery && (utils.isFunction(usePendingFind) ? usePendingFind.call(this, name, id, opts) : usePendingFind)) { + return pendingQuery; + } + var item = this.cachedFind(name, id, opts); + + if (opts.force || !item) { + var promise = this._pendingQueries[name][id] = Container.prototype.find.call(this, name, id, opts); + return promise.then(function (result) { + delete _this8._pendingQueries[name][id]; + result = _this8._end(name, result, opts); + _this8.cacheFind(name, result, id, opts); + return result; + }, function (err) { + delete _this8._pendingQueries[name][id]; + return utils.reject(err); + }); + } + + return utils.resolve(item); + }, + + + /** + * Fired during {@link SimpleStore#findAll}. See + * {@link SimpleStore~beforeFindAllListener} for how to listen for this event. + * + * @event SimpleStore#beforeFindAll + * @see SimpleStore~beforeFindAllListener + * @see SimpleStore#findAll + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeFindAll} event. + * + * @example + * function onBeforeFindAll (mapperName, query, opts) { + * // do something + * } + * store.on('beforeFindAll', onBeforeFindAll); + * + * @callback SimpleStore~beforeFindAllListener + * @param {string} name The `name` argument received by {@link Mapper#beforeFindAll}. + * @param {object} query The `query` argument received by {@link Mapper#beforeFindAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeFindAll}. + * @see SimpleStore#event:beforeFindAll + * @see SimpleStore#findAll + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#findAll}. See + * {@link SimpleStore~afterFindAllListener} for how to listen for this event. + * + * @event SimpleStore#afterFindAll + * @see SimpleStore~afterFindAllListener + * @see SimpleStore#findAll + */ + /** + * Callback signature for the {@link SimpleStore#event:afterFindAll} event. + * + * @example + * function onAfterFindAll (mapperName, query, opts, result) { + * // do something + * } + * store.on('afterFindAll', onAfterFindAll); + * + * @callback SimpleStore~afterFindAllListener + * @param {string} name The `name` argument received by {@link Mapper#afterFindAll}. + * @param {object} query The `query` argument received by {@link Mapper#afterFindAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterFindAll}. + * @param {object} result The `result` argument received by {@link Mapper#afterFindAll}. + * @see SimpleStore#event:afterFindAll + * @see SimpleStore#findAll + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#findAll}. Adds any found records to the store. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('movie'); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // GET /movie?rating=PG + * store.find('movie', { rating: 'PG' }).then((movies) => { + * // The movie records are now in the in-memory store + * console.log(store.filter('movie')); + * }); + * + * @fires SimpleStore#beforeFindAll + * @fires SimpleStore#afterFindAll + * @fires SimpleStore#add + * @method SimpleStore#findAll + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} [query] Passed to {@link Mapper.findAll}. + * @param {object} [opts] Passed to {@link Mapper.findAll}. + * @param {boolean} [opts.force] Bypass cacheFindAll + * @param {boolean|Function} [opts.usePendingFindAll] See {@link SimpleStore#usePendingFindAll} + * @returns {Promise} Resolves with the result, if any. + * @since 3.0.0 + */ + findAll: function findAll(name, query, opts) { + var _this9 = this; + + opts || (opts = {}); + var mapper = this.getMapper(name); + var hash = this.hashQuery(name, query, opts); + var pendingQuery = this._pendingQueries[name][hash]; + var usePendingFindAll = opts.usePendingFindAll === undefined ? this.usePendingFindAll : opts.usePendingFindAll; + utils._(opts, mapper); + + if (pendingQuery && (utils.isFunction(usePendingFindAll) ? usePendingFindAll.call(this, name, query, opts) : usePendingFindAll)) { + return pendingQuery; + } + + var items = this.cachedFindAll(name, hash, opts); + + if (opts.force || !items) { + var promise = this._pendingQueries[name][hash] = Container.prototype.findAll.call(this, name, query, opts); + return promise.then(function (result) { + delete _this9._pendingQueries[name][hash]; + result = _this9._end(name, result, opts); + _this9.cacheFindAll(name, result, hash, opts); + return result; + }, function (err) { + delete _this9._pendingQueries[name][hash]; + return utils.reject(err); + }); + } + + return utils.resolve(items); + }, + + + /** + * Return the {@link Collection} with the given name, if for some + * reason you need a direct reference to the collection. + * + * @method SimpleStore#getCollection + * @param {string} name Name of the {@link Collection} to retrieve. + * @returns {Collection} + * @since 3.0.0 + * @throws {Error} Thrown if the specified {@link Collection} does not + * exist. + */ + getCollection: function getCollection(name) { + var collection = this._collections[name]; + if (!collection) { + throw utils.err(DOMAIN$8 + '#getCollection', name)(404, 'collection'); + } + return collection; + }, + + + /** + * Hashing function used to cache {@link SimpleStore#find} and + * {@link SimpleStore#findAll} requests. This method simply JSONifies the + * `query` argument passed to {@link SimpleStore#find} or + * {@link SimpleStore#findAll}. + * + * Override this method for custom hashing behavior. + * @method SimpleStore#hashQuery + * @param {string} name The `name` argument passed to {@link SimpleStore#find} + * or {@link SimpleStore#findAll}. + * @param {object} query The `query` argument passed to {@link SimpleStore#find} + * or {@link SimpleStore#findAll}. + * @returns {string} The JSONified `query`. + * @since 3.0.0 + */ + hashQuery: function hashQuery(name, query, opts) { + return utils.toJson(query || {}); + }, + inject: function inject(name, records, opts) { + console.warn('DEPRECATED: "inject" is deprecated, use "add" instead'); + return this.add(name, records, opts); + }, + + + /** + * Wrapper for {@link Collection#remove}. Removes the specified + * {@link Record} from the store. + * + * @example SimpleStore#remove + * const JSData = require('js-data'); + * const { SimpleStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new SimpleStore(); + * store.defineMapper('book'); + * console.log(store.getAll('book').length); + * store.add('book', { id: 1234 }); + * console.log(store.getAll('book').length); + * store.remove('book', 1234); + * console.log(store.getAll('book').length); + * + * @fires SimpleStore#remove + * @method SimpleStore#remove + * @param {string} name The name of the {@link Collection} to target. + * @param {string|number} id The primary key of the {@link Record} to remove. + * @param {object} [opts] Configuration options. + * @param {string[]} [opts.with] Relations of the {@link Record} to also + * remove from the store. + * @returns {Record} The removed {@link Record}, if any. + * @see Collection#add + * @see Collection#add + * @since 3.0.0 + */ + remove: function remove(name, id, opts) { + var record = this.getCollection(name).remove(id, opts); + if (record) { + this.removeRelated(name, [record], opts); + } + return record; + }, + + + /** + * Wrapper for {@link Collection#removeAll}. Removes the selected + * {@link Record}s from the store. + * + * @example SimpleStore#removeAll + * const JSData = require('js-data'); + * const { SimpleStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new SimpleStore(); + * store.defineMapper('movie'); + * console.log(store.getAll('movie').length); + * store.add('movie', [{ id: 3, rating: 'R' }, { id: 4, rating: 'PG-13' }); + * console.log(store.getAll('movie').length); + * store.removeAll('movie', { rating: 'R' }); + * console.log(store.getAll('movie').length); + * + * @fires SimpleStore#remove + * @method SimpleStore#removeAll + * @param {string} name The name of the {@link Collection} to target. + * @param {object} [query={}] Selection query. See {@link query}. + * @param {object} [query.where] See {@link query.where}. + * @param {number} [query.offset] See {@link query.offset}. + * @param {number} [query.limit] See {@link query.limit}. + * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}. + * @param {object} [opts] Configuration options. + * @param {string[]} [opts.with] Relations of the {@link Record} to also + * remove from the store. + * @returns {Record} The removed {@link Record}s, if any. + * @see Collection#add + * @see Collection#add + * @since 3.0.0 + */ + removeAll: function removeAll(name, query, opts) { + if (!query || !Object.keys(query).length) { + this._completedQueries[name] = {}; + } else { + this._completedQueries[name][this.hashQuery(name, query, opts)] = undefined; + } + var records = this.getCollection(name).removeAll(query, opts); + if (records.length) { + this.removeRelated(name, records, opts); + } + return records; + }, + + + /** + * Remove from the store {@link Record}s that are related to the provided + * {@link Record}(s). + * + * @fires SimpleStore#remove + * @method SimpleStore#removeRelated + * @param {string} name The name of the {@link Collection} to target. + * @param {Record|Record[]} records {@link Record}s whose relations are to be + * removed. + * @param {object} [opts] Configuration options. + * @param {string[]} [opts.with] Relations of the {@link Record}(s) to remove + * from the store. + * @since 3.0.0 + */ + removeRelated: function removeRelated(name, records, opts) { + var _this10 = this; + + if (!utils.isArray(records)) { + records = [records]; + } + utils.forEachRelation(this.getMapper(name), opts, function (def, optsCopy) { + records.forEach(function (record) { + var relatedData = void 0; + var query = void 0; + if (def.foreignKey && (def.type === hasOneType || def.type === hasManyType)) { + query = defineProperty({}, def.foreignKey, def.getForeignKey(record)); + } else if (def.type === hasManyType && def.localKeys) { + query = { + where: defineProperty({}, def.getRelation().idAttribute, { + 'in': utils.get(record, def.localKeys) + }) + }; + } else if (def.type === hasManyType && def.foreignKeys) { + query = { + where: defineProperty({}, def.foreignKeys, { + 'contains': def.getForeignKey(record) + }) + }; + } else if (def.type === belongsToType) { + relatedData = _this10.remove(def.relation, def.getForeignKey(record), optsCopy); + } + if (query) { + relatedData = _this10.removeAll(def.relation, query, optsCopy); + } + if (relatedData) { + if (utils.isArray(relatedData) && !relatedData.length) { + return; + } + if (def.type === hasOneType) { + relatedData = relatedData[0]; + } + def.setLocalField(record, relatedData); + } + }); + }); + }, + + + /** + * Fired during {@link SimpleStore#update}. See + * {@link SimpleStore~beforeUpdateListener} for how to listen for this event. + * + * @event SimpleStore#beforeUpdate + * @see SimpleStore~beforeUpdateListener + * @see SimpleStore#update + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeUpdate} event. + * + * @example + * function onBeforeUpdate (mapperName, id, props, opts) { + * // do something + * } + * store.on('beforeUpdate', onBeforeUpdate); + * + * @callback SimpleStore~beforeUpdateListener + * @param {string} name The `name` argument received by {@link Mapper#beforeUpdate}. + * @param {string|number} id The `id` argument received by {@link Mapper#beforeUpdate}. + * @param {object} props The `props` argument received by {@link Mapper#beforeUpdate}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdate}. + * @see SimpleStore#event:beforeUpdate + * @see SimpleStore#update + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#update}. See + * {@link SimpleStore~afterUpdateListener} for how to listen for this event. + * + * @event SimpleStore#afterUpdate + * @see SimpleStore~afterUpdateListener + * @see SimpleStore#update + */ + /** + * Callback signature for the {@link SimpleStore#event:afterUpdate} event. + * + * @example + * function onAfterUpdate (mapperName, id, props, opts, result) { + * // do something + * } + * store.on('afterUpdate', onAfterUpdate); + * + * @callback SimpleStore~afterUpdateListener + * @param {string} name The `name` argument received by {@link Mapper#afterUpdate}. + * @param {string|number} id The `id` argument received by {@link Mapper#afterUpdate}. + * @param {object} props The `props` argument received by {@link Mapper#afterUpdate}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdate}. + * @param {object} result The `result` argument received by {@link Mapper#afterUpdate}. + * @see SimpleStore#event:afterUpdate + * @see SimpleStore#update + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#update}. Adds the updated {@link Record} to the + * store. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('post'); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // PUT /post/1234 {"status":"published"} + * store.update('post', 1, { status: 'published' }).then((post) => { + * // The post record has also been updated in the in-memory store + * console.log(store.get('post', 1234)); + * }); + * + * @fires SimpleStore#beforeUpdate + * @fires SimpleStore#afterUpdate + * @fires SimpleStore#add + * @method SimpleStore#update + * @param {string} name Name of the {@link Mapper} to target. + * @param {(string|number)} id Passed to {@link Mapper#update}. + * @param {object} record Passed to {@link Mapper#update}. + * @param {object} [opts] Passed to {@link Mapper#update}. See + * {@link Mapper#update} for more configuration options. + * @returns {Promise} Resolves with the result of the update. + * @since 3.0.0 + */ + update: function update(name, id, record, opts) { + var _this11 = this; + + opts || (opts = {}); + return Container.prototype.update.call(this, name, id, record, opts).then(function (result) { + return _this11._end(name, result, opts); + }); + }, + + + /** + * Fired during {@link SimpleStore#updateAll}. See + * {@link SimpleStore~beforeUpdateAllListener} for how to listen for this event. + * + * @event SimpleStore#beforeUpdateAll + * @see SimpleStore~beforeUpdateAllListener + * @see SimpleStore#updateAll + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeUpdateAll} event. + * + * @example + * function onBeforeUpdateAll (mapperName, props, query, opts) { + * // do something + * } + * store.on('beforeUpdateAll', onBeforeUpdateAll); + * + * @callback SimpleStore~beforeUpdateAllListener + * @param {string} name The `name` argument received by {@link Mapper#beforeUpdateAll}. + * @param {object} props The `props` argument received by {@link Mapper#beforeUpdateAll}. + * @param {object} query The `query` argument received by {@link Mapper#beforeUpdateAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateAll}. + * @see SimpleStore#event:beforeUpdateAll + * @see SimpleStore#updateAll + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#updateAll}. See + * {@link SimpleStore~afterUpdateAllListener} for how to listen for this event. + * + * @event SimpleStore#afterUpdateAll + * @see SimpleStore~afterUpdateAllListener + * @see SimpleStore#updateAll + */ + /** + * Callback signature for the {@link SimpleStore#event:afterUpdateAll} event. + * + * @example + * function onAfterUpdateAll (mapperName, props, query, opts, result) { + * // do something + * } + * store.on('afterUpdateAll', onAfterUpdateAll); + * + * @callback SimpleStore~afterUpdateAllListener + * @param {string} name The `name` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} props The `props` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} query The `query` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} result The `result` argument received by {@link Mapper#afterUpdateAll}. + * @see SimpleStore#event:afterUpdateAll + * @see SimpleStore#updateAll + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#updateAll}. Adds the updated {@link Record}s to + * the store. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('post'); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // PUT /post?author_id=1234 {"status":"published"} + * store.updateAll('post', { author_id: 1234 }, { status: 'published' }).then((posts) => { + * // The post records have also been updated in the in-memory store + * console.log(store.filter('posts', { author_id: 1234 })); + * }); + * + * @fires SimpleStore#beforeUpdateAll + * @fires SimpleStore#afterUpdateAll + * @fires SimpleStore#add + * @method SimpleStore#updateAll + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} props Passed to {@link Mapper#updateAll}. + * @param {object} [query] Passed to {@link Mapper#updateAll}. + * @param {object} [opts] Passed to {@link Mapper#updateAll}. See + * {@link Mapper#updateAll} for more configuration options. + * @returns {Promise} Resolves with the result of the update. + * @since 3.0.0 + */ + updateAll: function updateAll(name, props, query, opts) { + var _this12 = this; + + opts || (opts = {}); + return Container.prototype.updateAll.call(this, name, props, query, opts).then(function (result) { + return _this12._end(name, result, opts); + }); + }, + + + /** + * Fired during {@link SimpleStore#updateMany}. See + * {@link SimpleStore~beforeUpdateManyListener} for how to listen for this event. + * + * @event SimpleStore#beforeUpdateMany + * @see SimpleStore~beforeUpdateManyListener + * @see SimpleStore#updateMany + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeUpdateMany} event. + * + * @example + * function onBeforeUpdateMany (mapperName, records, opts) { + * // do something + * } + * store.on('beforeUpdateMany', onBeforeUpdateMany); + * + * @callback SimpleStore~beforeUpdateManyListener + * @param {string} name The `name` argument received by {@link Mapper#beforeUpdateMany}. + * @param {object} records The `records` argument received by {@link Mapper#beforeUpdateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateMany}. + * @see SimpleStore#event:beforeUpdateMany + * @see SimpleStore#updateMany + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#updateMany}. See + * {@link SimpleStore~afterUpdateManyListener} for how to listen for this event. + * + * @event SimpleStore#afterUpdateMany + * @see SimpleStore~afterUpdateManyListener + * @see SimpleStore#updateMany + */ + /** + * Callback signature for the {@link SimpleStore#event:afterUpdateMany} event. + * + * @example + * function onAfterUpdateMany (mapperName, records, opts, result) { + * // do something + * } + * store.on('afterUpdateMany', onAfterUpdateMany); + * + * @callback SimpleStore~afterUpdateManyListener + * @param {string} name The `name` argument received by {@link Mapper#afterUpdateMany}. + * @param {object} records The `records` argument received by {@link Mapper#afterUpdateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateMany}. + * @param {object} result The `result` argument received by {@link Mapper#afterUpdateMany}. + * @see SimpleStore#event:afterUpdateMany + * @see SimpleStore#updateMany + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#updateMany}. Adds the updated {@link Record}s to + * the store. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('post'); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // PUT /post [{"id":3,status":"published"},{"id":4,status":"published"}] + * store.updateMany('post', [ + * { id: 3, status: 'published' }, + * { id: 4, status: 'published' } + * ]).then((posts) => { + * // The post records have also been updated in the in-memory store + * console.log(store.getAll('post', 3, 4)); + * }); + * + * @fires SimpleStore#beforeUpdateMany + * @fires SimpleStore#afterUpdateMany + * @fires SimpleStore#add + * @method SimpleStore#updateMany + * @param {string} name Name of the {@link Mapper} to target. + * @param {(Object[]|Record[])} records Passed to {@link Mapper#updateMany}. + * @param {object} [opts] Passed to {@link Mapper#updateMany}. See + * {@link Mapper#updateMany} for more configuration options. + * @returns {Promise} Resolves with the result of the update. + * @since 3.0.0 + */ + updateMany: function updateMany(name, records, opts) { + var _this13 = this; + + opts || (opts = {}); + return Container.prototype.updateMany.call(this, name, records, opts).then(function (result) { + return _this13._end(name, result, opts); + }); + } +}; + +proxiedCollectionMethods.forEach(function (method) { + props$2[method] = function (name) { + var _getCollection; + + for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + + return (_getCollection = this.getCollection(name))[method].apply(_getCollection, args); + }; +}); + +var SimpleStore$1 = Container.extend(props$2); + +/** + * Fired when a record changes. Only works for records that have tracked fields. + * See {@link SimpleStore~changeListener} on how to listen for this event. + * + * @event SimpleStore#change + * @see SimpleStore~changeListener + */ + +/** + * Callback signature for the {@link SimpleStore#event:change} event. + * + * @example + * function onChange (mapperName, record, changes) { + * // do something + * } + * store.on('change', onChange); + * + * @callback SimpleStore~changeListener + * @param {string} name The name of the associated {@link Mapper}. + * @param {Record} record The Record that changed. + * @param {object} changes The changes. + * @see SimpleStore#event:change + * @since 3.0.0 + */ + +/** + * Fired when one or more records are added to the in-memory store. See + * {@link SimpleStore~addListener} on how to listen for this event. + * + * @event SimpleStore#add + * @see SimpleStore~addListener + * @see SimpleStore#event:add + * @see SimpleStore#add + * @see SimpleStore#create + * @see SimpleStore#createMany + * @see SimpleStore#find + * @see SimpleStore#findAll + * @see SimpleStore#update + * @see SimpleStore#updateAll + * @see SimpleStore#updateMany + */ + +/** + * Callback signature for the {@link SimpleStore#event:add} event. + * + * @example + * function onAdd (mapperName, recordOrRecords) { + * // do something + * } + * store.on('add', onAdd); + * + * @callback SimpleStore~addListener + * @param {string} name The name of the associated {@link Mapper}. + * @param {Record|Record[]} The Record or Records that were added. + * @see SimpleStore#event:add + * @see SimpleStore#add + * @see SimpleStore#create + * @see SimpleStore#createMany + * @see SimpleStore#find + * @see SimpleStore#findAll + * @see SimpleStore#update + * @see SimpleStore#updateAll + * @see SimpleStore#updateMany + * @since 3.0.0 + */ + +/** + * Fired when one or more records are removed from the in-memory store. See + * {@link SimpleStore~removeListener} for how to listen for this event. + * + * @event SimpleStore#remove + * @see SimpleStore~removeListener + * @see SimpleStore#event:remove + * @see SimpleStore#clear + * @see SimpleStore#destroy + * @see SimpleStore#destroyAll + * @see SimpleStore#remove + * @see SimpleStore#removeAll + */ + +/** + * Callback signature for the {@link SimpleStore#event:remove} event. + * + * @example + * function onRemove (mapperName, recordsOrRecords) { + * // do something + * } + * store.on('remove', onRemove); + * + * @callback SimpleStore~removeListener + * @param {string} name The name of the associated {@link Mapper}. + * @param {Record|Record[]} Record or Records that were removed. + * @see SimpleStore#event:remove + * @see SimpleStore#clear + * @see SimpleStore#destroy + * @see SimpleStore#destroyAll + * @see SimpleStore#remove + * @see SimpleStore#removeAll + * @since 3.0.0 + */ + +/** + * Create a subclass of this SimpleStore: + * @example SimpleStore.extend + * const JSData = require('js-data'); + * const { SimpleStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomSimpleStoreClass extends SimpleStore { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customSimpleStore = new CustomSimpleStoreClass(); + * console.log(customSimpleStore.foo()); + * console.log(CustomSimpleStoreClass.beep()); + * + * // Extend the class using alternate method. + * const OtherSimpleStoreClass = SimpleStore.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }) + * const otherSimpleStore = new OtherSimpleStoreClass(); + * console.log(otherSimpleStore.foo()); + * console.log(OtherSimpleStoreClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherSimpleStoreClass () { + * SimpleStore.call(this) + * this.created_at = new Date().getTime() + * } + * SimpleStore.extend({ + * constructor: AnotherSimpleStoreClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }) + * const anotherSimpleStore = new AnotherSimpleStoreClass(); + * console.log(anotherSimpleStore.created_at); + * console.log(anotherSimpleStore.foo()); + * console.log(AnotherSimpleStoreClass.beep()); + * + * @method SimpleStore.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this SimpleStore class. + * @since 3.0.0 + */ + +var DOMAIN$9 = 'LinkedCollection'; + +/** + * Extends {@link Collection}. Used by a {@link DataStore} to implement an + * Identity Map. + * + * ```javascript + * import {LinkedCollection} from 'js-data' + * ``` + * + * @class LinkedCollection + * @extends Collection + * @param {array} [records] Initial set of records to insert into the + * collection. See {@link Collection}. + * @param {object} [opts] Configuration options. See {@link Collection}. + * @returns {Mapper} + */ +function LinkedCollection(records, opts) { + utils.classCallCheck(this, LinkedCollection); + // Make sure this collection has somewhere to store "added" timestamps + Object.defineProperties(this, { + _added: { + value: {} + }, + datastore: { + writable: true, + value: undefined + } + }); + + Collection$1.call(this, records, opts); + + // Make sure this collection has a reference to a datastore + if (!this.datastore) { + throw utils.err('new ' + DOMAIN$9, 'opts.datastore')(400, 'DataStore', this.datastore); + } +} + +var LinkedCollection$1 = Collection$1.extend({ + constructor: LinkedCollection, + + _addMeta: function _addMeta(record, timestamp) { + // Track when this record was added + this._added[this.recordId(record)] = timestamp; + + if (utils.isFunction(record._set)) { + record._set('$', timestamp); + } + }, + _clearMeta: function _clearMeta(record) { + delete this._added[this.recordId(record)]; + if (utils.isFunction(record._set)) { + record._set('$'); // unset + } + }, + _onRecordEvent: function _onRecordEvent() { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + Collection$1.prototype._onRecordEvent.apply(this, args); + var event = args[0]; + // This is a very brute force method + // Lots of room for optimization + if (utils.isString(event) && event.indexOf('change') === 0) { + this.updateIndexes(args[1]); + } + }, + add: function add(records, opts) { + var _this = this; + + var mapper = this.mapper; + var timestamp = new Date().getTime(); + var singular = utils.isObject(records) && !utils.isArray(records); + + if (singular) { + records = [records]; + } + records = Collection$1.prototype.add.call(this, records, opts); + + if (mapper.relationList.length && records.length) { + // Check the currently visited record for relations that need to be + // inserted into their respective collections. + mapper.relationList.forEach(function (def) { + def.addLinkedRecords(records); + }); + } + + records.forEach(function (record) { + return _this._addMeta(record, timestamp); + }); + + return singular ? records[0] : records; + }, + remove: function remove(idOrRecord, opts) { + var mapper = this.mapper; + var record = Collection$1.prototype.remove.call(this, idOrRecord, opts); + if (record) { + this._clearMeta(record); + } + + if (mapper.relationList.length && record) { + mapper.relationList.forEach(function (def) { + def.removeLinkedRecords(mapper, [record]); + }); + } + + return record; + }, + removeAll: function removeAll(query, opts) { + var mapper = this.mapper; + var records = Collection$1.prototype.removeAll.call(this, query, opts); + records.forEach(this._clearMeta, this); + + if (mapper.relationList.length && records.length) { + mapper.relationList.forEach(function (def) { + def.removeLinkedRecords(mapper, records); + }); + } + + return records; + } +}); + +/** + * Create a subclass of this LinkedCollection: + * + * @example LinkedCollection.extend + * const JSData = require('js-data'); + * const { LinkedCollection } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomLinkedCollectionClass extends LinkedCollection { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customLinkedCollection = new CustomLinkedCollectionClass(); + * console.log(customLinkedCollection.foo()); + * console.log(CustomLinkedCollectionClass.beep()); + * + * // Extend the class using alternate method. + * const OtherLinkedCollectionClass = LinkedCollection.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherLinkedCollection = new OtherLinkedCollectionClass(); + * console.log(otherLinkedCollection.foo()); + * console.log(OtherLinkedCollectionClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherLinkedCollectionClass () { + * LinkedCollection.call(this); + * this.created_at = new Date().getTime(); + * } + * LinkedCollection.extend({ + * constructor: AnotherLinkedCollectionClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const anotherLinkedCollection = new AnotherLinkedCollectionClass(); + * console.log(anotherLinkedCollection.created_at); + * console.log(anotherLinkedCollection.foo()); + * console.log(AnotherLinkedCollectionClass.beep()); + * + * @method LinkedCollection.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this LinkedCollection class. + * @since 3.0.0 + */ + +var DATASTORE_DEFAULTS = { + /** + * Whether in-memory relations should be unlinked from records after they are + * destroyed. + * + * @default true + * @name DataStore#unlinkOnDestroy + * @since 3.0.0 + * @type {boolean} + */ + unlinkOnDestroy: true + + /** + * The `DataStore` class is an extension of {@link SimpleStore}. Not only does + * `DataStore` manage mappers and store data in collections, it uses the + * {@link LinkedCollection} class to link related records together in memory. + * + * ```javascript + * import { DataStore } from 'js-data'; + * ``` + * + * @example + * import { DataStore } from 'js-data'; + * import HttpAdapter from 'js-data-http'; + * const store = new DataStore(); + * + * // DataStore#defineMapper returns a direct reference to the newly created + * // Mapper. + * const UserMapper = store.defineMapper('user'); + * + * // DataStore#as returns the store scoped to a particular Mapper. + * const UserStore = store.as('user'); + * + * // Call "find" on "UserMapper" (Stateless ORM) + * UserMapper.find(1).then((user) => { + * // retrieved a "user" record via the http adapter, but that's it + * + * // Call "find" on "store" targeting "user" (Stateful DataStore) + * return store.find('user', 1); // same as "UserStore.find(1)" + * }).then((user) => { + * // not only was a "user" record retrieved, but it was added to the + * // store's "user" collection + * const cachedUser = store.getCollection('user').get(1); + * console.log(user === cachedUser); // true + * }); + * + * @class DataStore + * @extends SimpleStore + * @param {object} [opts] Configuration options. See {@link SimpleStore}. + * @param {boolean} [opts.collectionClass={@link LinkedCollection}] See {@link DataStore#collectionClass}. + * @param {boolean} [opts.debug=false] See {@link Component#debug}. + * @param {boolean} [opts.unlinkOnDestroy=true] See {@link DataStore#unlinkOnDestroy}. + * @param {boolean|Function} [opts.usePendingFind=true] See {@link DataStore#usePendingFind}. + * @param {boolean|Function} [opts.usePendingFindAll=true] See {@link DataStore#usePendingFindAll}. + * @returns {DataStore} + * @see SimpleStore + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#datastore","Components of JSData: DataStore"] + * @tutorial ["http://www.js-data.io/v3.0/docs/working-with-the-datastore","Working with the DataStore"] + * @tutorial ["http://www.js-data.io/v3.0/docs/jsdata-and-the-browser","Notes on using JSData in the Browser"] + */ +};function DataStore(opts) { + utils.classCallCheck(this, DataStore); + + opts || (opts = {}); + // Fill in any missing options with the defaults + utils.fillIn(opts, DATASTORE_DEFAULTS); + opts.collectionClass || (opts.collectionClass = LinkedCollection$1); + SimpleStore$1.call(this, opts); +} + +var props$1 = { + constructor: DataStore, + + defineMapper: function defineMapper(name, opts) { + // Complexity of this method is beyond simply using => functions to bind context + var self = this; + var mapper = SimpleStore$1.prototype.defineMapper.call(self, name, opts); + var idAttribute = mapper.idAttribute; + var collection = this.getCollection(name); + + mapper.relationList.forEach(function (def) { + var relation = def.relation; + var localField = def.localField; + var path = 'links.' + localField; + var foreignKey = def.foreignKey; + var type = def.type; + var updateOpts = { index: foreignKey }; + var descriptor = void 0; + + var getter = function getter() { + return this._get(path); + }; + + if (type === belongsToType) { + if (!collection.indexes[foreignKey]) { + collection.createIndex(foreignKey); + } + + descriptor = { + get: getter, + // e.g. profile.user = someUser + // or comment.post = somePost + set: function set(record) { + // e.g. const otherUser = profile.user + var currentParent = this._get(path); + // e.g. profile.user === someUser + if (record === currentParent) { + return currentParent; + } + var id = utils.get(this, idAttribute); + var inverseDef = def.getInverse(mapper); + + // e.g. profile.user !== someUser + // or comment.post !== somePost + if (currentParent && inverseDef) { + this.removeInverseRelation(currentParent, id, inverseDef, idAttribute); + } + if (record) { + // e.g. profile.user = someUser + var relatedIdAttribute = def.getRelation().idAttribute; + var relatedId = utils.get(record, relatedIdAttribute); + + // Prefer store record + if (relatedId !== undefined && this._get('$')) { + record = self.get(relation, relatedId) || record; + } + + // Set locals + // e.g. profile.user = someUser + // or comment.post = somePost + safeSetLink(this, localField, record); + safeSetProp(this, foreignKey, relatedId); + collection.updateIndex(this, updateOpts); + + if (inverseDef) { + this.setupInverseRelation(record, id, inverseDef, idAttribute); + } + } else { + // Unset in-memory link only + // e.g. profile.user = undefined + // or comment.post = undefined + safeSetLink(this, localField, undefined); + } + return record; + } + }; + + var foreignKeyDescriptor = Object.getOwnPropertyDescriptor(mapper.recordClass.prototype, foreignKey); + if (!foreignKeyDescriptor) { + foreignKeyDescriptor = { + enumerable: true + }; + } + var originalGet = foreignKeyDescriptor.get; + foreignKeyDescriptor.get = function () { + if (originalGet) { + return originalGet.call(this); + } + return this._get('props.' + foreignKey); + }; + var originalSet = foreignKeyDescriptor.set; + foreignKeyDescriptor.set = function (value) { + var _this = this; + + if (originalSet) { + originalSet.call(this, value); + } + var currentParent = utils.get(this, localField); + var id = utils.get(this, idAttribute); + var inverseDef = def.getInverse(mapper); + var currentParentId = currentParent ? utils.get(currentParent, def.getRelation().idAttribute) : undefined; + + if (currentParent && currentParentId !== undefined && currentParentId !== value) { + if (inverseDef.type === hasOneType) { + safeSetLink(currentParent, inverseDef.localField, undefined); + } else if (inverseDef.type === hasManyType) { + var children = utils.get(currentParent, inverseDef.localField); + if (id === undefined) { + utils.remove(children, function (child) { + return child === _this; + }); + } else { + utils.remove(children, function (child) { + return child === _this || id === utils.get(child, idAttribute); + }); + } + } + } + + safeSetProp(this, foreignKey, value); + collection.updateIndex(this, updateOpts); + + if (value === undefined || value === null) { + if (currentParentId !== undefined) { + // Unset locals + utils.set(this, localField, undefined); + } + } else if (this._get('$')) { + var storeRecord = self.get(relation, value); + if (storeRecord) { + utils.set(this, localField, storeRecord); + } + } + }; + Object.defineProperty(mapper.recordClass.prototype, foreignKey, foreignKeyDescriptor); + } else if (type === hasManyType) { + var localKeys = def.localKeys; + var foreignKeys = def.foreignKeys; + + // TODO: Handle case when belongsTo relation isn't ever defined + if (self._collections[relation] && foreignKey && !self.getCollection(relation).indexes[foreignKey]) { + self.getCollection(relation).createIndex(foreignKey); + } + + descriptor = { + get: function get() { + var current = getter.call(this); + if (!current) { + this._set(path, []); + } + return getter.call(this); + }, + + // e.g. post.comments = someComments + // or user.groups = someGroups + // or group.users = someUsers + set: function set(records) { + var _this2 = this; + + if (records && !utils.isArray(records)) { + records = [records]; + } + var id = utils.get(this, idAttribute); + var relatedIdAttribute = def.getRelation().idAttribute; + var inverseDef = def.getInverse(mapper); + var inverseLocalField = inverseDef.localField; + var current = this._get(path) || []; + var toLink = []; + var toLinkIds = {}; + + if (records) { + records.forEach(function (record) { + // e.g. comment.id + var relatedId = utils.get(record, relatedIdAttribute); + var currentParent = utils.get(record, inverseLocalField); + if (currentParent && currentParent !== _this2) { + var currentChildrenOfParent = utils.get(currentParent, localField); + // e.g. somePost.comments.remove(comment) + if (relatedId === undefined) { + utils.remove(currentChildrenOfParent, function (child) { + return child === record; + }); + } else { + utils.remove(currentChildrenOfParent, function (child) { + return child === record || relatedId === utils.get(child, relatedIdAttribute); + }); + } + } + if (relatedId !== undefined) { + if (_this2._get('$')) { + // Prefer store record + record = self.get(relation, relatedId) || record; + } + // e.g. toLinkIds[comment.id] = comment + toLinkIds[relatedId] = record; + } + toLink.push(record); + }); + } + + // e.g. post.comments = someComments + if (foreignKey) { + current.forEach(function (record) { + // e.g. comment.id + var relatedId = utils.get(record, relatedIdAttribute); + if (relatedId === undefined && toLink.indexOf(record) === -1 || relatedId !== undefined && !(relatedId in toLinkIds)) { + // Update (unset) inverse relation + if (records) { + // e.g. comment.post_id = undefined + safeSetProp(record, foreignKey, undefined); + // e.g. CommentCollection.updateIndex(comment, { index: 'post_id' }) + self.getCollection(relation).updateIndex(record, updateOpts); + } + // e.g. comment.post = undefined + safeSetLink(record, inverseLocalField, undefined); + } + }); + toLink.forEach(function (record) { + // Update (set) inverse relation + // e.g. comment.post_id = post.id + safeSetProp(record, foreignKey, id); + // e.g. CommentCollection.updateIndex(comment, { index: 'post_id' }) + self.getCollection(relation).updateIndex(record, updateOpts); + // e.g. comment.post = post + safeSetLink(record, inverseLocalField, _this2); + }); + } else if (localKeys) { + // Update locals + // e.g. group.users = someUsers + // Update (set) inverse relation + var ids = toLink.map(function (child) { + return utils.get(child, relatedIdAttribute); + }).filter(function (id) { + return id !== undefined; + }); + // e.g. group.user_ids = [1,2,3,...] + utils.set(this, localKeys, ids); + // Update (unset) inverse relation + if (inverseDef.foreignKeys) { + current.forEach(function (child) { + var relatedId = utils.get(child, relatedIdAttribute); + if (relatedId === undefined && toLink.indexOf(child) === -1 || relatedId !== undefined && !(relatedId in toLinkIds)) { + // Update inverse relation + // safeSetLink(child, inverseLocalField, undefined) + var parents = utils.get(child, inverseLocalField) || []; + // e.g. someUser.groups.remove(group) + if (id === undefined) { + utils.remove(parents, function (parent) { + return parent === _this2; + }); + } else { + utils.remove(parents, function (parent) { + return parent === _this2 || id === utils.get(parent, idAttribute); + }); + } + } + }); + toLink.forEach(function (child) { + // Update (set) inverse relation + var parents = utils.get(child, inverseLocalField); + // e.g. someUser.groups.push(group) + if (id === undefined) { + utils.noDupeAdd(parents, _this2, function (parent) { + return parent === _this2; + }); + } else { + utils.noDupeAdd(parents, _this2, function (parent) { + return parent === _this2 || id === utils.get(parent, idAttribute); + }); + } + }); + } + } else if (foreignKeys) { + // e.g. user.groups = someGroups + // Update (unset) inverse relation + current.forEach(function (parent) { + var ids = utils.get(parent, foreignKeys) || []; + // e.g. someGroup.user_ids.remove(user.id) + utils.remove(ids, function (_key) { + return id === _key; + }); + var children = utils.get(parent, inverseLocalField); + // e.g. someGroup.users.remove(user) + if (id === undefined) { + utils.remove(children, function (child) { + return child === _this2; + }); + } else { + utils.remove(children, function (child) { + return child === _this2 || id === utils.get(child, idAttribute); + }); + } + }); + // Update (set) inverse relation + toLink.forEach(function (parent) { + var ids = utils.get(parent, foreignKeys) || []; + utils.noDupeAdd(ids, id, function (_key) { + return id === _key; + }); + var children = utils.get(parent, inverseLocalField); + if (id === undefined) { + utils.noDupeAdd(children, _this2, function (child) { + return child === _this2; + }); + } else { + utils.noDupeAdd(children, _this2, function (child) { + return child === _this2 || id === utils.get(child, idAttribute); + }); + } + }); + } + + this._set(path, toLink); + return toLink; + } + }; + } else if (type === hasOneType) { + // TODO: Handle case when belongsTo relation isn't ever defined + if (self._collections[relation] && foreignKey && !self.getCollection(relation).indexes[foreignKey]) { + self.getCollection(relation).createIndex(foreignKey); + } + descriptor = { + get: getter, + // e.g. user.profile = someProfile + set: function set(record) { + var current = this._get(path); + if (record === current) { + return current; + } + var inverseLocalField = def.getInverse(mapper).localField; + // Update (unset) inverse relation + if (current) { + safeSetProp(current, foreignKey, undefined); + self.getCollection(relation).updateIndex(current, updateOpts); + safeSetLink(current, inverseLocalField, undefined); + } + if (record) { + var relatedId = utils.get(record, def.getRelation().idAttribute); + // Prefer store record + if (relatedId !== undefined) { + record = self.get(relation, relatedId) || record; + } + + // Set locals + safeSetLink(this, localField, record); + + // Update (set) inverse relation + safeSetProp(record, foreignKey, utils.get(this, idAttribute)); + self.getCollection(relation).updateIndex(record, updateOpts); + safeSetLink(record, inverseLocalField, this); + } else { + // Unset locals + safeSetLink(this, localField, undefined); + } + return record; + } + }; + } + + if (descriptor) { + descriptor.enumerable = def.enumerable === undefined ? false : def.enumerable; + if (def.get) { + var origGet = descriptor.get; + descriptor.get = function () { + var _this3 = this; + + return def.get(def, this, function () { + for (var _len = arguments.length, args = Array(_len), _key2 = 0; _key2 < _len; _key2++) { + args[_key2] = arguments[_key2]; + } + + return origGet.apply(_this3, args); + }); + }; + } + if (def.set) { + var origSet = descriptor.set; + descriptor.set = function (related) { + var _this4 = this; + + return def.set(def, this, related, function (value) { + return origSet.call(_this4, value === undefined ? related : value); + }); + }; + } + Object.defineProperty(mapper.recordClass.prototype, localField, descriptor); + } + }); + + return mapper; + }, + destroy: function destroy(name, id, opts) { + var _this5 = this; + + opts || (opts = {}); + return SimpleStore$1.prototype.destroy.call(this, name, id, opts).then(function (result) { + var record = void 0; + if (opts.raw) { + record = result.data; + } else { + record = result; + } + + if (record && _this5.unlinkOnDestroy) { + var _opts = utils.plainCopy(opts); + _opts.withAll = true; + utils.forEachRelation(_this5.getMapper(name), _opts, function (def) { + utils.set(record, def.localField, undefined); + }); + } + return result; + }); + }, + destroyAll: function destroyAll(name, query, opts) { + var _this6 = this; + + opts || (opts = {}); + return SimpleStore$1.prototype.destroyAll.call(this, name, query, opts).then(function (result) { + var records = void 0; + if (opts.raw) { + records = result.data; + } else { + records = result; + } + + if (records && records.length && _this6.unlinkOnDestroy) { + var _opts = utils.plainCopy(opts); + _opts.withAll = true; + utils.forEachRelation(_this6.getMapper(name), _opts, function (def) { + records.forEach(function (record) { + utils.set(record, def.localField, undefined); + }); + }); + } + return result; + }); + } +}; + +var DataStore$1 = SimpleStore$1.extend(props$1); + +/** + * Create a subclass of this DataStore: + * @example DataStore.extend + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomDataStoreClass extends DataStore { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customDataStore = new CustomDataStoreClass(); + * console.log(customDataStore.foo()); + * console.log(CustomDataStoreClass.beep()); + * + * // Extend the class using alternate method. + * const OtherDataStoreClass = DataStore.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherDataStore = new OtherDataStoreClass(); + * console.log(otherDataStore.foo()); + * console.log(OtherDataStoreClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherDataStoreClass () { + * DataStore.call(this); + * this.created_at = new Date().getTime(); + * } + * DataStore.extend({ + * constructor: AnotherDataStoreClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const anotherDataStore = new AnotherDataStoreClass(); + * console.log(anotherDataStore.created_at); + * console.log(anotherDataStore.foo()); + * console.log(AnotherDataStoreClass.beep()); + * + * @method DataStore.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this DataStore class. + * @since 3.0.0 + */ + +/** + * Registered as `js-data` in NPM and Bower. + * + * Also available from CDN.JS and JSDelivr. + * + * @module js-data + * + * @example Install from NPM + * npm i --save js-data@beta + * @example Install from Bower + * bower i --save js-data@3.0.0-beta.1 + * @example Install from CDN.JS + * + * @example Install from JSDelivr + * + * @example Load into your app via script tag + * + * + * @example Load into your app via CommonJS + * var JSData = require('js-data'); + * @example Load into your app via ES2015 Modules + * import * as JSData from 'js-data'; + * @example Load into your app via AMD + * define('myApp', ['js-data'], function (JSData) { ... }); + */ + +/** + * JSData's utility methods. + * + * @example + * import { utils } from 'js-data'; + * console.log(utils.isString('foo')); // true + * + * @name module:js-data.utils + * @property {Function} Promise See {@link utils.Promise}. + * @see utils + * @since 3.0.0 + * @type {Object} + */ +/** + * JSData's {@link Collection} class. + * + * @example + * import { Collection } from 'js-data'; + * const collection = new Collection(); + * + * @name module:js-data.Collection + * @see Collection + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#collection","Components of JSData: Collection"] + * @type {Constructor} + */ +/** + * JSData's {@link Component} class. Most components in JSData extend this + * class. + * + * @example + * import { Component } from 'js-data'; + * // Make a custom component. + * const MyComponent = Component.extend({ + * myMethod (someArg) { ... } + * }); + * + * @name module:js-data.Component + * @see Component + * @since 3.0.0 + * @type {Constructor} + */ +/** + * JSData's {@link Container} class. Defines and manages {@link Mapper}s. Used + * in Node.js and in the browser, though in the browser you may want to use + * {@link DataStore} instead. + * + * @example + * import { Container } from 'js-data'; + * const store = new Container(); + * + * @name module:js-data.Container + * @see Container + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#container","Components of JSData: Container"] + * @type {Constructor} + */ +/** + * JSData's {@link DataStore} class. Primarily for use in the browser. In + * Node.js you probably want to use {@link Container} instead. + * + * @example + * import { DataStore } from 'js-data'; + * const store = new DataStore(); + * + * @name module:js-data.DataStore + * @see DataStore + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#datastore","Components of JSData: DataStore"] + * @type {Constructor} + */ +/** + * JSData's {@link Index} class, based on [mindex]{@link https://github.com/internalfx/mindex}. + * + * @name module:js-data.Index + * @see Index + * @since 3.0.0 + * @type {Constructor} + */ +/** + * JSData's {@link LinkedCollection} class. Used by the {@link DataStore} + * component. If you need to create a collection manually, you should probably + * use the {@link Collection} class. + * + * @name module:js-data.LinkedCollection + * @see DataStore + * @see LinkedCollection + * @since 3.0.0 + * @type {Constructor} + */ +/** + * JSData's {@link Mapper} class. The core of the ORM. + * + * @example Recommended use + * import { Container } from 'js-data'; + * const store = new Container(); + * store.defineMapper('user'); + * + * @example Create Mapper manually + * import { Mapper } from 'js-data'; + * const UserMapper = new Mapper({ name: 'user' }); + * + * @name module:js-data.Mapper + * @see Container + * @see Mapper + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/modeling-your-data","Modeling your data"] + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#mapper","Components of JSData: Mapper"] + * @type {Constructor} + */ +/** + * JSData's {@link Query} class. Used by the {@link Collection} component. + * + * @name module:js-data.Query + * @see Query + * @since 3.0.0 + * @type {Constructor} + */ +/** + * JSData's {@link Record} class. + * + * @example + * import { Container } from 'js-data'; + * const store = new Container(); + * store.defineMapper('user'); + * const user = store.createRecord('user'); + * + * @name module:js-data.Record + * @see Record + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#record","Components of JSData: Record"] + * @type {Constructor} + */ +/** + * JSData's {@link Schema} class. Implements http://json-schema.org/draft-04. + * + * @example + * import { Container, Schema } from 'js-data'; + * const userSchema = new Schema({ + * properties: { + * id: { type: 'string' }, + * name: { type: 'string' } + * } + * }); + * const store = new Container(); + * store.defineMapper('user', { + * schema: userSchema + * }); + * + * @name module:js-data.Schema + * @see Schema + * @see http://json-schema.org/ + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#schema","Components of JSData: schema"] + * @tutorial ["http://www.js-data.io/v3.0/docs/schemas","JSData's Schema Syntax"] + * @type {Constructor} + */ +/** + * JSData's {@link Settable} class. + * + * @example + * import { Settable } from 'js-data'; + * const obj = new Settable(); + * obj.set('secret', 'value'); + * console.log(JSON.stringify(obj)); // {} + * + * @name module:js-data.Settable + * @see Settable + * @since 3.0.0 + * @type {Constructor} + */ +/** + * JSData's {@link SimpleStore} class. Primarily for use in the browser. In + * Node.js you probably want to use {@link Container} instead. + * + * @example + * import { SimpleStore } from 'js-data'; + * const store = new SimpleStore(); + * + * @name module:js-data.SimpleStore + * @see SimpleStore + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#SimpleStore","Components of JSData: SimpleStore"] + * @type {Constructor} + */ +/** + * Describes the version of this `JSData` object. + * + * @example + * console.log(JSData.version.full); // "3.0.0-beta.1" + * + * @name version + * @memberof module:js-data + * @property {string} full The full semver value. + * @property {number} major The major version number. + * @property {number} minor The minor version number. + * @property {number} patch The patch version number. + * @property {(string|boolean)} alpha The alpha version value, otherwise `false` + * if the current version is not alpha. + * @property {(string|boolean)} beta The beta version value, otherwise `false` + * if the current version is not beta. + * @since 2.0.0 + * @type {Object} + */ +var version = { + full: '3.0.2', + major: 3, + minor: 0, + patch: 2 +}; + +export { version, Collection$1 as Collection, Component$1 as Component, Container, DataStore$1 as DataStore, Index, LinkedCollection$1 as LinkedCollection, Mapper$1 as Mapper, Query$1 as Query, Record$1 as Record, Schema$1 as Schema, Settable, SimpleStore$1 as SimpleStore, utils, belongsTo, hasMany, hasOne, belongsToType, hasManyType, hasOneType }; +//# sourceMappingURL=js-data.es2015.js.map diff --git a/dist/js-data.es2015.js.map b/dist/js-data.es2015.js.map new file mode 100644 index 00000000..a74061e6 --- /dev/null +++ b/dist/js-data.es2015.js.map @@ -0,0 +1 @@ +{"version":3,"file":"js-data.es2015.js","sources":["../src/utils.js","../src/Settable.js","../src/Component.js","../src/Query.js","../src/Relation.js","../src/Relation/BelongsTo.js","../src/Relation/HasMany.js","../src/Relation/HasOne.js","../src/relations.js","../src/decorators.js","../src/Record.js","../lib/mindex/_utils.js","../lib/mindex/index.js","../src/Collection.js","../src/Schema.js","../src/Mapper.js","../src/Container.js","../src/SimpleStore.js","../src/LinkedCollection.js","../src/DataStore.js","../src/index.js"],"sourcesContent":["/**\n * Utility methods used by JSData.\n *\n * @example\n * import { utils } from 'js-data';\n * console.log(utils.isString('foo')); // true\n *\n * @namespace utils\n * @type {Object}\n */\n\nconst DOMAIN = 'utils'\n\nconst INFINITY = 1 / 0\nconst MAX_INTEGER = 1.7976931348623157e+308\nconst BOOL_TAG = '[object Boolean]'\nconst DATE_TAG = '[object Date]'\nconst FUNC_TAG = '[object Function]'\nconst NUMBER_TAG = '[object Number]'\nconst OBJECT_TAG = '[object Object]'\nconst REGEXP_TAG = '[object RegExp]'\nconst STRING_TAG = '[object String]'\nconst objToString = Object.prototype.toString\nconst PATH = /^(.+)\\.(.+)$/\n\nconst ERRORS = {\n '400' () { return `expected: ${arguments[0]}, found: ${arguments[2] ? arguments[1] : typeof arguments[1]}` },\n '404' () { return `${arguments[0]} not found` }\n}\n\nconst toInteger = function (value) {\n if (!value) {\n return 0\n }\n // Coerce to number\n value = +value\n if (value === INFINITY || value === -INFINITY) {\n const sign = (value < 0 ? -1 : 1)\n return sign * MAX_INTEGER\n }\n const remainder = value % 1\n return value === value ? (remainder ? value - remainder : value) : 0 // eslint-disable-line\n}\n\nconst toStr = function (value) {\n return objToString.call(value)\n}\n\nconst isPlainObject = function (value) {\n return (!!value && typeof value === 'object' && value.constructor === Object)\n}\n\nconst mkdirP = function (object, path) {\n if (!path) {\n return object\n }\n const parts = path.split('.')\n parts.forEach(function (key) {\n if (!object[key]) {\n object[key] = {}\n }\n object = object[key]\n })\n return object\n}\n\nconst utils = {\n /**\n * Reference to the Promise constructor used by JSData. Defaults to\n * `window.Promise` or `global.Promise`.\n *\n * @example Make JSData use a different `Promise` constructor\n * import Promise from 'bluebird';\n * import { utils } from 'js-data';\n * utils.Promise = Promise;\n *\n * @name utils.Promise\n * @since 3.0.0\n * @type {Function}\n */\n Promise: Promise,\n\n /**\n * Shallow copy properties that meet the following criteria from `src` to\n * `dest`:\n *\n * - own enumerable\n * - not a function\n * - does not start with \"_\"\n *\n * @method utils._\n * @param {object} dest Destination object.\n * @param {object} src Source object.\n * @private\n * @since 3.0.0\n */\n _ (dest, src) {\n utils.forOwn(src, function (value, key) {\n if (key && dest[key] === undefined && !utils.isFunction(value) && key.indexOf('_') !== 0) {\n dest[key] = value\n }\n })\n },\n\n /**\n * Recursively iterates over relations found in `opts.with`.\n *\n * @method utils._forRelation\n * @param {object} opts Configuration options.\n * @param {Relation} def Relation definition.\n * @param {Function} fn Callback function.\n * @param {*} [thisArg] Execution context for the callback function.\n * @private\n * @since 3.0.0\n */\n _forRelation (opts, def, fn, thisArg) {\n const relationName = def.relation\n let containedName = null\n let index\n opts || (opts = {})\n opts.with || (opts.with = [])\n\n if ((index = utils._getIndex(opts.with, relationName)) >= 0) {\n containedName = relationName\n } else if ((index = utils._getIndex(opts.with, def.localField)) >= 0) {\n containedName = def.localField\n }\n\n if (opts.withAll) {\n fn.call(thisArg, def, {})\n return\n } else if (!containedName) {\n return\n }\n let optsCopy = {}\n utils.fillIn(optsCopy, def.getRelation())\n utils.fillIn(optsCopy, opts)\n optsCopy.with = opts.with.slice()\n optsCopy._activeWith = optsCopy.with.splice(index, 1)[0]\n optsCopy.with.forEach(function (relation, i) {\n if (relation && relation.indexOf(containedName) === 0 && relation.length >= containedName.length && relation[containedName.length] === '.') {\n optsCopy.with[i] = relation.substr(containedName.length + 1)\n } else {\n optsCopy.with[i] = ''\n }\n })\n fn.call(thisArg, def, optsCopy)\n },\n\n /**\n * Find the index of a relation in the given list\n *\n * @method utils._getIndex\n * @param {string[]} list List to search.\n * @param {string} relation Relation to find.\n * @private\n * @returns {number}\n */\n _getIndex (list, relation) {\n let index = -1\n list.forEach(function (_relation, i) {\n if (_relation === relation) {\n index = i\n return false\n } else if (utils.isObject(_relation)) {\n if (_relation.relation === relation) {\n index = i\n return false\n }\n }\n })\n return index\n },\n\n /**\n * Define hidden (non-enumerable), writable properties on `target` from the\n * provided `props`.\n *\n * @example\n * import { utils } from 'js-data';\n * function Cat () {}\n * utils.addHiddenPropsToTarget(Cat.prototype, {\n * say () {\n * console.log('meow');\n * }\n * });\n * const cat = new Cat();\n * cat.say(); // \"meow\"\n *\n * @method utils.addHiddenPropsToTarget\n * @param {object} target That to which `props` should be added.\n * @param {object} props Properties to be added to `target`.\n * @since 3.0.0\n */\n addHiddenPropsToTarget (target, props) {\n const map = {}\n Object.keys(props).forEach(function (propName) {\n const descriptor = Object.getOwnPropertyDescriptor(props, propName)\n\n descriptor.enumerable = false\n map[propName] = descriptor\n })\n Object.defineProperties(target, map)\n },\n\n /**\n * Return whether the two objects are deeply different.\n *\n * @example\n * import { utils } from 'js-data';\n * utils.areDifferent({}, {}); // false\n * utils.areDifferent({ a: 1 }, { a: 1 }); // false\n * utils.areDifferent({ foo: 'bar' }, {}); // true\n *\n * @method utils.areDifferent\n * @param {object} a Base object.\n * @param {object} b Comparison object.\n * @param {object} [opts] Configuration options.\n * @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function.\n * @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore.\n * @returns {boolean} Whether the two objects are deeply different.\n * @see utils.diffObjects\n * @since 3.0.0\n */\n areDifferent (newObject, oldObject, opts) {\n opts || (opts = {})\n const diff = utils.diffObjects(newObject, oldObject, opts)\n const diffCount = Object.keys(diff.added).length +\n Object.keys(diff.removed).length +\n Object.keys(diff.changed).length\n return diffCount > 0\n },\n\n /**\n * Verified that the given constructor is being invoked via `new`, as opposed\n * to just being called like a normal function.\n *\n * @example\n * import { utils } from 'js-data';\n * function Cat () {\n * utils.classCallCheck(this, Cat);\n * }\n * const cat = new Cat(); // this is ok\n * Cat(); // this throws an error\n *\n * @method utils.classCallCheck\n * @param {*} instance Instance that is being constructed.\n * @param {Constructor} ctor Constructor function used to construct the\n * instance.\n * @since 3.0.0\n * @throws {Error} Throws an error if the constructor is being improperly\n * invoked.\n */\n classCallCheck (instance, ctor) {\n if (!(instance instanceof ctor)) {\n throw utils.err(`${ctor.name}`)(500, 'Cannot call a class as a function')\n }\n },\n\n /**\n * Deep copy a value.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { foo: { bar: 'baz' } };\n * const b = utils.copy(a);\n * a === b; // false\n * utils.areDifferent(a, b); // false\n *\n * @param {*} from Value to deep copy.\n * @param {*} [to] Destination object for the copy operation.\n * @param {*} [stackFrom] For internal use.\n * @param {*} [stackTo] For internal use.\n * @param {string[]|RegExp[]} [blacklist] List of strings or RegExp of\n * properties to skip.\n * @param {boolean} [plain] Whether to make a plain copy (don't try to use\n * original prototype).\n * @returns {*} Deep copy of `from`.\n * @since 3.0.0\n */\n copy (from, to, stackFrom, stackTo, blacklist, plain) {\n if (!to) {\n to = from\n if (from) {\n if (utils.isArray(from)) {\n to = utils.copy(from, [], stackFrom, stackTo, blacklist, plain)\n } else if (utils.isDate(from)) {\n to = new Date(from.getTime())\n } else if (utils.isRegExp(from)) {\n to = new RegExp(from.source, from.toString().match(/[^/]*$/)[0])\n to.lastIndex = from.lastIndex\n } else if (utils.isObject(from)) {\n if (plain) {\n to = utils.copy(from, {}, stackFrom, stackTo, blacklist, plain)\n } else {\n to = utils.copy(from, Object.create(Object.getPrototypeOf(from)), stackFrom, stackTo, blacklist, plain)\n }\n }\n }\n } else {\n if (from === to) {\n throw utils.err(`${DOMAIN}.copy`)(500, 'Cannot copy! Source and destination are identical.')\n }\n\n stackFrom = stackFrom || []\n stackTo = stackTo || []\n\n if (utils.isObject(from)) {\n let index = stackFrom.indexOf(from)\n if (index !== -1) {\n return stackTo[index]\n }\n\n stackFrom.push(from)\n stackTo.push(to)\n }\n\n let result\n if (utils.isArray(from)) {\n let i\n to.length = 0\n for (i = 0; i < from.length; i++) {\n result = utils.copy(from[i], null, stackFrom, stackTo, blacklist, plain)\n if (utils.isObject(from[i])) {\n stackFrom.push(from[i])\n stackTo.push(result)\n }\n to.push(result)\n }\n } else {\n if (utils.isArray(to)) {\n to.length = 0\n } else {\n utils.forOwn(to, function (value, key) {\n delete to[key]\n })\n }\n for (var key in from) {\n if (from.hasOwnProperty(key)) {\n if (utils.isBlacklisted(key, blacklist)) {\n continue\n }\n result = utils.copy(from[key], null, stackFrom, stackTo, blacklist, plain)\n if (utils.isObject(from[key])) {\n stackFrom.push(from[key])\n stackTo.push(result)\n }\n to[key] = result\n }\n }\n }\n }\n return to\n },\n\n /**\n * Recursively shallow fill in own enumerable properties from `source` to\n * `dest`.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { foo: { bar: 'baz' }, beep: 'boop' };\n * const b = { beep: 'bip' };\n * utils.deepFillIn(b, a);\n * console.log(b); // {\"foo\":{\"bar\":\"baz\"},\"beep\":\"bip\"}\n *\n * @method utils.deepFillIn\n * @param {object} dest The destination object.\n * @param {object} source The source object.\n * @see utils.fillIn\n * @see utils.deepMixIn\n * @since 3.0.0\n */\n deepFillIn (dest, source) {\n if (source) {\n utils.forOwn(source, function (value, key) {\n const existing = dest[key]\n if (isPlainObject(value) && isPlainObject(existing)) {\n utils.deepFillIn(existing, value)\n } else if (!dest.hasOwnProperty(key) || dest[key] === undefined) {\n dest[key] = value\n }\n })\n }\n return dest\n },\n\n /**\n * Recursively shallow copy enumerable properties from `source` to `dest`.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { foo: { bar: 'baz' }, beep: 'boop' };\n * const b = { beep: 'bip' };\n * utils.deepFillIn(b, a);\n * console.log(b); // {\"foo\":{\"bar\":\"baz\"},\"beep\":\"boop\"}\n *\n * @method utils.deepMixIn\n * @param {object} dest The destination object.\n * @param {object} source The source object.\n * @see utils.fillIn\n * @see utils.deepFillIn\n * @since 3.0.0\n */\n deepMixIn (dest, source) {\n if (source) {\n for (var key in source) {\n const value = source[key]\n const existing = dest[key]\n if (isPlainObject(value) && isPlainObject(existing)) {\n utils.deepMixIn(existing, value)\n } else {\n dest[key] = value\n }\n }\n }\n return dest\n },\n\n /**\n * Return a diff of the base object to the comparison object.\n *\n * @example\n * import { utils } from 'js-data';\n * const oldObject = { foo: 'bar', a: 1234 };\n * const newObject = { beep: 'boop', a: 5678 };\n * const diff = utils.diffObjects(oldObject, newObject);\n * console.log(diff.added); // {\"beep\":\"boop\"}\n * console.log(diff.changed); // {\"a\":5678}\n * console.log(diff.removed); // {\"foo\":undefined}\n *\n * @method utils.diffObjects\n * @param {object} newObject Comparison object.\n * @param {object} oldObject Base object.\n * @param {object} [opts] Configuration options.\n * @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function.\n * @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore.\n * @returns {Object} The diff from the base object to the comparison object.\n * @see utils.areDifferent\n * @since 3.0.0\n */\n diffObjects (newObject, oldObject, opts) {\n opts || (opts = {})\n let equalsFn = opts.equalsFn\n let blacklist = opts.ignore\n const diff = {\n added: {},\n changed: {},\n removed: {}\n }\n if (!utils.isFunction(equalsFn)) {\n equalsFn = utils.deepEqual\n }\n\n const newKeys = Object.keys(newObject).filter(function (key) {\n return !utils.isBlacklisted(key, blacklist)\n })\n const oldKeys = Object.keys(oldObject).filter(function (key) {\n return !utils.isBlacklisted(key, blacklist)\n })\n\n // Check for properties that were added or changed\n newKeys.forEach(function (key) {\n const oldValue = oldObject[key]\n const newValue = newObject[key]\n if (equalsFn(oldValue, newValue)) {\n return\n }\n if (oldValue === undefined) {\n diff.added[key] = newValue\n } else {\n diff.changed[key] = newValue\n }\n })\n\n // Check for properties that were removed\n oldKeys.forEach(function (key) {\n const oldValue = oldObject[key]\n const newValue = newObject[key]\n if (newValue === undefined && oldValue !== undefined) {\n diff.removed[key] = undefined\n }\n })\n\n return diff\n },\n\n /**\n * Return whether the two values are equal according to the `==` operator.\n *\n * @example\n * import { utils } from 'js-data';\n * console.log(utils.equal(1,1)); // true\n * console.log(utils.equal(1,'1')); // true\n * console.log(utils.equal(93, 66)); // false\n *\n * @method utils.equal\n * @param {*} a First value in the comparison.\n * @param {*} b Second value in the comparison.\n * @returns {boolean} Whether the two values are equal according to `==`.\n * @since 3.0.0\n */\n equal (a, b) {\n return a == b // eslint-disable-line\n },\n\n /**\n * Produce a factory function for making Error objects with the provided\n * metadata. Used throughout the various js-data components.\n *\n * @example\n * import { utils } from 'js-data';\n * const errorFactory = utils.err('domain', 'target');\n * const error400 = errorFactory(400, 'expected type', 'actual type');\n * console.log(error400); // [Error: [domain:target] expected: expected type, found: string\nhttp://www.js-data.io/v3.0/docs/errors#400]\n * @method utils.err\n * @param {string} domain Namespace.\n * @param {string} target Target.\n * @returns {Function} Factory function.\n * @since 3.0.0\n */\n err (domain, target) {\n return function (code) {\n const prefix = `[${domain}:${target}] `\n let message = ERRORS[code].apply(null, Array.prototype.slice.call(arguments, 1))\n message = `${prefix}${message}\nhttp://www.js-data.io/v3.0/docs/errors#${code}`\n return new Error(message)\n }\n },\n\n /**\n * Add eventing capabilities into the target object.\n *\n * @example\n * import { utils } from 'js-data';\n * const user = { name: 'John' };\n * utils.eventify(user);\n * user.on('foo', () => console.log(arguments));\n * user.emit('foo', 1, 'bar'); // should log to console values (1, \"bar\")\n *\n * @method utils.eventify\n * @param {object} target Target object.\n * @param {Function} [getter] Custom getter for retrieving the object's event\n * listeners.\n * @param {Function} [setter] Custom setter for setting the object's event\n * listeners.\n * @since 3.0.0\n */\n eventify (target, getter, setter) {\n target = target || this\n let _events = {}\n if (!getter && !setter) {\n getter = function () { return _events }\n setter = function (value) { _events = value }\n }\n Object.defineProperties(target, {\n emit: {\n value (...args) {\n const events = getter.call(this) || {}\n const type = args.shift()\n let listeners = events[type] || []\n let i\n for (i = 0; i < listeners.length; i++) {\n listeners[i].f.apply(listeners[i].c, args)\n }\n listeners = events.all || []\n args.unshift(type)\n for (i = 0; i < listeners.length; i++) {\n listeners[i].f.apply(listeners[i].c, args)\n }\n }\n },\n off: {\n value (type, func) {\n const events = getter.call(this)\n const listeners = events[type]\n if (!listeners) {\n setter.call(this, {})\n } else if (func) {\n for (let i = 0; i < listeners.length; i++) {\n if (listeners[i].f === func) {\n listeners.splice(i, 1)\n break\n }\n }\n } else {\n listeners.splice(0, listeners.length)\n }\n }\n },\n on: {\n value (type, func, thisArg) {\n if (!getter.call(this)) {\n setter.call(this, {})\n }\n const events = getter.call(this)\n events[type] = events[type] || []\n events[type].push({\n c: thisArg,\n f: func\n })\n }\n }\n })\n },\n\n /**\n * Used for sublcassing. Invoke this method in the context of a superclass to\n * to produce a subclass based on `props` and `classProps`.\n *\n * @example\n * import { utils } from 'js-data';\n * function Animal () {}\n * Animal.extend = utils.extend;\n * const Cat = Animal.extend({\n * say () {\n * console.log('meow');\n * }\n * });\n * const cat = new Cat();\n * cat instanceof Animal; // true\n * cat instanceof Cat; // true\n * cat.say(); // \"meow\"\n *\n * @method utils.extend\n * @param {object} props Instance properties for the subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to use as the subclass.\n * @param {object} props Static properties for the subclass.\n * @returns {Constructor} A new subclass.\n * @since 3.0.0\n */\n extend (props, classProps) {\n const superClass = this\n let subClass\n\n props || (props = {})\n classProps || (classProps = {})\n\n if (props.hasOwnProperty('constructor')) {\n subClass = props.constructor\n delete props.constructor\n } else {\n subClass = function (...args) {\n utils.classCallCheck(this, subClass)\n superClass.apply(this, args)\n }\n }\n\n // Setup inheritance of instance members\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n configurable: true,\n enumerable: false,\n value: subClass,\n writable: true\n }\n })\n\n const obj = Object\n // Setup inheritance of static members\n if (obj.setPrototypeOf) {\n obj.setPrototypeOf(subClass, superClass)\n } else if (classProps.strictEs6Class) {\n subClass.__proto__ = superClass // eslint-disable-line\n } else {\n utils.forOwn(superClass, function (value, key) {\n subClass[key] = value\n })\n }\n if (!subClass.hasOwnProperty('__super__')) {\n Object.defineProperty(subClass, '__super__', {\n configurable: true,\n value: superClass\n })\n }\n\n utils.addHiddenPropsToTarget(subClass.prototype, props)\n utils.fillIn(subClass, classProps)\n\n return subClass\n },\n\n /**\n * Shallow copy own enumerable properties from `src` to `dest` that are on\n * `src` but are missing from `dest.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { foo: 'bar', beep: 'boop' };\n * const b = { beep: 'bip' };\n * utils.fillIn(b, a);\n * console.log(b); // {\"foo\":\"bar\",\"beep\":\"bip\"}\n *\n * @method utils.fillIn\n * @param {object} dest The destination object.\n * @param {object} source The source object.\n * @see utils.deepFillIn\n * @see utils.deepMixIn\n * @since 3.0.0\n */\n fillIn (dest, src) {\n utils.forOwn(src, function (value, key) {\n if (!dest.hasOwnProperty(key) || dest[key] === undefined) {\n dest[key] = value\n }\n })\n },\n\n /**\n * Find the last index of an item in an array according to the given checker function.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * const john = { name: 'John', age: 20 };\n * const sara = { name: 'Sara', age: 25 };\n * const dan = { name: 'Dan', age: 20 };\n * const users = [john, sara, dan];\n *\n * console.log(utils.findIndex(users, (user) => user.age === 25)); // 1\n * console.log(utils.findIndex(users, (user) => user.age > 19)); // 2\n * console.log(utils.findIndex(users, (user) => user.name === 'John')); // 0\n * console.log(utils.findIndex(users, (user) => user.name === 'Jimmy')); // -1\n *\n * @method utils.findIndex\n * @param {array} array The array to search.\n * @param {Function} fn Checker function.\n * @returns {number} Index if found or -1 if not found.\n * @since 3.0.0\n */\n findIndex (array, fn) {\n let index = -1\n if (!array) {\n return index\n }\n array.forEach(function (record, i) {\n if (fn(record)) {\n index = i\n return false\n }\n })\n return index\n },\n\n /**\n * Recursively iterate over a {@link Mapper}'s relations according to\n * `opts.with`.\n *\n * @method utils.forEachRelation\n * @param {Mapper} mapper Mapper.\n * @param {object} opts Configuration options.\n * @param {Function} fn Callback function.\n * @param {*} thisArg Execution context for the callback function.\n * @since 3.0.0\n */\n forEachRelation (mapper, opts, fn, thisArg) {\n const relationList = mapper.relationList || []\n if (!relationList.length) {\n return\n }\n relationList.forEach(function (def) {\n utils._forRelation(opts, def, fn, thisArg)\n })\n },\n\n /**\n * Iterate over an object's own enumerable properties.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { b: 1, c: 4 };\n * let sum = 0;\n * utils.forOwn(a, function (value, key) {\n * sum += value;\n * });\n * console.log(sum); // 5\n *\n * @method utils.forOwn\n * @param {object} object The object whose properties are to be enumerated.\n * @param {Function} fn Iteration function.\n * @param {object} [thisArg] Content to which to bind `fn`.\n * @since 3.0.0\n */\n forOwn (obj, fn, thisArg) {\n const keys = Object.keys(obj)\n const len = keys.length\n let i\n for (i = 0; i < len; i++) {\n if (fn.call(thisArg, obj[keys[i]], keys[i], obj) === false) {\n break\n }\n }\n },\n\n /**\n * Proxy for `JSON.parse`.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * const a = utils.fromJson('{\"name\" : \"John\"}');\n * console.log(a); // { name: 'John' }\n *\n * @method utils.fromJson\n * @param {string} json JSON to parse.\n * @returns {Object} Parsed object.\n * @see utils.toJson\n * @since 3.0.0\n */\n fromJson (json) {\n return utils.isString(json) ? JSON.parse(json) : json\n },\n\n /**\n * Retrieve the specified property from the given object. Supports retrieving\n * nested properties.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { foo: { bar: 'baz' }, beep: 'boop' };\n * console.log(utils.get(a, 'beep')); // \"boop\"\n * console.log(utils.get(a, 'foo.bar')); // \"baz\"\n *\n * @method utils.get\n * @param {object} object Object from which to retrieve a property's value.\n * @param {string} prop Property to retrieve.\n * @returns {*} Value of the specified property.\n * @see utils.set\n * @since 3.0.0\n */\n 'get': function (object, prop) {\n if (!prop) {\n return\n }\n const parts = prop.split('.')\n const last = parts.pop()\n\n while (prop = parts.shift()) { // eslint-disable-line\n object = object[prop]\n if (object == null) { // eslint-disable-line\n return\n }\n }\n\n return object[last]\n },\n\n /**\n * Return the superclass for the given instance or subclass. If an instance is\n * provided, then finds the parent class of the instance's constructor.\n *\n * @example\n * import { utils } from 'js-data';\n * // using ES2015 classes\n * class Foo {}\n * class Bar extends Foo {}\n * const barInstance = new Bar();\n * let baseType = utils.getSuper(barInstance);\n * console.log(Foo === baseType); // true\n *\n * // using Function constructor with utils.extend\n * function Foo () {}\n * Foo.extend = utils.extend;\n * const Bar = Foo.extend();\n * const barInstance = new Bar();\n * let baseType = utils.getSuper(barInstance);\n * console.log(Foo === baseType); // true\n *\n * @method utils.getSuper\n * @param {Object|Function} instance Instance or constructor.\n * @param {boolean} [isCtor=false] Whether `instance` is a constructor.\n * @returns {Constructor} The superclass (grandparent constructor).\n * @since 3.0.0\n */\n getSuper (instance, isCtor) {\n const ctor = isCtor ? instance : instance.constructor\n if (ctor.hasOwnProperty('__super__')) {\n return ctor.__super__\n }\n return Object.getPrototypeOf(ctor) || ctor.__proto__ // eslint-disable-line\n },\n\n /**\n * Return the intersection of two arrays.\n *\n * @example\n * import { utils } from 'js-data';\n * const arrA = ['green', 'red', 'blue', 'red'];\n * const arrB = ['green', 'yellow', 'red'];\n * const intersected = utils.intersection(arrA, arrB);\n *\n * console.log(intersected); // ['green', 'red'])\n *\n * @method utils.intersection\n * @param {array} array1 First array.\n * @param {array} array2 Second array.\n * @returns {Array} Array of elements common to both arrays.\n * @since 3.0.0\n */\n intersection (array1, array2) {\n if (!array1 || !array2) {\n return []\n }\n const result = []\n let item\n let i\n const len = array1.length\n for (i = 0; i < len; i++) {\n item = array1[i]\n if (result.indexOf(item) !== -1) {\n continue\n }\n if (array2.indexOf(item) !== -1) {\n result.push(item)\n }\n }\n return result\n },\n\n /**\n * Proxy for `Array.isArray`.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = [1,2,3,4,5];\n * const b = { foo: \"bar\" };\n * console.log(utils.isArray(a)); // true\n * console.log(utils.isArray(b)); // false\n *\n * @method utils.isArray\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is an array.\n * @since 3.0.0\n */\n isArray: Array.isArray,\n\n /**\n * Return whether `prop` is matched by any string or regular expression in\n * `blacklist`.\n *\n * @example\n * import { utils } from 'js-data';\n * const blacklist = [/^\\$hashKey/g, /^_/g, 'id'];\n * console.log(utils.isBlacklisted(\"$hashKey\", blacklist)); // true\n * console.log(utils.isBlacklisted(\"id\", blacklist)); // true\n * console.log(utils.isBlacklisted(\"_myProp\", blacklist)); // true\n * console.log(utils.isBlacklisted(\"my_id\", blacklist)); // false\n *\n * @method utils.isBlacklisted\n * @param {string} prop The name of a property to check.\n * @param {array} blacklist Array of strings and regular expressions.\n * @returns {boolean} Whether `prop` was matched.\n * @since 3.0.0\n */\n isBlacklisted (prop, blacklist) {\n if (!blacklist || !blacklist.length) {\n return false\n }\n let matches\n for (var i = 0; i < blacklist.length; i++) {\n if ((toStr(blacklist[i]) === REGEXP_TAG && blacklist[i].test(prop)) || blacklist[i] === prop) {\n matches = prop\n return !!matches\n }\n }\n return !!matches\n },\n\n /**\n * Return whether the provided value is a boolean.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = true;\n * const b = { foo: \"bar\" };\n * console.log(utils.isBoolean(a)); // true\n * console.log(utils.isBoolean(b)); // false\n *\n * @method utils.isBoolean\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is a boolean.\n * @since 3.0.0\n */\n isBoolean (value) {\n return toStr(value) === BOOL_TAG\n },\n\n /**\n * Return whether the provided value is a date.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = new Date();\n * const b = { foo: \"bar\" };\n * console.log(utils.isDate(a)); // true\n * console.log(utils.isDate(b)); // false\n *\n * @method utils.isDate\n * @param {*} value The value to test.\n * @returns {Date} Whether the provided value is a date.\n * @since 3.0.0\n */\n isDate (value) {\n return (value && typeof value === 'object' && toStr(value) === DATE_TAG)\n },\n\n /**\n * Return whether the provided value is a function.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = function () { console.log('foo bar'); };\n * const b = { foo: \"bar\" };\n * console.log(utils.isFunction(a)); // true\n * console.log(utils.isFunction(b)); // false\n *\n * @method utils.isFunction\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is a function.\n * @since 3.0.0\n */\n isFunction (value) {\n return typeof value === 'function' || (value && toStr(value) === FUNC_TAG)\n },\n\n /**\n * Return whether the provided value is an integer.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = 1;\n * const b = 1.25;\n * const c = '1';\n * console.log(utils.isInteger(a)); // true\n * console.log(utils.isInteger(b)); // false\n * console.log(utils.isInteger(c)); // false\n *\n * @method utils.isInteger\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is an integer.\n * @since 3.0.0\n */\n isInteger (value) {\n return toStr(value) === NUMBER_TAG && value == toInteger(value) // eslint-disable-line\n },\n\n /**\n * Return whether the provided value is `null`.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = null;\n * const b = { foo: \"bar\" };\n * console.log(utils.isNull(a)); // true\n * console.log(utils.isNull(b)); // false\n *\n * @method utils.isNull\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is `null`.\n * @since 3.0.0\n */\n isNull (value) {\n return value === null\n },\n\n /**\n * Return whether the provided value is a number.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = 1;\n * const b = -1.25;\n * const c = '1';\n * console.log(utils.isNumber(a)); // true\n * console.log(utils.isNumber(b)); // true\n * console.log(utils.isNumber(c)); // false\n *\n * @method utils.isNumber\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is a number.\n * @since 3.0.0\n */\n isNumber (value) {\n const type = typeof value\n return type === 'number' || (value && type === 'object' && toStr(value) === NUMBER_TAG)\n },\n\n /**\n * Return whether the provided value is an object.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { foo: \"bar\" };\n * const b = 'foo bar';\n * console.log(utils.isObject(a)); // true\n * console.log(utils.isObject(b)); // false\n *\n * @method utils.isObject\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is an object.\n * @since 3.0.0\n */\n isObject (value) {\n return toStr(value) === OBJECT_TAG\n },\n\n /**\n * Return whether the provided value is a regular expression.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = /^\\$.+$/ig;\n * const b = new RegExp('^\\$.+$', 'ig');\n * const c = { foo: \"bar\" };\n * console.log(utils.isRegExp(a)); // true\n * console.log(utils.isRegExp(b)); // true\n * console.log(utils.isRegExp(c)); // false\n *\n * @method utils.isRegExp\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is a regular expression.\n * @since 3.0.0\n */\n isRegExp (value) {\n return toStr(value) === REGEXP_TAG\n },\n\n /**\n * Return whether the provided value is a string or a number.\n *\n * @example\n * import { utils } from 'js-data';\n * console.log(utils.isSorN('')); // true\n * console.log(utils.isSorN(-1.65)); // true\n * console.log(utils.isSorN('my string')); // true\n * console.log(utils.isSorN({})); // false\n * console.log(utils.isSorN([1,2,4])); // false\n *\n * @method utils.isSorN\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is a string or a number.\n * @since 3.0.0\n */\n isSorN (value) {\n return utils.isString(value) || utils.isNumber(value)\n },\n\n /**\n * Return whether the provided value is a string.\n *\n * @example\n * import { utils } from 'js-data';\n * console.log(utils.isString('')); // true\n * console.log(utils.isString('my string')); // true\n * console.log(utils.isString(100)); // false\n * console.log(utils.isString([1,2,4])); // false\n *\n * @method utils.isString\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is a string.\n * @since 3.0.0\n */\n isString (value) {\n return typeof value === 'string' || (value && typeof value === 'object' && toStr(value) === STRING_TAG)\n },\n\n /**\n * Return whether the provided value is a `undefined`.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = undefined;\n * const b = { foo: \"bar\"};\n * console.log(utils.isUndefined(a)); // true\n * console.log(utils.isUndefined(b.baz)); // true\n * console.log(utils.isUndefined(b)); // false\n * console.log(utils.isUndefined(b.foo)); // false\n *\n * @method utils.isUndefined\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is a `undefined`.\n * @since 3.0.0\n */\n isUndefined (value) {\n return value === undefined\n },\n\n /**\n * Mix in logging capabilities to the target.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { foo: \"bar\"};\n *\n * // Add standard logging to an object\n * utils.logify(a);\n * a.log('info', 'test log info'); // output 'test log info' to console.\n *\n * // Toggle debug output of an object\n * a.dbg('test debug output'); // does not output because debug is off.\n * a.debug = true;\n * a.dbg('test debug output'); // output 'test debug output' to console.\n *\n * @method utils.logify\n * @param {*} target The target.\n * @since 3.0.0\n */\n logify (target) {\n utils.addHiddenPropsToTarget(target, {\n dbg (...args) {\n if (utils.isFunction(this.log)) {\n this.log('debug', ...args)\n }\n },\n log (level, ...args) {\n if (level && !args.length) {\n args.push(level)\n level = 'debug'\n }\n if (level === 'debug' && !this.debug) {\n return\n }\n const prefix = `${level.toUpperCase()}: (${this.name || this.constructor.name})`\n if (utils.isFunction(console[level])) {\n console[level](prefix, ...args)\n } else {\n console.log(prefix, ...args)\n }\n }\n })\n },\n\n /**\n * Adds the given record to the provided array only if it's not already in the\n * array.\n *\n * @example\n * import { utils } from 'js-data';\n * const colors = ['red', 'green', 'yellow'];\n *\n * console.log(colors.length); // 3\n * utils.noDupeAdd(colors, 'red');\n * console.log(colors.length); // 3, red already exists\n *\n * utils.noDupeAdd(colors, 'blue');\n * console.log(colors.length); // 4, blue was added\n *\n * @method utils.noDupeAdd\n * @param {array} array The array.\n * @param {*} record The value to add.\n * @param {Function} fn Callback function passed to {@link utils.findIndex}.\n * @since 3.0.0\n */\n noDupeAdd (array, record, fn) {\n if (!array) {\n return\n }\n const index = this.findIndex(array, fn)\n if (index < 0) {\n array.push(record)\n }\n },\n\n /**\n * Return a shallow copy of the provided object, minus the properties\n * specified in `keys`.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { name: 'John', $hashKey: 1214910 };\n *\n * let b = utils.omit(a, ['$hashKey']);\n * console.log(b); // { name: 'John' }\n *\n * @method utils.omit\n * @param {object} props The object to copy.\n * @param {string[]} keys Array of strings, representing properties to skip.\n * @returns {Object} Shallow copy of `props`, minus `keys`.\n * @since 3.0.0\n */\n omit (props, keys) {\n const _props = {}\n utils.forOwn(props, function (value, key) {\n if (keys.indexOf(key) === -1) {\n _props[key] = value\n }\n })\n return _props\n },\n\n /**\n * Return a shallow copy of the provided object, but only include the\n * properties specified in `keys`.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { name: 'John', $hashKey: 1214910 };\n *\n * let b = utils.pick(a, ['$hashKey']);\n * console.log(b); // { $hashKey: 1214910 }\n *\n * @method utils.pick\n * @param {object} props The object to copy.\n * @param {string[]} keys Array of strings, representing properties to keep.\n * @returns {Object} Shallow copy of `props`, but only including `keys`.\n * @since 3.0.0\n */\n pick (props, keys) {\n return keys.reduce((map, key) => {\n map[key] = props[key]\n return map\n }, {})\n },\n\n /**\n * Return a plain copy of the given value.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { name: 'John' };\n * let b = utils.plainCopy(a);\n * console.log(a === b); // false\n *\n * @method utils.plainCopy\n * @param {*} value The value to copy.\n * @returns {*} Plain copy of `value`.\n * @see utils.copy\n * @since 3.0.0\n */\n plainCopy (value) {\n return utils.copy(value, undefined, undefined, undefined, undefined, true)\n },\n\n /**\n * Shortcut for `utils.Promise.reject(value)`.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * utils.reject(\"Testing static reject\").then(function (data) {\n * // not called\n * }).catch(function (reason) {\n * console.log(reason); // \"Testing static reject\"\n * });\n *\n * @method utils.reject\n * @param {*} [value] Value with which to reject the Promise.\n * @returns {Promise} Promise reject with `value`.\n * @see utils.Promise\n * @since 3.0.0\n */\n reject (value) {\n return utils.Promise.reject(value)\n },\n\n /**\n * Remove the last item found in array according to the given checker function.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * const colors = ['red', 'green', 'yellow', 'red'];\n * utils.remove(colors, (color) => color === 'red');\n * console.log(colors); // ['red', 'green', 'yellow']\n *\n * @method utils.remove\n * @param {array} array The array to search.\n * @param {Function} fn Checker function.\n */\n remove (array, fn) {\n if (!array || !array.length) {\n return\n }\n const index = this.findIndex(array, fn)\n if (index >= 0) {\n array.splice(index, 1) // todo should this be recursive?\n }\n },\n\n /**\n * Shortcut for `utils.Promise.resolve(value)`.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * utils.resolve(\"Testing static resolve\").then(function (data) {\n * console.log(data); // \"Testing static resolve\"\n * }).catch(function (reason) {\n * // not called\n * });\n *\n * @param {*} [value] Value with which to resolve the Promise.\n * @returns {Promise} Promise resolved with `value`.\n * @see utils.Promise\n * @since 3.0.0\n */\n resolve (value) {\n return utils.Promise.resolve(value)\n },\n\n /**\n * Set the value at the provided key or path.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * const john = {\n * name: 'John',\n * age: 25,\n * parent: {\n * name: 'John's Mom',\n * age: 50\n * }\n * };\n * // set value by key\n * utils.set(john, 'id', 98);\n * console.log(john.id); // 98\n *\n * // set value by path\n * utils.set(john, 'parent.id', 20);\n * console.log(john.parent.id); // 20\n *\n * // set value by path/value map\n * utils.set(john, {\n * 'id': 1098,\n * 'parent': { id: 1020 },\n * 'parent.age': '55'\n * });\n * console.log(john.id); // 1098\n * console.log(john.parent.id); // 1020\n * console.log(john.parent.age); // 55\n *\n * @method utils.set\n * @param {object} object The object on which to set a property.\n * @param {(string|Object)} path The key or path to the property. Can also\n * pass in an object of path/value pairs, which will all be set on the target\n * object.\n * @param {*} [value] The value to set.\n */\n set: function (object, path, value) {\n if (utils.isObject(path)) {\n utils.forOwn(path, function (value, _path) {\n utils.set(object, _path, value)\n })\n } else {\n const parts = PATH.exec(path)\n if (parts) {\n mkdirP(object, parts[1])[parts[2]] = value\n } else {\n object[path] = value\n }\n }\n },\n\n /**\n * Check whether the two provided objects are deeply equal.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * const objA = {\n * name: 'John',\n * id: 27,\n * nested: {\n * item: 'item 1',\n * colors: ['red', 'green', 'blue']\n * }\n * };\n *\n * const objB = {\n * name: 'John',\n * id: 27,\n * nested: {\n * item: 'item 1',\n * colors: ['red', 'green', 'blue']\n * }\n * };\n *\n * console.log(utils.deepEqual(a,b)); // true\n * objB.nested.colors.add('yellow'); // make a change to a nested object's array\n * console.log(utils.deepEqual(a,b)); // false\n *\n * @method utils.deepEqual\n * @param {object} a First object in the comparison.\n * @param {object} b Second object in the comparison.\n * @returns {boolean} Whether the two provided objects are deeply equal.\n * @see utils.equal\n * @since 3.0.0\n */\n deepEqual (a, b) {\n if (a === b) {\n return true\n }\n let _equal = true\n if (utils.isArray(a) && utils.isArray(b)) {\n if (a.length !== b.length) {\n return false\n }\n for (let i = a.length; i--;) {\n if (!utils.deepEqual(a[i], b[i])) {\n // Exit loop early\n return false\n }\n }\n } else if (utils.isObject(a) && utils.isObject(b)) {\n utils.forOwn(a, function (value, key) {\n if (!(_equal = utils.deepEqual(value, b[key]))) {\n // Exit loop early\n return false\n }\n })\n if (_equal) {\n utils.forOwn(b, function (value, key) {\n if (!(_equal = utils.deepEqual(value, a[key]))) {\n // Exit loop early\n return false\n }\n })\n }\n } else {\n return false\n }\n return _equal\n },\n\n /**\n * Proxy for `JSON.stringify`.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * const a = { name: 'John' };\n * let jsonVal = utils.toJson(a);\n * console.log(jsonVal); // '{\"name\" : \"John\"}'\n *\n * @method utils.toJson\n * @param {*} value Value to serialize to JSON.\n * @returns {string} JSON string.\n * @see utils.fromJson\n * @since 3.0.0\n */\n toJson: JSON.stringify,\n\n /**\n * Unset the value at the provided key or path.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * const john = {\n * name: 'John',\n * age: 25,\n * parent: {\n * name: 'John's Mom',\n * age: 50\n * }\n * };\n *\n * utils.unset(john, age);\n * utils.unset(john, parent.age);\n *\n * console.log(john.age); // null\n * console.log(john.parent.age); // null\n *\n * @method utils.unset\n * @param {object} object The object from which to delete the property.\n * @param {string} path The key or path to the property.\n * @see utils.set\n * @since 3.0.0\n */\n unset (object, path) {\n const parts = path.split('.')\n const last = parts.pop()\n\n while (path = parts.shift()) { // eslint-disable-line\n object = object[path]\n if (object == null) { // eslint-disable-line\n return\n }\n }\n\n object[last] = undefined\n }\n}\n\nexport const safeSetProp = function (record, field, value) {\n if (record && record._set) {\n record._set(`props.${field}`, value)\n } else {\n utils.set(record, field, value)\n }\n}\n\nexport const safeSetLink = function (record, field, value) {\n if (record && record._set) {\n record._set(`links.${field}`, value)\n } else {\n utils.set(record, field, value)\n }\n}\n\nexport default utils\n","import utils from './utils'\n\n/**\n * A base class which gives instances private properties.\n *\n * Typically you won't instantiate this class directly, but you may find it\n * useful as an abstract class for your own components.\n *\n * See {@link Settable.extend} for an example of using {@link Settable} as a\n * base class.\n *\n *```javascript\n * import {Settable} from 'js-data'\n * ```\n *\n * @class Settable\n * @returns {Settable} A new {@link Settable} instance.\n * @since 3.0.0\n */\nexport default function Settable () {\n const _props = {}\n Object.defineProperties(this, {\n /**\n * Get a private property of this instance.\n *\n * __Don't use the method unless you know what you're doing.__\n *\n * @method Settable#_get\n * @param {string} key The property to retrieve.\n * @returns {*} The value of the property.\n * @since 3.0.0\n */\n _get: { value (key) { return utils.get(_props, key) } },\n\n /**\n * Set a private property of this instance.\n *\n * __Don't use the method unless you know what you're doing.__\n *\n * @method __Don't use the method unless you know what you're doing.__#_set\n * @param {(string|Object)} key The key or path to the property. Can also\n * pass in an object of key/value pairs, which will all be set on the instance.\n * @param {*} [value] The value to set.\n * @since 3.0.0\n */\n _set: { value (key, value) { return utils.set(_props, key, value) } },\n\n /**\n * Unset a private property of this instance.\n *\n * __Don't use the method unless you know what you're doing.__\n *\n * @method __Don't use the method unless you know what you're doing.__#_unset\n * @param {string} key The property to unset.\n * @since 3.0.0\n */\n _unset: { value (key) { return utils.unset(_props, key) } }\n })\n}\n\n/**\n * Create a subclass of this Settable:\n *\n * @example Settable.extend\n * const JSData = require('js-data');\n * const { Settable } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomSettableClass extends Settable {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customSettable = new CustomSettableClass();\n * console.log(customSettable.foo());\n * console.log(CustomSettableClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherSettableClass = Settable.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherSettable = new OtherSettableClass();\n * console.log(otherSettable.foo());\n * console.log(OtherSettableClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherSettableClass () {\n * Settable.call(this);\n * this.created_at = new Date().getTime();\n * }\n * Settable.extend({\n * constructor: AnotherSettableClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * })\n * const anotherSettable = new AnotherSettableClass();\n * console.log(anotherSettable.created_at);\n * console.log(anotherSettable.foo());\n * console.log(AnotherSettableClass.beep());\n *\n * @method Settable.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this Settable class.\n * @since 3.0.0\n */\nSettable.extend = utils.extend\n","import utils from './utils'\nimport Settable from './Settable'\n\n/**\n * The base class from which all JSData components inherit some basic\n * functionality.\n *\n * Typically you won't instantiate this class directly, but you may find it\n * useful as an abstract class for your own components.\n *\n * See {@link Component.extend} for an example of using {@link Component} as a\n * base class.\n *\n *```javascript\n * import {Component} from 'js-data'\n * ```\n *\n * @class Component\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.debug=false] See {@link Component#debug}.\n * @returns {Component} A new {@link Component} instance.\n * @since 3.0.0\n */\nfunction Component (opts) {\n Settable.call(this)\n opts || (opts = {})\n\n /**\n * Whether to enable debug-level logs for this component. Anything that\n * extends `Component` inherits this option and the corresponding logging\n * functionality.\n *\n * @example Component#debug\n * const JSData = require('js-data');\n * const { Component } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const component = new Component();\n * component.log('debug', 'some message'); // nothing gets logged\n * // Display debug logs:\n * component.debug = true;\n * component.log('debug', 'other message'); // this DOES get logged\n *\n * @default false\n * @name Component#debug\n * @since 3.0.0\n * @type {boolean}\n */\n this.debug = opts.hasOwnProperty('debug') ? !!opts.debug : false\n\n /**\n * Event listeners attached to this Component. __Do not modify.__ Use\n * {@link Component#on} and {@link Component#off} instead.\n *\n * @name Component#_listeners\n * @private\n * @instance\n * @since 3.0.0\n * @type {Object}\n */\n Object.defineProperty(this, '_listeners', { value: {}, writable: true })\n}\n\nexport default Settable.extend({\n constructor: Component\n})\n\n/**\n * Create a subclass of this Component:\n *\n * @example Component.extend\n * const JSData = require('js-data');\n * const { Component } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomComponentClass extends Component {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customComponent = new CustomComponentClass();\n * console.log(customComponent.foo());\n * console.log(CustomComponentClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherComponentClass = Component.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherComponent = new OtherComponentClass();\n * console.log(otherComponent.foo());\n * console.log(OtherComponentClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherComponentClass () {\n * Component.call(this);\n * this.created_at = new Date().getTime();\n * }\n * Component.extend({\n * constructor: AnotherComponentClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * })\n * const anotherComponent = new AnotherComponentClass();\n * console.log(anotherComponent.created_at);\n * console.log(anotherComponent.foo());\n * console.log(AnotherComponentClass.beep());\n *\n * @method Component.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this Component class.\n * @since 3.0.0\n */\nComponent.extend = utils.extend\n\n/**\n * Log the provided values at the \"debug\" level. Debug-level logs are only\n * logged if {@link Component#debug} is `true`.\n *\n * `.dbg(...)` is shorthand for `.log('debug', ...)`.\n *\n * @method Component#dbg\n * @param {...*} [args] Values to log.\n * @since 3.0.0\n */\n/**\n * Log the provided values. By default sends values to `console[level]`.\n * Debug-level logs are only logged if {@link Component#debug} is `true`.\n *\n * Will attempt to use appropriate `console` methods if they are available.\n *\n * @method Component#log\n * @param {string} level Log level.\n * @param {...*} [args] Values to log.\n * @since 3.0.0\n */\nutils.logify(Component.prototype)\n\n/**\n * Register a new event listener on this Component.\n *\n * @example\n * // Listen for all \"afterCreate\" events in a DataStore\n * store.on('afterCreate', (mapperName, props, opts, result) => {\n * console.log(mapperName); // \"post\"\n * console.log(props.id); // undefined\n * console.log(result.id); // 1234\n * });\n * store.create('post', { title: 'Modeling your data' }).then((post) => {\n * console.log(post.id); // 1234\n * });\n *\n * @example\n * // Listen for the \"add\" event on a collection\n * collection.on('add', (records) => {\n * console.log(records); // [...]\n * });\n *\n * @example\n * // Listen for \"change\" events on a record\n * post.on('change', (record, changes) => {\n * console.log(changes); // { changed: { title: 'Modeling your data' } }\n * });\n * post.title = 'Modeling your data';\n *\n * @method Component#on\n * @param {string} event Name of event to subsribe to.\n * @param {Function} listener Listener function to handle the event.\n * @param {*} [ctx] Optional content in which to invoke the listener.\n * @since 3.0.0\n */\n/**\n * Remove an event listener from this Component. If no listener is provided,\n * then all listeners for the specified event will be removed. If no event is\n * specified then all listeners for all events will be removed.\n *\n * @example\n * // Remove a particular listener for a particular event\n * collection.off('add', handler);\n *\n * @example\n * // Remove all listeners for a particular event\n * record.off('change');\n *\n * @example\n * // Remove all listeners to all events\n * store.off();\n *\n * @method Component#off\n * @param {string} [event] Name of event to unsubsribe to.\n * @param {Function} [listener] Listener to remove.\n * @since 3.0.0\n */\n/**\n * Trigger an event on this Component.\n *\n * @example Component#emit\n * // import { Collection, DataStore } from 'js-data';\n * const JSData = require('js-data');\n * const { Collection, DataStore } = JSData;\n *\n * const collection = new Collection();\n * collection.on('foo', function (msg) {\n * console.log(msg);\n * });\n * collection.emit('foo', 'bar');\n *\n * const store = new DataStore();\n * store.on('beep', function (msg) {\n * console.log(msg);\n * });\n * store.emit('beep', 'boop');\n *\n * @method Component#emit\n * @param {string} event Name of event to emit.\n * @param {...*} [args] Arguments to pass to any listeners.\n * @since 3.0.0\n */\nutils.eventify(\n Component.prototype,\n function () {\n return this._listeners\n },\n function (value) {\n this._listeners = value\n }\n)\n","import utils from './utils'\nimport Component from './Component'\n\nconst DOMAIN = 'Query'\nconst INDEX_ERR = 'Index inaccessible after first operation'\n\n// Reserved words used by JSData's Query Syntax\nconst reserved = {\n limit: '',\n offset: '',\n orderBy: '',\n skip: '',\n sort: '',\n where: ''\n}\n\n// Used by our JavaScript implementation of the LIKE operator\nconst escapeRegExp = /([.*+?^=!:${}()|[\\]/\\\\])/g\nconst percentRegExp = /%/g\nconst underscoreRegExp = /_/g\nconst escape = function (pattern) {\n return pattern.replace(escapeRegExp, '\\\\$1')\n}\n\n/**\n * A class used by the {@link Collection} class to build queries to be executed\n * against the collection's data. An instance of `Query` is returned by\n * {@link Collection#query}. Query instances are typically short-lived, and you\n * shouldn't have to create them yourself. Just use {@link Collection#query}.\n *\n * ```javascript\n * import { Query } from 'js-data';\n * ```\n *\n * @example Query intro\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'draft', id: 2 },\n * { author: 'Mike', age: 32, status: 'draft', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'draft', id: 5 }\n * ]\n * store.add('post', posts);\n * const drafts = store.query('post').filter({ status: 'draft' }).limit(2).run();\n * console.log(drafts);\n *\n * @class Query\n * @extends Component\n * @param {Collection} collection The collection on which this query operates.\n * @since 3.0.0\n */\nfunction Query (collection) {\n utils.classCallCheck(this, Query)\n\n /**\n * The {@link Collection} on which this query operates.\n *\n * @name Query#collection\n * @since 3.0.0\n * @type {Collection}\n */\n this.collection = collection\n\n /**\n * The current data result of this query.\n *\n * @name Query#data\n * @since 3.0.0\n * @type {Array}\n */\n this.data = null\n}\n\nexport default Component.extend({\n constructor: Query,\n\n _applyWhereFromObject (where) {\n const fields = []\n const ops = []\n const predicates = []\n utils.forOwn(where, (clause, field) => {\n if (!utils.isObject(clause)) {\n clause = {\n '==': clause\n }\n }\n utils.forOwn(clause, (expr, op) => {\n fields.push(field)\n ops.push(op)\n predicates.push(expr)\n })\n })\n return {\n fields,\n ops,\n predicates\n }\n },\n\n _applyWhereFromArray (where) {\n const groups = []\n where.forEach((_where, i) => {\n if (utils.isString(_where)) {\n return\n }\n const prev = where[i - 1]\n const parser = utils.isArray(_where) ? this._applyWhereFromArray : this._applyWhereFromObject\n const group = parser.call(this, _where)\n if (prev === 'or') {\n group.isOr = true\n }\n groups.push(group)\n })\n groups.isArray = true\n return groups\n },\n\n _testObjectGroup (keep, first, group, item) {\n let i\n const fields = group.fields\n const ops = group.ops\n const predicates = group.predicates\n const len = ops.length\n for (i = 0; i < len; i++) {\n let op = ops[i]\n const isOr = op.charAt(0) === '|'\n op = isOr ? op.substr(1) : op\n const expr = this.evaluate(utils.get(item, fields[i]), op, predicates[i])\n if (expr !== undefined) {\n keep = first ? expr : (isOr ? keep || expr : keep && expr)\n }\n first = false\n }\n return { keep, first }\n },\n\n _testArrayGroup (keep, first, groups, item) {\n let i\n const len = groups.length\n for (i = 0; i < len; i++) {\n const group = groups[i]\n const parser = group.isArray ? this._testArrayGroup : this._testObjectGroup\n const result = parser.call(this, true, true, group, item)\n if (groups[i - 1]) {\n if (group.isOr) {\n keep = keep || result.keep\n } else {\n keep = keep && result.keep\n }\n } else {\n keep = result.keep\n }\n first = result.first\n }\n return { keep, first }\n },\n\n /**\n * Find all entities between two boundaries.\n *\n * @example Get the users ages 18 to 30.\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('user');\n * const users = [\n * { name: 'Peter', age: 25, id: 1 },\n * { name: 'Jim', age: 19, id: 2 },\n * { name: 'Mike', age: 17, id: 3 },\n * { name: 'Alan', age: 29, id: 4 },\n * { name: 'Katie', age: 33, id: 5 }\n * ];\n * store.add('user', users)\n * const filteredUsers = store\n * .query('user')\n * .between(18, 30, { index: 'age' })\n * .run();\n * console.log(filteredUsers);\n *\n * @example Same as above.\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('user');\n * const users = [\n * { name: 'Peter', age: 25, id: 1 },\n * { name: 'Jim', age: 19, id: 2 },\n * { name: 'Mike', age: 17, id: 3 },\n * { name: 'Alan', age: 29, id: 4 },\n * { name: 'Katie', age: 33, id: 5 }\n * ];\n * store.add('user', users)\n * const filteredUsers = store\n * .query('user')\n * .between([18], [30], { index: 'age' })\n * .run();\n * console.log(filteredUsers);\n *\n * @method Query#between\n * @param {array} leftKeys Keys defining the left boundary.\n * @param {array} rightKeys Keys defining the right boundary.\n * @param {object} [opts] Configuration options.\n * @param {string} [opts.index] Name of the secondary index to use in the\n * query. If no index is specified, the main index is used.\n * @param {boolean} [opts.leftInclusive=true] Whether to include entities\n * on the left boundary.\n * @param {boolean} [opts.rightInclusive=false] Whether to include entities\n * on the left boundary.\n * @param {boolean} [opts.limit] Limit the result to a certain number.\n * @param {boolean} [opts.offset] The number of resulting entities to skip.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n between (leftKeys, rightKeys, opts) {\n opts || (opts = {})\n if (this.data) {\n throw utils.err(`${DOMAIN}#between`)(500, 'Cannot access index')\n }\n this.data = this.collection.getIndex(opts.index).between(leftKeys, rightKeys, opts)\n return this\n },\n\n /**\n * The comparison function used by the {@link Query} class.\n *\n * @method Query#compare\n * @param {array} orderBy An orderBy clause used for sorting and sub-sorting.\n * @param {number} index The index of the current orderBy clause being used.\n * @param {*} a The first item in the comparison.\n * @param {*} b The second item in the comparison.\n * @returns {number} -1 if `b` should preceed `a`. 0 if `a` and `b` are equal.\n * 1 if `a` should preceed `b`.\n * @since 3.0.0\n */\n compare (orderBy, index, a, b) {\n const def = orderBy[index]\n let cA = utils.get(a, def[0])\n let cB = utils.get(b, def[0])\n if (cA && utils.isString(cA)) {\n cA = cA.toUpperCase()\n }\n if (cB && utils.isString(cB)) {\n cB = cB.toUpperCase()\n }\n if (a === undefined) {\n a = null\n }\n if (b === undefined) {\n b = null\n }\n if (def[1].toUpperCase() === 'DESC') {\n const temp = cB\n cB = cA\n cA = temp\n }\n if (cA < cB) {\n return -1\n } else if (cA > cB) {\n return 1\n } else {\n if (index < orderBy.length - 1) {\n return this.compare(orderBy, index + 1, a, b)\n } else {\n return 0\n }\n }\n },\n\n /**\n * Predicate evaluation function used by the {@link Query} class.\n *\n * @method Query#evaluate\n * @param {*} value The value to evaluate.\n * @param {string} op The operator to use in this evaluation.\n * @param {*} predicate The predicate to use in this evaluation.\n * @returns {boolean} Whether the value passed the evaluation or not.\n * @since 3.0.0\n */\n evaluate (value, op, predicate) {\n const ops = this.constructor.ops\n if (ops[op]) {\n return ops[op](value, predicate)\n }\n if (op.indexOf('like') === 0) {\n return this.like(predicate, op.substr(4)).exec(value) !== null\n } else if (op.indexOf('notLike') === 0) {\n return this.like(predicate, op.substr(7)).exec(value) === null\n }\n },\n\n /**\n * Find the record or records that match the provided query or are accepted by\n * the provided filter function.\n *\n * @example Get the draft posts by authors younger than 30\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post')\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'published', id: 2 },\n * { author: 'Mike', age: 32, status: 'draft', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'published', id: 5 }\n * { author: 'Peter', age: 25, status: 'deleted', id: 6 },\n * { author: 'Sally', age: 21, status: 'draft', id: 7 },\n * { author: 'Jim', age: 27, status: 'draft', id: 8 },\n * { author: 'Jim', age: 27, status: 'published', id: 9 },\n * { author: 'Jason', age: 55, status: 'published', id: 10 }\n * ];\n * store.add('post', posts);\n * const results = store\n * .query('post')\n * .filter({\n * where: {\n * status: {\n * '==': 'draft'\n * },\n * age: {\n * '<': 30\n * }\n * }\n * })\n * .run();\n * console.log(results);\n *\n * @example Use a custom filter function\n * const posts = query\n * .filter(function (post) {\n * return post.isReady();\n * })\n * .run();\n *\n * @method Query#filter\n * @param {(Object|Function)} [queryOrFn={}] Selection query or filter\n * function.\n * @param {Function} [thisArg] Context to which to bind `queryOrFn` if\n * `queryOrFn` is a function.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n filter (query, thisArg) {\n /**\n * Selection query as defined by JSData's [Query Syntax][querysyntax].\n *\n * [querysyntax]: http://www.js-data.io/v3.0/docs/query-syntax\n *\n * @example Empty \"findAll\" query\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post')\n * store.findAll('post').then((posts) => {\n * console.log(posts); // [...]\n * });\n *\n * @example Empty \"filter\" query\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n * const posts = store.filter('post');\n * console.log(posts); // [...]\n *\n * @example Complex \"filter\" query\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * const PAGE_SIZE = 2;\n * let currentPage = 3;\n *\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'published', id: 2 },\n * { author: 'Mike', age: 32, status: 'draft', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'published', id: 5 }\n * { author: 'Peter', age: 25, status: 'deleted', id: 6 },\n * { author: 'Sally', age: 21, status: 'draft', id: 7 },\n * { author: 'Jim', age: 27, status: 'draft', id: 8 },\n * { author: 'Jim', age: 27, status: 'published', id: 9 },\n * { author: 'Jason', age: 55, status: 'published', id: 10 }\n * ];\n * store.add('post', posts);\n * // Retrieve a filtered page of blog posts\n * // Would typically replace filter with findAll\n * const results = store.filter('post', {\n * where: {\n * status: {\n * // WHERE status = 'published'\n * '==': 'published'\n * },\n * author: {\n * // AND author IN ('bob', 'alice')\n * 'in': ['bob', 'alice'],\n * // OR author IN ('karen')\n * '|in': ['karen']\n * }\n * },\n * orderBy: [\n * // ORDER BY date_published DESC,\n * ['date_published', 'DESC'],\n * // ORDER BY title ASC\n * ['title', 'ASC']\n * ],\n * // LIMIT 2\n * limit: PAGE_SIZE,\n * // SKIP 4\n * offset: PAGE_SIZE * (currentPage - 1)\n * });\n * console.log(results);\n *\n * @namespace query\n * @property {number} [limit] See {@link query.limit}.\n * @property {number} [offset] See {@link query.offset}.\n * @property {string|Array[]} [orderBy] See {@link query.orderBy}.\n * @property {number} [skip] Alias for {@link query.offset}.\n * @property {string|Array[]} [sort] Alias for {@link query.orderBy}.\n * @property {Object} [where] See {@link query.where}.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/query-syntax\",\"JSData's Query Syntax\"]\n */\n query || (query = {})\n this.getData()\n if (utils.isObject(query)) {\n let where = {}\n\n /**\n * Filtering criteria. Records that do not meet this criteria will be exluded\n * from the result.\n *\n * @example Return posts where author is at least 32 years old\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post')\n * const posts = [\n * { author: 'John', age: 30, id: 5 },\n * { author: 'Sally', age: 31, id: 6 },\n * { author: 'Mike', age: 32, id: 7 },\n * { author: 'Adam', age: 33, id: 8 },\n * { author: 'Adam', age: 33, id: 9 }\n * ];\n * store.add('post', posts);\n * const results = store.filter('post', {\n * where: {\n * age: {\n * '>=': 30\n * }\n * }\n * });\n * console.log(results);\n *\n * @name query.where\n * @type {Object}\n * @see http://www.js-data.io/v3.0/docs/query-syntax\n * @since 3.0.0\n */\n if (utils.isObject(query.where) || utils.isArray(query.where)) {\n where = query.where\n }\n utils.forOwn(query, function (value, key) {\n if (!(key in reserved) && !(key in where)) {\n where[key] = {\n '==': value\n }\n }\n })\n let groups\n\n // Apply filter for each field\n if (utils.isObject(where) && Object.keys(where).length !== 0) {\n groups = this._applyWhereFromArray([where])\n } else if (utils.isArray(where)) {\n groups = this._applyWhereFromArray(where)\n }\n\n if (groups) {\n this.data = this.data.filter((item, i) => this._testArrayGroup(true, true, groups, item).keep)\n }\n\n // Sort\n let orderBy = query.orderBy || query.sort\n\n if (utils.isString(orderBy)) {\n orderBy = [\n [orderBy, 'ASC']\n ]\n }\n if (!utils.isArray(orderBy)) {\n orderBy = null\n }\n\n /**\n * Determines how records should be ordered in the result.\n *\n * @example Order posts by `author` then by `id` descending \n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post')\n * const posts = [\n * { author: 'John', age: 30, id: 5 },\n * { author: 'Sally', age: 31, id: 6 },\n * { author: 'Mike', age: 32, id: 7 },\n * { author: 'Adam', age: 33, id: 8 },\n * { author: 'Adam', age: 33, id: 9 }\n * ];\n * store.add('post', posts);\n * const results = store.filter('post', {\n * orderBy:[['author','ASC'],['id','DESC']]\n * });\n * console.log(results);\n *\n * @name query.orderBy\n * @type {string|Array[]}\n * @see http://www.js-data.io/v3.0/docs/query-syntax\n * @since 3.0.0\n */\n if (orderBy) {\n let index = 0\n orderBy.forEach(function (def, i) {\n if (utils.isString(def)) {\n orderBy[i] = [def, 'ASC']\n }\n })\n this.data.sort((a, b) => this.compare(orderBy, index, a, b))\n }\n\n /**\n * Number of records to skip.\n *\n * @example Retrieve the first \"page\" of blog posts using findAll\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n * const PAGE_SIZE = 10;\n * let currentPage = 1;\n * store.findAll('post', {\n * offset: PAGE_SIZE * (currentPage 1)\n * limit: PAGE_SIZE\n * });\n *\n * @example Retrieve the last \"page\" of blog posts using filter\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n *\n * const PAGE_SIZE = 5;\n * let currentPage = 2;\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, id: 1 },\n * { author: 'Sally', age: 31, id: 2 },\n * { author: 'Mike', age: 32, id: 3 },\n * { author: 'Adam', age: 33, id: 4 },\n * { author: 'Adam', age: 33, id: 5 },\n * { author: 'Peter', age: 25, id: 6 },\n * { author: 'Sally', age: 21, id: 7 },\n * { author: 'Jim', age: 27, id: 8 },\n * { author: 'Jim', age: 27, id: 9 },\n * { author: 'Jason', age: 55, id: 10 }\n * ];\n * store.add('post', posts);\n * const results = store.filter('post', {\n * offset: PAGE_SIZE * (currentPage 1)\n * limit: PAGE_SIZE\n * });\n * console.log(results)\n *\n * @name query.offset\n * @type {number}\n * @see http://www.js-data.io/v3.0/docs/query-syntax\n * @since 3.0.0\n */\n if (utils.isNumber(query.skip)) {\n this.skip(query.skip)\n } else if (utils.isNumber(query.offset)) {\n this.skip(query.offset)\n }\n\n /**\n * Maximum number of records to retrieve.\n *\n * @example Retrieve the first \"page\" of blog posts using findAll\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n *\n * const PAGE_SIZE = 10\n * let currentPage = 1\n * store.findAll('post', {\n * offset: PAGE_SIZE * (currentPage 1)\n * limit: PAGE_SIZE\n * });\n *\n * @example Retrieve the last \"page\" of blog posts using filter\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n *\n * const PAGE_SIZE = 5\n * let currentPage = 2\n * store.defineMapper('post')\n * const posts = [\n * { author: 'John', age: 30, id: 1 },\n * { author: 'Sally', age: 31, id: 2 },\n * { author: 'Mike', age: 32, id: 3 },\n * { author: 'Adam', age: 33, id: 4 },\n * { author: 'Adam', age: 33, id: 5 },\n * { author: 'Peter', age: 25, id: 6 },\n * { author: 'Sally', age: 21, id: 7 },\n * { author: 'Jim', age: 27, id: 8 },\n * { author: 'Jim', age: 27, id: 9 },\n * { author: 'Jason', age: 55, id: 10 }\n * ];\n * store.add('post', posts);\n * const results = store.filter('post', {\n * offset: PAGE_SIZE * (currentPage 1)\n * limit: PAGE_SIZE\n * });\n * console.log(results)\n *\n * @name query.limit\n * @type {number}\n * @see http://www.js-data.io/v3.0/docs/query-syntax\n * @since 3.0.0\n */\n if (utils.isNumber(query.limit)) {\n this.limit(query.limit)\n }\n } else if (utils.isFunction(query)) {\n this.data = this.data.filter(query, thisArg)\n }\n return this\n },\n\n /**\n * Iterate over all entities.\n *\n * @method Query#forEach\n * @param {Function} forEachFn Iteration function.\n * @param {*} [thisArg] Context to which to bind `forEachFn`.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n forEach (forEachFn, thisArg) {\n this.getData().forEach(forEachFn, thisArg)\n return this\n },\n\n /**\n * Find the entity or entities that match the provided key.\n *\n * @example Get the entity whose primary key is 25.\n * const entities = query.get(25).run();\n *\n * @example Same as above.\n * const entities = query.get([25]).run();\n *\n * @example Get all users who are active and have the \"admin\" role.\n * const activeAdmins = query.get(['active', 'admin'], {\n * index: 'activityAndRoles'\n * }).run();\n *\n * @example Get all entities that match a certain weather condition.\n * const niceDays = query.get(['sunny', 'humid', 'calm'], {\n * index: 'weatherConditions'\n * }).run();\n *\n * @method Query#get\n * @param {array} keyList Key(s) defining the entity to retrieve. If\n * `keyList` is not an array (i.e. for a single-value key), it will be\n * wrapped in an array.\n * @param {object} [opts] Configuration options.\n * @param {string} [opts.string] Name of the secondary index to use in the\n * query. If no index is specified, the main index is used.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n get (keyList, opts) {\n keyList || (keyList = [])\n opts || (opts = {})\n if (this.data) {\n throw utils.err(`${DOMAIN}#get`)(500, INDEX_ERR)\n }\n if (keyList && !utils.isArray(keyList)) {\n keyList = [keyList]\n }\n if (!keyList.length) {\n this.getData()\n return this\n }\n this.data = this.collection.getIndex(opts.index).get(keyList)\n return this\n },\n\n /**\n * Find the entity or entities that match the provided keyLists.\n *\n * @example Get the posts where \"status\" is \"draft\" or \"inReview\".\n * const posts = query.getAll('draft', 'inReview', { index: 'status' }).run();\n *\n * @example Same as above.\n * const posts = query.getAll(['draft'], ['inReview'], { index: 'status' }).run();\n *\n * @method Query#getAll\n * @param {...Array} [keyList] Provide one or more keyLists, and all\n * entities matching each keyList will be retrieved. If no keyLists are\n * provided, all entities will be returned.\n * @param {object} [opts] Configuration options.\n * @param {string} [opts.index] Name of the secondary index to use in the\n * query. If no index is specified, the main index is used.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n getAll (...args) {\n let opts = {}\n if (this.data) {\n throw utils.err(`${DOMAIN}#getAll`)(500, INDEX_ERR)\n }\n if (!args.length || (args.length === 1 && utils.isObject(args[0]))) {\n this.getData()\n return this\n } else if (args.length && utils.isObject(args[args.length - 1])) {\n opts = args[args.length - 1]\n args.pop()\n }\n const collection = this.collection\n const index = collection.getIndex(opts.index)\n this.data = []\n args.forEach((keyList) => {\n this.data = this.data.concat(index.get(keyList))\n })\n return this\n },\n\n /**\n * Return the current data result of this query.\n *\n * @method Query#getData\n * @returns {Array} The data in this query.\n * @since 3.0.0\n */\n getData () {\n if (!this.data) {\n this.data = this.collection.index.getAll()\n }\n return this.data\n },\n\n /**\n * Implementation used by the `like` operator. Takes a pattern and flags and\n * returns a `RegExp` instance that can test strings.\n *\n * @method Query#like\n * @param {string} pattern Testing pattern.\n * @param {string} flags Flags for the regular expression.\n * @returns {RegExp} Regular expression for testing strings.\n * @since 3.0.0\n */\n like (pattern, flags) {\n return new RegExp(`^${(escape(pattern).replace(percentRegExp, '.*').replace(underscoreRegExp, '.'))}$`, flags)\n },\n\n /**\n * Limit the result.\n *\n * @example Get only the first 2 posts.\n * const store = new JSData.DataStore();\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'draft', id: 2 },\n * { author: 'Mike', age: 32, status: 'draft', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'draft', id: 5 }\n * ];\n * store.add('post', posts);\n * const results = store.query('post').limit(2).run();\n * console.log(results);\n *\n * @method Query#limit\n * @param {number} num The maximum number of entities to keep in the result.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n limit (num) {\n if (!utils.isNumber(num)) {\n throw utils.err(`${DOMAIN}#limit`, 'num')(400, 'number', num)\n }\n const data = this.getData()\n this.data = data.slice(0, Math.min(data.length, num))\n return this\n },\n\n /**\n * Apply a mapping function to the result data.\n *\n * @example\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('user');\n * const users = [\n * { name: 'Peter', age: 25, id: 1 },\n * { name: 'Jim', age: 19, id: 2 },\n * { name: 'Mike', age: 17, id: 3 },\n * { name: 'Alan', age: 29, id: 4 },\n * { name: 'Katie', age: 33, id: 5 }\n * ];\n * store.add('user', users);\n * const ages = store\n * .query('user')\n * .map(function (user) {\n * return user.age;\n * })\n * .run();\n * console.log(ages);\n *\n * @method Query#map\n * @param {Function} mapFn Mapping function.\n * @param {*} [thisArg] Context to which to bind `mapFn`.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n map (mapFn, thisArg) {\n this.data = this.getData().map(mapFn, thisArg)\n return this\n },\n\n /**\n * Return the result of calling the specified function on each item in this\n * collection's main index.\n *\n * @example\n * const stringAges = UserCollection.query().mapCall('toString').run();\n *\n * @method Query#mapCall\n * @param {string} funcName Name of function to call\n * @parama {...*} [args] Remaining arguments to be passed to the function.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n mapCall (funcName, ...args) {\n this.data = this.getData().map(function (item) {\n return item[funcName](...args)\n })\n return this\n },\n\n /**\n * Complete the execution of the query and return the resulting data.\n *\n * @method Query#run\n * @returns {Array} The result of executing this query.\n * @since 3.0.0\n */\n run () {\n const data = this.data\n this.data = null\n return data\n },\n\n /**\n * Skip a number of results.\n *\n * @example Get all but the first 2 posts.\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'draft', id: 2 },\n * { author: 'Mike', age: 32, status: 'draft', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'draft', id: 5 }\n * ];\n * store.add('post', posts);\n * const results = store.query('post').skip(2).run();\n * console.log(results);\n *\n * @method Query#skip\n * @param {number} num The number of entities to skip.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n skip (num) {\n if (!utils.isNumber(num)) {\n throw utils.err(`${DOMAIN}#skip`, 'num')(400, 'number', num)\n }\n const data = this.getData()\n if (num < data.length) {\n this.data = data.slice(num)\n } else {\n this.data = []\n }\n return this\n }\n}, {\n /**\n * The filtering operators supported by {@link Query#filter}, and which are\n * implemented by adapters (for the most part).\n *\n * @example Variant 1\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'published', id: 2 },\n * { author: 'Mike', age: 32, status: 'published', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'published', id: 5 }\n * ];\n * store.add('post', posts);\n * const publishedPosts = store.filter('post', {\n * status: 'published',\n * limit: 2\n * });\n * console.log(publishedPosts);\n *\n *\n * @example Variant 2\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post')\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'published', id: 2 },\n * { author: 'Mike', age: 32, status: 'published', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'published', id: 5 }\n * ];\n * store.add('post', posts);\n * const publishedPosts = store.filter('post', {\n * where: {\n * status: {\n * '==': 'published'\n * }\n * },\n * limit: 2\n * });\n * console.log(publishedPosts);\n *\n * @example Variant 3\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'published', id: 2 },\n * { author: 'Mike', age: 32, status: 'published', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'published', id: 5 }\n * ];\n * store.add('post', posts);\n * const publishedPosts = store\n * .query('post')\n * .filter({ status: 'published' })\n * .limit(2)\n * .run();\n * console.log(publishedPosts);\n *\n * @example Variant 4\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'published', id: 2 },\n * { author: 'Mike', age: 32, status: 'published', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'published', id: 5 }\n * ];\n * store.add('post', posts);\n * const publishedPosts = store\n * .query('post')\n * .filter({\n * where: {\n * status: {\n * '==': 'published'\n * }\n * }\n * })\n * .limit(2)\n * .run();\n * console.log(publishedPosts);\n *\n * @example Multiple operators\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'published', id: 2 },\n * { author: 'Mike', age: 32, status: 'published', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'published', id: 5 }\n * ];\n * store.add('post', posts);\n *\n * const myPublishedPosts = store.filter('post', {\n * where: {\n * status: {\n * '==': 'published'\n * },\n * user_id: {\n * '==': currentUser.id\n * }\n * }\n * });\n *\n * console.log(myPublishedPosts);\n *\n * @name Query.ops\n * @property {Function} == Equality operator.\n * @property {Function} != Inequality operator.\n * @property {Function} > Greater than operator.\n * @property {Function} >= Greater than (inclusive) operator.\n * @property {Function} < Less than operator.\n * @property {Function} <= Less than (inclusive) operator.\n * @property {Function} isectEmpty Operator that asserts that the intersection\n * between two arrays is empty.\n * @property {Function} isectNotEmpty Operator that asserts that the\n * intersection between two arrays is __not__ empty.\n * @property {Function} in Operator that asserts whether a value is in an\n * array.\n * @property {Function} notIn Operator that asserts whether a value is __not__\n * in an array.\n * @property {Function} contains Operator that asserts whether an array\n * contains a value.\n * @property {Function} notContains Operator that asserts whether an array\n * does __not__ contain a value.\n * @since 3.0.0\n * @type {Object}\n */\n ops: {\n '=': function (value, predicate) {\n return value == predicate // eslint-disable-line\n },\n '==': function (value, predicate) {\n return value == predicate // eslint-disable-line\n },\n '===': function (value, predicate) {\n return value === predicate\n },\n '!=': function (value, predicate) {\n return value != predicate // eslint-disable-line\n },\n '!==': function (value, predicate) {\n return value !== predicate\n },\n '>': function (value, predicate) {\n return value > predicate\n },\n '>=': function (value, predicate) {\n return value >= predicate\n },\n '<': function (value, predicate) {\n return value < predicate\n },\n '<=': function (value, predicate) {\n return value <= predicate\n },\n 'isectEmpty': function (value, predicate) {\n return !utils.intersection((value || []), (predicate || [])).length\n },\n 'isectNotEmpty': function (value, predicate) {\n return utils.intersection((value || []), (predicate || [])).length\n },\n 'in': function (value, predicate) {\n return predicate.indexOf(value) !== -1\n },\n 'notIn': function (value, predicate) {\n return predicate.indexOf(value) === -1\n },\n 'contains': function (value, predicate) {\n return (value || []).indexOf(predicate) !== -1\n },\n 'notContains': function (value, predicate) {\n return (value || []).indexOf(predicate) === -1\n }\n }\n})\n\n/**\n * Create a subclass of this Query:\n * @example Query.extend\n * const JSData = require('js-data');\n * const { Query } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomQueryClass extends Query {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customQuery = new CustomQueryClass();\n * console.log(customQuery.foo());\n * console.log(CustomQueryClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherQueryClass = Query.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherQuery = new OtherQueryClass();\n * console.log(otherQuery.foo());\n * console.log(OtherQueryClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherQueryClass (collection) {\n * Query.call(this, collection);\n * this.created_at = new Date().getTime();\n * }\n * Query.extend({\n * constructor: AnotherQueryClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const anotherQuery = new AnotherQueryClass();\n * console.log(anotherQuery.created_at);\n * console.log(anotherQuery.foo());\n * console.log(AnotherQueryClass.beep());\n *\n * @method Query.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this Query class.\n * @since 3.0.0\n */\n","import utils from './utils'\n\n// TODO: remove this when the rest of the project is cleaned\nexport const belongsToType = 'belongsTo'\nexport const hasManyType = 'hasMany'\nexport const hasOneType = 'hasOne'\n\nconst DOMAIN = 'Relation'\n\nexport function Relation (relatedMapper, options = {}) {\n utils.classCallCheck(this, Relation)\n\n options.type = this.constructor.TYPE_NAME\n this.validateOptions(relatedMapper, options)\n\n if (typeof relatedMapper === 'object') {\n Object.defineProperty(this, 'relatedMapper', { value: relatedMapper })\n }\n\n Object.defineProperty(this, 'inverse', { writable: true })\n utils.fillIn(this, options)\n}\n\nRelation.extend = utils.extend\n\nutils.addHiddenPropsToTarget(Relation.prototype, {\n get canAutoAddLinks () {\n return this.add === undefined || !!this.add\n },\n\n get relatedCollection () {\n return this.mapper.datastore.getCollection(this.relation)\n },\n\n validateOptions (related, opts) {\n const DOMAIN_ERR = `new ${DOMAIN}`\n\n const localField = opts.localField\n if (!localField) {\n throw utils.err(DOMAIN_ERR, 'opts.localField')(400, 'string', localField)\n }\n\n const foreignKey = opts.foreignKey = opts.foreignKey || opts.localKey\n if (!foreignKey && (opts.type === belongsToType || opts.type === hasOneType)) {\n throw utils.err(DOMAIN_ERR, 'opts.foreignKey')(400, 'string', foreignKey)\n }\n\n if (utils.isString(related)) {\n opts.relation = related\n if (!utils.isFunction(opts.getRelation)) {\n throw utils.err(DOMAIN_ERR, 'opts.getRelation')(400, 'function', opts.getRelation)\n }\n } else if (related) {\n opts.relation = related.name\n } else {\n throw utils.err(DOMAIN_ERR, 'related')(400, 'Mapper or string', related)\n }\n },\n\n assignTo (mapper) {\n this.name = mapper.name\n Object.defineProperty(this, 'mapper', { value: mapper })\n\n mapper.relationList || Object.defineProperty(mapper, 'relationList', { value: [] })\n mapper.relationFields || Object.defineProperty(mapper, 'relationFields', { value: [] })\n mapper.relationList.push(this)\n mapper.relationFields.push(this.localField)\n },\n\n canFindLinkFor () {\n return !!(this.foreignKey || this.localKey)\n },\n\n getRelation () {\n return this.relatedMapper\n },\n\n getForeignKey (record) {\n return utils.get(record, this.mapper.idAttribute)\n },\n\n setForeignKey (record, relatedRecord) {\n if (!record || !relatedRecord) {\n return\n }\n\n this._setForeignKey(record, relatedRecord)\n },\n\n _setForeignKey (record, relatedRecords) {\n const idAttribute = this.mapper.idAttribute\n\n if (!utils.isArray(relatedRecords)) {\n relatedRecords = [relatedRecords]\n }\n\n relatedRecords.forEach((relatedRecord) => {\n utils.set(relatedRecord, this.foreignKey, utils.get(record, idAttribute))\n })\n },\n\n getLocalField (record) {\n return utils.get(record, this.localField)\n },\n\n setLocalField (record, relatedData) {\n return utils.set(record, this.localField, relatedData)\n },\n\n getInverse (mapper) {\n if (!this.inverse) {\n this.findInverseRelation(mapper)\n }\n\n return this.inverse\n },\n\n findInverseRelation (mapper) {\n this.getRelation().relationList.forEach((def) => {\n if (def.getRelation() === mapper && this.isInversedTo(def) && this !== def) {\n this.inverse = def\n return true\n }\n })\n },\n\n isInversedTo (def) {\n return !def.foreignKey || def.foreignKey === this.foreignKey\n },\n\n addLinkedRecords (records) {\n const datastore = this.mapper.datastore\n\n records.forEach((record) => {\n let relatedData = this.getLocalField(record)\n\n if (utils.isFunction(this.add)) {\n relatedData = this.add(datastore, this, record)\n } else if (relatedData) {\n relatedData = this.linkRecord(record, relatedData)\n }\n\n const isEmptyLinks = !relatedData || (utils.isArray(relatedData) && !relatedData.length)\n\n if (isEmptyLinks && this.canFindLinkFor(record)) {\n relatedData = this.findExistingLinksFor(record)\n }\n\n if (relatedData) {\n this.setLocalField(record, relatedData)\n }\n })\n },\n\n removeLinkedRecords (relatedMapper, records) {\n const localField = this.localField\n records.forEach((record) => {\n utils.set(record, localField, undefined)\n })\n },\n\n linkRecord (record, relatedRecord) {\n const relatedId = utils.get(relatedRecord, this.mapper.idAttribute)\n\n if (relatedId === undefined) {\n const unsaved = this.relatedCollection.unsaved()\n if (unsaved.indexOf(relatedRecord) === -1) {\n if (this.canAutoAddLinks) {\n relatedRecord = this.relatedCollection.add(relatedRecord)\n }\n }\n } else {\n if (relatedRecord !== this.relatedCollection.get(relatedId)) {\n this.setForeignKey(record, relatedRecord)\n\n if (this.canAutoAddLinks) {\n relatedRecord = this.relatedCollection.add(relatedRecord)\n }\n }\n }\n\n return relatedRecord\n },\n\n // e.g. user hasMany post via \"foreignKey\", so find all posts of user\n findExistingLinksByForeignKey (id) {\n if (id === undefined || id === null) {\n return\n }\n return this.relatedCollection.filter({\n [this.foreignKey]: id\n })\n },\n\n ensureLinkedDataHasProperType (props, opts) {\n const relatedMapper = this.getRelation()\n const relationData = this.getLocalField(props)\n\n if (utils.isArray(relationData) && (!relationData.length || relatedMapper.is(relationData[0]))) {\n return\n }\n\n if (relationData && !relatedMapper.is(relationData)) {\n utils.set(props, this.localField, relatedMapper.createRecord(relationData, opts))\n }\n },\n\n isRequiresParentId () {\n return false\n },\n\n isRequiresChildId () {\n return false\n },\n\n createChildRecord (props, relationData, opts) {\n this.setForeignKey(props, relationData)\n\n return this.createLinked(relationData, opts).then((result) => {\n this.setLocalField(props, result)\n })\n },\n\n createLinked (props, opts) {\n const create = utils.isArray(props) ? 'createMany' : 'create'\n\n return this.getRelation()[create](props, opts)\n }\n})\n","import utils from '../utils'\nimport { Relation } from '../Relation'\n\nexport const BelongsToRelation = Relation.extend({\n getForeignKey (record) {\n return utils.get(record, this.foreignKey)\n },\n\n _setForeignKey (record, relatedRecord) {\n utils.set(record, this.foreignKey, utils.get(relatedRecord, this.getRelation().idAttribute))\n },\n\n findExistingLinksFor (record) {\n // console.log('\\tBelongsTo#findExistingLinksFor', record)\n if (!record) {\n return\n }\n const relatedId = utils.get(record, this.foreignKey)\n if (relatedId !== undefined && relatedId !== null) {\n return this.relatedCollection.get(relatedId)\n }\n },\n\n isRequiresParentId () {\n return true\n },\n\n createParentRecord (props, opts) {\n const relationData = this.getLocalField(props)\n\n return this.createLinked(relationData, opts).then((record) => {\n this.setForeignKey(props, record)\n })\n },\n\n createChildRecord () {\n throw new Error('\"BelongsTo\" relation does not support child creation as it cannot have children.')\n }\n}, {\n TYPE_NAME: 'belongsTo'\n})\n","import utils from '../utils'\nimport { Relation } from '../Relation'\n\nexport const HasManyRelation = Relation.extend({\n validateOptions (related, opts) {\n Relation.prototype.validateOptions.call(this, related, opts)\n\n const { localKeys, foreignKeys, foreignKey } = opts\n\n if (!foreignKey && !localKeys && !foreignKeys) {\n throw utils.err('new Relation', 'opts.')(400, 'string', foreignKey)\n }\n },\n\n canFindLinkFor (record) {\n const hasForeignKeys = this.foreignKey || this.foreignKeys\n return !!(hasForeignKeys || (this.localKeys && utils.get(record, this.localKeys)))\n },\n\n linkRecord (record, relatedRecords) {\n const relatedCollection = this.relatedCollection\n const canAutoAddLinks = this.canAutoAddLinks\n const foreignKey = this.foreignKey\n const unsaved = this.relatedCollection.unsaved()\n\n return relatedRecords.map((relatedRecord) => {\n const relatedId = relatedCollection.recordId(relatedRecord)\n\n if ((relatedId === undefined && unsaved.indexOf(relatedRecord) === -1) || relatedRecord !== relatedCollection.get(relatedId)) {\n if (foreignKey) {\n // TODO: slow, could be optimized? But user loses hook\n this.setForeignKey(record, relatedRecord)\n }\n if (canAutoAddLinks) {\n relatedRecord = relatedCollection.add(relatedRecord)\n }\n }\n\n return relatedRecord\n })\n },\n\n findExistingLinksFor (record) {\n const id = utils.get(record, this.mapper.idAttribute)\n const ids = this.localKeys ? utils.get(record, this.localKeys) : null\n let records\n\n if (id !== undefined && this.foreignKey) {\n records = this.findExistingLinksByForeignKey(id)\n } else if (this.localKeys && ids) {\n records = this.findExistingLinksByLocalKeys(ids)\n } else if (id !== undefined && this.foreignKeys) {\n records = this.findExistingLinksByForeignKeys(id)\n }\n\n if (records && records.length) {\n return records\n }\n },\n\n // e.g. user hasMany group via \"foreignKeys\", so find all users of a group\n findExistingLinksByLocalKeys (ids) {\n return this.relatedCollection.filter({\n where: {\n [this.mapper.idAttribute]: {\n 'in': ids\n }\n }\n })\n },\n\n // e.g. group hasMany user via \"localKeys\", so find all groups that own a user\n findExistingLinksByForeignKeys (id) {\n return this.relatedCollection.filter({\n where: {\n [this.foreignKeys]: {\n 'contains': id\n }\n }\n })\n },\n\n isRequiresParentId () {\n return !!this.localKeys && this.localKeys.length > 0\n },\n\n isRequiresChildId () {\n return !!this.foreignKey\n },\n\n createParentRecord (props, opts) {\n const relationData = this.getLocalField(props)\n const foreignIdField = this.getRelation().idAttribute\n\n return this.createLinked(relationData, opts).then((records) => {\n utils.set(props, this.localKeys, records.map((record) => utils.get(record, foreignIdField)))\n })\n },\n\n createLinked (props, opts) {\n return this.getRelation().createMany(props, opts)\n }\n}, {\n TYPE_NAME: 'hasMany'\n})\n","import utils from '../utils'\nimport { Relation } from '../Relation'\n\nexport const HasOneRelation = Relation.extend({\n findExistingLinksFor (relatedMapper, record) {\n const recordId = utils.get(record, relatedMapper.idAttribute)\n const records = this.findExistingLinksByForeignKey(recordId)\n\n if (records && records.length) {\n return records[0]\n }\n },\n\n isRequiresChildId () {\n return true\n }\n}, {\n TYPE_NAME: 'hasOne'\n})\n","import { Relation } from './Relation'\nimport { BelongsToRelation } from './Relation/BelongsTo'\nimport { HasManyRelation } from './Relation/HasMany'\nimport { HasOneRelation } from './Relation/HasOne'\n\n[BelongsToRelation, HasManyRelation, HasOneRelation].forEach(function (RelationType) {\n Relation[RelationType.TYPE_NAME] = function (related, options) {\n return new RelationType(related, options)\n }\n})\n\nexport { belongsToType, hasManyType, hasOneType, Relation } from './Relation'\n","import { Relation } from './relations'\n\nexport { belongsToType, hasManyType, hasOneType } from './relations'\n/**\n * BelongsTo relation decorator. You probably won't use this directly.\n *\n * @name module:js-data.belongsTo\n * @method\n * @param {Mapper} related The relation the target belongs to.\n * @param {object} opts Configuration options.\n * @param {string} opts.foreignKey The field that holds the primary key of the\n * related record.\n * @param {string} opts.localField The field that holds a reference to the\n * related record object.\n * @returns {Function} Invocation function, which accepts the target as the only\n * parameter.\n */\nexport const belongsTo = function (related, opts) {\n return function (mapper) {\n Relation.belongsTo(related, opts).assignTo(mapper)\n }\n}\n\n/**\n * HasMany relation decorator. You probably won't use this directly.\n *\n * @name module:js-data.hasMany\n * @method\n * @param {Mapper} related The relation of which the target has many.\n * @param {object} opts Configuration options.\n * @param {string} [opts.foreignKey] The field that holds the primary key of the\n * related record.\n * @param {string} opts.localField The field that holds a reference to the\n * related record object.\n * @returns {Function} Invocation function, which accepts the target as the only\n * parameter.\n */\nexport const hasMany = function (related, opts) {\n return function (mapper) {\n Relation.hasMany(related, opts).assignTo(mapper)\n }\n}\n\n/**\n * HasOne relation decorator. You probably won't use this directly.\n *\n * @name module:js-data.hasOne\n * @method\n * @param {Mapper} related The relation of which the target has one.\n * @param {object} opts Configuration options.\n * @param {string} [opts.foreignKey] The field that holds the primary key of the\n * related record.\n * @param {string} opts.localField The field that holds a reference to the\n * related record object.\n * @returns {Function} Invocation function, which accepts the target as the only\n * parameter.\n */\nexport const hasOne = function (related, opts) {\n return function (mapper) {\n Relation.hasOne(related, opts).assignTo(mapper)\n }\n}\n","import utils, { safeSetLink } from './utils'\nimport Component from './Component'\nimport Settable from './Settable'\nimport {\n hasManyType,\n hasOneType\n} from './decorators'\n\nconst DOMAIN = 'Record'\n\nconst superMethod = function (mapper, name) {\n const store = mapper.datastore\n if (store && store[name]) {\n return function (...args) {\n return store[name](mapper.name, ...args)\n }\n }\n return mapper[name].bind(mapper)\n}\n\n// Cache these strings\nconst creatingPath = 'creating'\nconst noValidatePath = 'noValidate'\nconst keepChangeHistoryPath = 'keepChangeHistory'\nconst previousPath = 'previous'\n\n/**\n * js-data's Record class. An instance of `Record` corresponds to an in-memory\n * representation of a single row or document in a database, Firebase,\n * localstorage, etc. Basically, a `Record` instance represents whatever kind of\n * entity in your persistence layer that has a primary key.\n *\n * ```javascript\n * import {Record} from 'js-data'\n * ```\n *\n * @example Record#constructor\n * const JSData = require('js-data');\n * const { Record } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Instantiate a plain record\n * let record = new Record();\n * console.log('record: ' + JSON.stringify(record));\n *\n * // You can supply properties on instantiation\n * record = new Record({ name: 'John' });\n * console.log('record: ' + JSON.stringify(record));\n *\n * @example Record#constructor2\n * const JSData = require('js-data');\n * const { Mapper } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Instantiate a record that's associated with a Mapper:\n * const UserMapper = new Mapper({ name: 'user' });\n * const User = UserMapper.recordClass;\n * const user = UserMapper.createRecord({ name: 'John' });\n * const user2 = new User({ name: 'Sally' });\n * console.log('user: ' + JSON.stringify(user));\n * console.log('user2: ' + JSON.stringify(user2));\n *\n * @example Record#constructor3\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * store.defineMapper('user');\n *\n * // Instantiate a record that's associated with a store's Mapper\n * const user = store.createRecord('user', { name: 'John' });\n * console.log('user: ' + JSON.stringify(user));\n *\n * @example Record#constructor4\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * store.defineMapper('user', {\n * schema: {\n * properties: {\n * name: { type: 'string' }\n * }\n * }\n * });\n *\n * // Validate on instantiation\n * const user = store.createRecord('user', { name: 1234 });\n * console.log('user: ' + JSON.stringify(user));\n *\n * @example Record#constructor5\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * store.defineMapper('user', {\n * schema: {\n * properties: {\n * name: { type: 'string' }\n * }\n * }\n * });\n *\n * // Skip validation on instantiation\n * const user = store.createRecord('user', { name: 1234 }, { noValidate: true });\n * console.log('user: ' + JSON.stringify(user));\n * console.log('user.isValid(): ' + user.isValid());\n *\n * @class Record\n * @extends Component\n * @param {object} [props] The initial properties of the new Record instance.\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.noValidate=false] Whether to skip validation on the\n * initial properties.\n * @param {boolean} [opts.validateOnSet=true] Whether to enable setter\n * validation on properties after the Record has been initialized.\n * @since 3.0.0\n */\nfunction Record (props, opts) {\n utils.classCallCheck(this, Record)\n Settable.call(this)\n props || (props = {})\n opts || (opts = {})\n const _set = this._set\n const mapper = this.constructor.mapper\n\n _set(creatingPath, true)\n _set(noValidatePath, !!opts.noValidate)\n _set(keepChangeHistoryPath, opts.keepChangeHistory === undefined ? (mapper ? mapper.keepChangeHistory : true) : opts.keepChangeHistory)\n\n // Set the idAttribute value first, if it exists.\n const id = mapper ? utils.get(props, mapper.idAttribute) : undefined\n if (id !== undefined) {\n utils.set(this, mapper.idAttribute, id)\n }\n\n utils.fillIn(this, props)\n _set(creatingPath, false)\n if (opts.validateOnSet !== undefined) {\n _set(noValidatePath, !opts.validateOnSet)\n } else if (mapper && mapper.validateOnSet !== undefined) {\n _set(noValidatePath, !mapper.validateOnSet)\n } else {\n _set(noValidatePath, false)\n }\n _set(previousPath, mapper ? mapper.toJSON(props) : utils.plainCopy(props))\n}\n\nexport default Component.extend({\n constructor: Record,\n\n /**\n * Returns the {@link Mapper} paired with this record's class, if any.\n *\n * @method Record#_mapper\n * @returns {Mapper} The {@link Mapper} paired with this record's class, if any.\n * @since 3.0.0\n */\n _mapper () {\n const mapper = this.constructor.mapper\n if (!mapper) {\n throw utils.err(`${DOMAIN}#_mapper`, '')(404, 'mapper')\n }\n return mapper\n },\n\n /**\n * Lifecycle hook.\n *\n * @method Record#afterLoadRelations\n * @param {string[]} relations The `relations` argument passed to {@link Record#loadRelations}.\n * @param {object} opts The `opts` argument passed to {@link Record#loadRelations}.\n * @since 3.0.0\n */\n afterLoadRelations () {},\n\n /**\n * Lifecycle hook.\n *\n * @method Record#beforeLoadRelations\n * @param {string[]} relations The `relations` argument passed to {@link Record#loadRelations}.\n * @param {object} opts The `opts` argument passed to {@link Record#loadRelations}.\n * @since 3.0.0\n */\n beforeLoadRelations () {},\n\n /**\n * Return the change history of this record since it was instantiated or\n * {@link Record#commit} was called.\n *\n * @method Record#changeHistory\n * @since 3.0.0\n */\n changeHistory () {\n return (this._get('history') || []).slice()\n },\n\n /**\n * Return changes to this record since it was instantiated or\n * {@link Record#commit} was called.\n *\n * @example Record#changes\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * store.defineMapper('user');\n * const user = store.createRecord('user');\n * console.log('user changes: ' + JSON.stringify(user.changes()));\n * user.name = 'John';\n * console.log('user changes: ' + JSON.stringify(user.changes()));\n *\n * @method Record#changes\n * @param [opts] Configuration options.\n * @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function.\n * @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore.\n * @returns {Object} Object describing the changes to this record since it was\n * instantiated or its {@link Record#commit} method was last called.\n * @since 3.0.0\n */\n changes (opts) {\n opts || (opts = {})\n return utils.diffObjects(typeof this.toJSON === 'function' ? this.toJSON(opts) : this, this._get('previous'), opts)\n },\n\n /**\n * Make the record's current in-memory state it's only state, with any\n * previous property values being set to current values.\n *\n * @example Record#commit\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * store.defineMapper('user');\n * const user = store.createRecord('user');\n * console.log('user hasChanges: ' + user.hasChanges());\n * user.name = 'John';\n * console.log('user hasChanges: ' + user.hasChanges());\n * user.commit();\n * console.log('user hasChanges: ' + user.hasChanges());\n *\n * @method Record#commit\n * @param {object} [opts] Configuration options. Passed to {@link Record#toJSON}.\n * @since 3.0.0\n */\n commit (opts) {\n this._set('changed') // unset\n this._set('changing', false)\n this._set('history', []) // clear history\n this._set('previous', this.toJSON(opts))\n },\n\n /**\n * Call {@link Mapper#destroy} using this record's primary key.\n *\n * @example\n * import { Container } from 'js-data';\n * import { RethinkDBAdapter } from 'js-data-rethinkdb';\n *\n * const store = new Container();\n * store.registerAdapter('rethink', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('user');\n * store.find('user', 1234).then((user) => {\n * console.log(user.id); // 1234\n *\n * // Destroy this user from the database\n * return user.destroy();\n * });\n *\n * @method Record#destroy\n * @param {object} [opts] Configuration options passed to {@link Mapper#destroy}.\n * @returns {Promise} The result of calling {@link Mapper#destroy} with the\n * primary key of this record.\n * @since 3.0.0\n */\n destroy (opts) {\n opts || (opts = {})\n const mapper = this._mapper()\n return superMethod(mapper, 'destroy')(utils.get(this, mapper.idAttribute), opts)\n },\n\n /**\n * Return the value at the given path for this instance.\n *\n * @example Record#get\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user');\n *\n * const user = store.createRecord('user', { name: 'Bob' });\n * console.log('user.get(\"name\"): ' + user.get('name'));\n *\n * @method Record#get\n * @param {string} key Path of value to retrieve.\n * @returns {*} Value at path.\n * @since 3.0.0\n */\n 'get' (key) {\n return utils.get(this, key)\n },\n\n /**\n * Return whether this record has changed since it was instantiated or\n * {@link Record#commit} was called.\n *\n * @example Record#hasChanges\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user');\n * const user = store.createRecord('user');\n * console.log('user hasChanges: ' + user.hasChanges());\n * user.name = 'John';\n * console.log('user hasChanges: ' + user.hasChanges());\n * user.commit();\n * console.log('user hasChanges: ' + user.hasChanges());\n *\n * @method Record#hasChanges\n * @param [opts] Configuration options.\n * @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function.\n * @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore.\n * @returns {boolean} Return whether the record has changed since it was\n * instantiated or since its {@link Record#commit} method was called.\n * @since 3.0.0\n */\n hasChanges (opts) {\n const quickHasChanges = !!(this._get('changed') || []).length\n return quickHasChanges || utils.areDifferent(typeof this.toJSON === 'function' ? this.toJSON(opts) : this, this._get('previous'), opts)\n },\n\n /**\n * Return whether the record is unsaved. Records that have primary keys are\n * considered \"saved\". Records without primary keys are considered \"unsaved\".\n *\n * @example Record#isNew\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user');\n * const user = store.createRecord('user', {\n * id: 1234\n * });\n * const user2 = store.createRecord('user');\n * console.log('user isNew: ' + user.isNew()); // false\n * console.log('user2 isNew: ' + user2.isNew()); // true\n *\n * @method Record#isNew\n * @returns {boolean} Whether the record is unsaved.\n * @since 3.0.0\n */\n isNew (opts) {\n return utils.get(this, this._mapper().idAttribute) === undefined\n },\n\n /**\n * Return whether the record in its current state passes validation.\n *\n * @example Record#isValid\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user', {\n * schema: {\n * properties: {\n * name: { type: 'string' }\n * }\n * }\n * });\n * const user = store.createRecord('user', {\n * name: 1234\n * }, {\n * noValidate: true // this allows us to put the record into an invalid state\n * });\n * console.log('user isValid: ' + user.isValid());\n * user.name = 'John';\n * console.log('user isValid: ' + user.isValid());\n *\n * @method Record#isValid\n * @param {object} [opts] Configuration options. Passed to {@link Mapper#validate}.\n * @returns {boolean} Whether the record in its current state passes\n * validation.\n * @since 3.0.0\n */\n isValid (opts) {\n return !this._mapper().validate(this, opts)\n },\n\n removeInverseRelation (currentParent, id, inverseDef, idAttribute) {\n if (inverseDef.type === hasOneType) {\n safeSetLink(currentParent, inverseDef.localField, undefined)\n } else if (inverseDef.type === hasManyType) {\n // e.g. remove comment from otherPost.comments\n const children = utils.get(currentParent, inverseDef.localField)\n if (id === undefined) {\n utils.remove(children, (child) => child === this)\n } else {\n utils.remove(children, (child) => child === this || id === utils.get(child, idAttribute))\n }\n }\n },\n\n setupInverseRelation (record, id, inverseDef, idAttribute) {\n // Update (set) inverse relation\n if (inverseDef.type === hasOneType) {\n // e.g. someUser.profile = profile\n safeSetLink(record, inverseDef.localField, this)\n } else if (inverseDef.type === hasManyType) {\n // e.g. add comment to somePost.comments\n const children = utils.get(record, inverseDef.localField)\n if (id === undefined) {\n utils.noDupeAdd(children, this, (child) => child === this)\n } else {\n utils.noDupeAdd(children, this, (child) => child === this || id === utils.get(child, idAttribute))\n }\n }\n },\n\n /**\n * Lazy load relations of this record, to be attached to the record once their\n * loaded.\n *\n * @example\n * import { Container } from 'js-data';\n * import { RethinkDBAdapter } from 'js-data-rethinkdb';\n *\n * const store = new Container();\n * store.registerAdapter('rethink', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('user', {\n * relations: {\n * hasMany: {\n * post: {\n * localField: 'posts',\n * foreignKey: 'user_id'\n * }\n * }\n * }\n * });\n * store.defineMapper('post', {\n * relations: {\n * belongsTo: {\n * user: {\n * localField: 'user',\n * foreignKey: 'user_id'\n * }\n * }\n * }\n * });\n * store.find('user', 1234).then((user) => {\n * console.log(user.id); // 1234\n *\n * // Load the user's post relations\n * return user.loadRelations(['post']);\n * }).then((user) => {\n * console.log(user.posts); // [{...}, {...}, ...]\n * });\n *\n * @method Record#loadRelations\n * @param {string[]} [relations] List of relations to load. Can use localField\n * names or Mapper names to pick relations.\n * @param {object} [opts] Configuration options.\n * @returns {Promise} Resolves with the record, with the loaded relations now\n * attached.\n * @since 3.0.0\n */\n loadRelations (relations, opts) {\n let op\n const mapper = this._mapper()\n\n // Default values for arguments\n relations || (relations = [])\n if (utils.isString(relations)) {\n relations = [relations]\n }\n opts || (opts = {})\n opts.with = relations\n\n // Fill in \"opts\" with the Model's configuration\n utils._(opts, mapper)\n opts.adapter = mapper.getAdapterName(opts)\n\n // beforeLoadRelations lifecycle hook\n op = opts.op = 'beforeLoadRelations'\n return utils.resolve(this[op](relations, opts)).then(() => {\n // Now delegate to the adapter\n op = opts.op = 'loadRelations'\n mapper.dbg(op, this, relations, opts)\n let tasks = []\n let task\n utils.forEachRelation(mapper, opts, (def, optsCopy) => {\n const relatedMapper = def.getRelation()\n optsCopy.raw = false\n if (utils.isFunction(def.load)) {\n task = def.load(mapper, def, this, opts)\n } else if (def.type === 'hasMany' || def.type === 'hasOne') {\n if (def.foreignKey) {\n task = superMethod(relatedMapper, 'findAll')({\n [def.foreignKey]: utils.get(this, mapper.idAttribute)\n }, optsCopy).then(function (relatedData) {\n if (def.type === 'hasOne') {\n return relatedData.length ? relatedData[0] : undefined\n }\n return relatedData\n })\n } else if (def.localKeys) {\n task = superMethod(relatedMapper, 'findAll')({\n where: {\n [relatedMapper.idAttribute]: {\n 'in': utils.get(this, def.localKeys)\n }\n }\n })\n } else if (def.foreignKeys) {\n task = superMethod(relatedMapper, 'findAll')({\n where: {\n [def.foreignKeys]: {\n 'contains': utils.get(this, mapper.idAttribute)\n }\n }\n }, opts)\n }\n } else if (def.type === 'belongsTo') {\n const key = utils.get(this, def.foreignKey)\n if (utils.isSorN(key)) {\n task = superMethod(relatedMapper, 'find')(key, optsCopy)\n }\n }\n if (task) {\n task = task.then((relatedData) => {\n def.setLocalField(this, relatedData)\n })\n tasks.push(task)\n }\n })\n return Promise.all(tasks)\n }).then(() => {\n // afterLoadRelations lifecycle hook\n op = opts.op = 'afterLoadRelations'\n return utils.resolve(this[op](relations, opts)).then(() => this)\n })\n },\n\n /**\n * Return the properties with which this record was instantiated.\n *\n * @example Record#previous\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user');\n * const user = store.createRecord('user', {\n * name: 'William'\n * });\n * console.log('user previous: ' + JSON.stringify(user.previous()));\n * user.name = 'Bob';\n * console.log('user previous: ' + JSON.stringify(user.previous()));\n * user.commit();\n * console.log('user previous: ' + JSON.stringify(user.previous()));\n *\n * @method Record#previous\n * @param {string} [key] If specified, return just the initial value of the\n * given key.\n * @returns {Object} The initial properties of this record.\n * @since 3.0.0\n */\n previous (key) {\n if (key) {\n return this._get(`previous.${key}`)\n }\n return this._get('previous')\n },\n\n /**\n * Revert changes to this record back to the properties it had when it was\n * instantiated.\n *\n * @example Record#revert\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user');\n * const user = store.createRecord('user', {\n * name: 'William'\n * });\n * console.log('user: ' + JSON.stringify(user));\n * user.name = 'Bob';\n * console.log('user: ' + JSON.stringify(user));\n * user.revert();\n * console.log('user: ' + JSON.stringify(user));\n *\n * @method Record#revert\n * @param {object} [opts] Configuration options.\n * @param {string[]} [opts.preserve] Array of strings or Regular Expressions\n * denoting properties that should not be reverted.\n * @since 3.0.0\n */\n revert (opts) {\n const previous = this._get('previous')\n opts || (opts = {})\n opts.preserve || (opts.preserve = [])\n utils.forOwn(this, (value, key) => {\n if (key !== this._mapper().idAttribute && !previous.hasOwnProperty(key) && this.hasOwnProperty(key) && opts.preserve.indexOf(key) === -1) {\n delete this[key]\n }\n })\n utils.forOwn(previous, (value, key) => {\n if (opts.preserve.indexOf(key) === -1) {\n this[key] = value\n }\n })\n this.commit()\n },\n\n /**\n * Delegates to {@link Mapper#create} or {@link Mapper#update}.\n *\n * @example\n * import { Container } from 'js-data';\n * import { RethinkDBAdapter } from 'js-data-rethinkdb';\n *\n * const store = new Container();\n * store.registerAdapter('rethink', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('session');\n * const session = store.createRecord('session', { topic: 'Node.js' });\n *\n * // Create a new record in the database\n * session.save().then(() => {\n * console.log(session.id); // 1234\n *\n * session.skill_level = 'beginner';\n *\n * // Update the record in the database\n * return session.save();\n * });\n *\n * @method Record#save\n * @param {object} [opts] Configuration options. See {@link Mapper#create} and\n * {@link Mapper#update}.\n * @param {boolean} [opts.changesOnly] Equality function. Default uses `===`.\n * @param {Function} [opts.equalsFn] Passed to {@link Record#changes} when\n * `opts.changesOnly` is `true`.\n * @param {array} [opts.ignore] Passed to {@link Record#changes} when\n * `opts.changesOnly` is `true`.\n * @returns {Promise} The result of calling {@link Mapper#create} or\n * {@link Mapper#update}.\n * @since 3.0.0\n */\n save (opts) {\n opts || (opts = {})\n const mapper = this._mapper()\n const id = utils.get(this, mapper.idAttribute)\n let props = this\n\n const postProcess = (result) => {\n const record = opts.raw ? result.data : result\n if (record) {\n utils.deepMixIn(this, record)\n this.commit()\n }\n return result\n }\n\n if (id === undefined) {\n return superMethod(mapper, 'create')(props, opts).then(postProcess)\n }\n if (opts.changesOnly) {\n const changes = this.changes(opts)\n props = {}\n utils.fillIn(props, changes.added)\n utils.fillIn(props, changes.changed)\n }\n return superMethod(mapper, 'update')(id, props, opts).then(postProcess)\n },\n\n /**\n * Set the value for a given key, or the values for the given keys if \"key\" is\n * an object. Triggers change events on those properties that have `track: true`\n * in {@link Mapper#schema}.\n *\n * @example Record#set\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user');\n *\n * const user = store.createRecord('user');\n * console.log('user: ' + JSON.stringify(user));\n *\n * user.set('name', 'Bob');\n * console.log('user: ' + JSON.stringify(user));\n *\n * user.set({ age: 30, role: 'admin' });\n * console.log('user: ' + JSON.stringify(user));\n *\n * @fires Record#change\n * @method Record#set\n * @param {(string|Object)} key Key to set or hash of key-value pairs to set.\n * @param {*} [value] Value to set for the given key.\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.silent=false] Whether to trigger change events.\n * @since 3.0.0\n */\n 'set' (key, value, opts) {\n if (utils.isObject(key)) {\n opts = value\n }\n opts || (opts = {})\n if (opts.silent) {\n this._set('silent', true)\n }\n utils.set(this, key, value)\n if (!this._get('eventId')) {\n this._set('silent') // unset\n }\n },\n\n /**\n * Return a plain object representation of this record. If the class from\n * which this record was created has a Mapper, then {@link Mapper#toJSON} will\n * be called with this record instead.\n *\n * @example Record#toJSON\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user', {\n * schema: {\n * properties: {\n * name: { type: 'string' }\n * }\n * }\n * });\n *\n * const user = store.createRecord('user', {\n * name: 'John',\n * $$hashKey: '1234'\n * });\n * console.log('user: ' + JSON.stringify(user.toJSON()));\n *\n * @method Record#toJSON\n * @param {object} [opts] Configuration options.\n * @param {string[]} [opts.with] Array of relation names or relation fields\n * to include in the representation. Only available as an option if the class\n * from which this record was created has a Mapper and this record resides in\n * an instance of {@link DataStore}.\n * @returns {Object} Plain object representation of this record.\n * @since 3.0.0\n */\n toJSON (opts) {\n const mapper = this.constructor.mapper\n if (mapper) {\n return mapper.toJSON(this, opts)\n } else {\n const json = {}\n utils.forOwn(this, (prop, key) => {\n json[key] = utils.plainCopy(prop)\n })\n return json\n }\n },\n\n /**\n * Unset the value for a given key. Triggers change events on those properties\n * that have `track: true` in {@link Mapper#schema}.\n *\n * @example Record#unset\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user');\n *\n * const user = store.createRecord('user', {\n * name: 'John'\n * });\n * console.log('user: ' + JSON.stringify(user));\n *\n * user.unset('name');\n * console.log('user: ' + JSON.stringify(user));\n *\n * @method Record#unset\n * @param {string} key Key to unset.\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.silent=false] Whether to trigger change events.\n * @since 3.0.0\n */\n unset (key, opts) {\n this.set(key, undefined, opts)\n },\n\n /**\n * Validate this record based on its current properties.\n *\n * @example Record#validate\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user', {\n * schema: {\n * properties: {\n * name: { type: 'string' }\n * }\n * }\n * });\n * const user = store.createRecord('user', {\n * name: 1234\n * }, {\n * noValidate: true // this allows us to put the record into an invalid state\n * });\n * console.log('user validation: ' + JSON.stringify(user.validate()));\n * user.name = 'John';\n * console.log('user validation: ' + user.validate());\n *\n * @method Record#validate\n * @param {object} [opts] Configuration options. Passed to {@link Mapper#validate}.\n * @returns {*} Array of errors or `undefined` if no errors.\n * @since 3.0.0\n */\n validate (opts) {\n return this._mapper().validate(this, opts)\n }\n}, {\n creatingPath,\n noValidatePath,\n keepChangeHistoryPath,\n previousPath\n})\n\n/**\n * Allow records to emit events.\n *\n * An record's registered listeners are stored in the record's private data.\n */\nutils.eventify(\n Record.prototype,\n function () {\n return this._get('events')\n },\n function (value) {\n this._set('events', value)\n }\n)\n\n/**\n * Fired when a record changes. Only works for records that have tracked fields.\n * See {@link Record~changeListener} on how to listen for this event.\n *\n * @event Record#change\n * @see Record~changeListener\n */\n\n/**\n * Callback signature for the {@link Record#event:change} event.\n *\n * @example\n * function onChange (record, changes) {\n * // do something\n * }\n * record.on('change', onChange);\n *\n * @callback Record~changeListener\n * @param {Record} The Record that changed.\n * @param {object} The changes.\n * @see Record#event:change\n * @since 3.0.0\n */\n\n/**\n * Create a subclass of this Record:\n * @example Record.extend\n * const JSData = require('js-data');\n * const { Record } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomRecordClass extends Record {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customRecord = new CustomRecordClass();\n * console.log(customRecord.foo());\n * console.log(CustomRecordClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherRecordClass = Record.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherRecord = new OtherRecordClass();\n * console.log(otherRecord.foo());\n * console.log(OtherRecordClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherRecordClass () {\n * Record.call(this);\n * this.created_at = new Date().getTime();\n * }\n * Record.extend({\n * constructor: AnotherRecordClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const anotherRecord = new AnotherRecordClass();\n * console.log(anotherRecord.created_at);\n * console.log(anotherRecord.foo());\n * console.log(AnotherRecordClass.beep());\n *\n * @method Record.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this Record class.\n * @since 3.0.0\n */\n","export function sort (a, b, hashCode) {\n // Short-circuit comparison if a and b are strictly equal\n // This is absolutely necessary for indexed objects that\n // don't have the idAttribute field\n if (a === b) {\n return 0\n }\n if (hashCode) {\n a = hashCode(a)\n b = hashCode(b)\n }\n if ((a === null && b === null) || (a === undefined && b === undefined)) {\n return -1\n }\n\n if (a === null || a === undefined) {\n return -1\n }\n\n if (b === null || b === undefined) {\n return 1\n }\n\n if (a < b) {\n return -1\n }\n\n if (a > b) {\n return 1\n }\n\n return 0\n}\n\nexport function insertAt (array, index, value) {\n array.splice(index, 0, value)\n return array\n}\n\nexport function removeAt (array, index) {\n array.splice(index, 1)\n return array\n}\n\nexport function binarySearch (array, value, field) {\n let lo = 0\n let hi = array.length\n let compared\n let mid\n\n while (lo < hi) {\n mid = ((lo + hi) / 2) | 0\n compared = sort(value, array[mid], field)\n if (compared === 0) {\n return {\n found: true,\n index: mid\n }\n } else if (compared < 0) {\n hi = mid\n } else {\n lo = mid + 1\n }\n }\n\n return {\n found: false,\n index: hi\n }\n}\n","// Copyright (c) 2015, InternalFX.\n\n// Permission to use, copy, modify, and/or distribute this software for any purpose with or\n// without fee is hereby granted, provided that the above copyright notice and this permission\n// notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO\n// THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT\n// SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR\n// ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION\n// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE\n// USE OR PERFORMANCE OF THIS SOFTWARE.\n\n// Modifications\n// Copyright 2015-2016 Jason Dobry\n//\n// Summary of modifications:\n// Reworked dependencies so as to re-use code already in js-data\n// Removed unused code\nimport utils from '../../src/utils'\nimport {binarySearch, insertAt, removeAt} from './_utils'\n\nexport default function Index (fieldList, opts) {\n utils.classCallCheck(this, Index)\n fieldList || (fieldList = [])\n\n if (!utils.isArray(fieldList)) {\n throw new Error('fieldList must be an array.')\n }\n\n opts || (opts = {})\n this.fieldList = fieldList\n this.fieldGetter = opts.fieldGetter\n this.hashCode = opts.hashCode\n this.isIndex = true\n this.keys = []\n this.values = []\n}\n\nutils.addHiddenPropsToTarget(Index.prototype, {\n 'set' (keyList, value) {\n if (!utils.isArray(keyList)) {\n keyList = [keyList]\n }\n\n let key = keyList.shift() || undefined\n let pos = binarySearch(this.keys, key)\n\n if (keyList.length === 0) {\n if (pos.found) {\n let dataLocation = binarySearch(this.values[pos.index], value, this.hashCode)\n if (!dataLocation.found) {\n insertAt(this.values[pos.index], dataLocation.index, value)\n }\n } else {\n insertAt(this.keys, pos.index, key)\n insertAt(this.values, pos.index, [value])\n }\n } else {\n if (pos.found) {\n this.values[pos.index].set(keyList, value)\n } else {\n insertAt(this.keys, pos.index, key)\n let newIndex = new Index([], { hashCode: this.hashCode })\n newIndex.set(keyList, value)\n insertAt(this.values, pos.index, newIndex)\n }\n }\n },\n\n 'get' (keyList) {\n if (!utils.isArray(keyList)) {\n keyList = [keyList]\n }\n\n let key = keyList.shift() || undefined\n let pos = binarySearch(this.keys, key)\n\n if (keyList.length === 0) {\n if (pos.found) {\n if (this.values[pos.index].isIndex) {\n return this.values[pos.index].getAll()\n } else {\n return this.values[pos.index].slice()\n }\n } else {\n return []\n }\n } else {\n if (pos.found) {\n return this.values[pos.index].get(keyList)\n } else {\n return []\n }\n }\n },\n\n getAll (opts) {\n opts || (opts = {})\n let results = []\n const values = this.values\n if (opts.order === 'desc') {\n for (let i = values.length - 1; i >= 0; i--) {\n const value = values[i]\n if (value.isIndex) {\n results = results.concat(value.getAll(opts))\n } else {\n results = results.concat(value)\n }\n }\n } else {\n for (let i = 0; i < values.length; i++) {\n const value = values[i]\n if (value.isIndex) {\n results = results.concat(value.getAll(opts))\n } else {\n results = results.concat(value)\n }\n }\n }\n return results\n },\n\n visitAll (cb, thisArg) {\n this.values.forEach(function (value) {\n if (value.isIndex) {\n value.visitAll(cb, thisArg)\n } else {\n value.forEach(cb, thisArg)\n }\n })\n },\n\n between (leftKeys, rightKeys, opts) {\n opts || (opts = {})\n if (!utils.isArray(leftKeys)) {\n leftKeys = [leftKeys]\n }\n if (!utils.isArray(rightKeys)) {\n rightKeys = [rightKeys]\n }\n utils.fillIn(opts, {\n leftInclusive: true,\n rightInclusive: false,\n limit: undefined,\n offset: 0\n })\n\n let results = this._between(leftKeys, rightKeys, opts)\n\n if (opts.limit) {\n return results.slice(opts.offset, opts.limit + opts.offset)\n } else {\n return results.slice(opts.offset)\n }\n },\n\n _between (leftKeys, rightKeys, opts) {\n let results = []\n\n let leftKey = leftKeys.shift()\n let rightKey = rightKeys.shift()\n\n let pos\n\n if (leftKey !== undefined) {\n pos = binarySearch(this.keys, leftKey)\n } else {\n pos = {\n found: false,\n index: 0\n }\n }\n\n if (leftKeys.length === 0) {\n if (pos.found && opts.leftInclusive === false) {\n pos.index += 1\n }\n\n for (let i = pos.index; i < this.keys.length; i += 1) {\n if (rightKey !== undefined) {\n if (opts.rightInclusive) {\n if (this.keys[i] > rightKey) { break }\n } else {\n if (this.keys[i] >= rightKey) { break }\n }\n }\n\n if (this.values[i].isIndex) {\n results = results.concat(this.values[i].getAll())\n } else {\n results = results.concat(this.values[i])\n }\n\n if (opts.limit) {\n if (results.length >= (opts.limit + opts.offset)) {\n break\n }\n }\n }\n } else {\n for (let i = pos.index; i < this.keys.length; i += 1) {\n let currKey = this.keys[i]\n if (currKey > rightKey) { break }\n\n if (this.values[i].isIndex) {\n if (currKey === leftKey) {\n results = results.concat(this.values[i]._between(utils.copy(leftKeys), rightKeys.map(function () { return undefined }), opts))\n } else if (currKey === rightKey) {\n results = results.concat(this.values[i]._between(leftKeys.map(function () { return undefined }), utils.copy(rightKeys), opts))\n } else {\n results = results.concat(this.values[i].getAll())\n }\n } else {\n results = results.concat(this.values[i])\n }\n\n if (opts.limit) {\n if (results.length >= (opts.limit + opts.offset)) {\n break\n }\n }\n }\n }\n\n if (opts.limit) {\n return results.slice(0, opts.limit + opts.offset)\n } else {\n return results\n }\n },\n\n peek () {\n if (this.values.length) {\n if (this.values[0].isIndex) {\n return this.values[0].peek()\n } else {\n return this.values[0]\n }\n }\n return []\n },\n\n clear () {\n this.keys = []\n this.values = []\n },\n\n insertRecord (data) {\n let keyList = this.fieldList.map(function (field) {\n if (utils.isFunction(field)) {\n return field(data) || undefined\n } else {\n return data[field] || undefined\n }\n })\n this.set(keyList, data)\n },\n\n removeRecord (data) {\n let removed\n const isUnique = this.hashCode(data) !== undefined\n this.values.forEach((value, i) => {\n if (value.isIndex) {\n if (value.removeRecord(data)) {\n if (value.keys.length === 0) {\n removeAt(this.keys, i)\n removeAt(this.values, i)\n }\n removed = true\n return false\n }\n } else {\n let dataLocation = {}\n if (this.keys[i] === undefined || !isUnique) {\n for (let j = value.length - 1; j >= 0; j--) {\n if (value[j] === data) {\n dataLocation = {\n found: true,\n index: j\n }\n break\n }\n }\n } else if (isUnique) {\n dataLocation = binarySearch(value, data, this.hashCode)\n }\n if (dataLocation.found) {\n removeAt(value, dataLocation.index)\n if (value.length === 0) {\n removeAt(this.keys, i)\n removeAt(this.values, i)\n }\n removed = true\n return false\n }\n }\n })\n return removed ? data : undefined\n },\n\n updateRecord (data) {\n const removed = this.removeRecord(data)\n if (removed !== undefined) {\n this.insertRecord(data)\n }\n }\n})\n","import utils from './utils'\nimport Component from './Component'\nimport Query from './Query'\nimport Record from './Record'\nimport Index from '../lib/mindex/index'\n\nconst { noValidatePath } = Record\n\nconst DOMAIN = 'Collection'\n\nconst COLLECTION_DEFAULTS = {\n /**\n * Whether to call {@link Record#commit} on records that are added to the\n * collection and already exist in the collection.\n *\n * @name Collection#commitOnMerge\n * @type {boolean}\n * @default true\n */\n commitOnMerge: true,\n\n /**\n * Whether record events should bubble up and be emitted by the collection.\n *\n * @name Collection#emitRecordEvents\n * @type {boolean}\n * @default true\n */\n emitRecordEvents: true,\n\n /**\n * Field to be used as the unique identifier for records in this collection.\n * Defaults to `\"id\"` unless {@link Collection#mapper} is set, in which case\n * this will default to {@link Mapper#idAttribute}.\n *\n * @name Collection#idAttribute\n * @type {string}\n * @default \"id\"\n */\n idAttribute: 'id',\n\n /**\n * What to do when inserting a record into this Collection that shares a\n * primary key with a record already in this Collection.\n *\n * Possible values:\n * merge\n * replace\n * skip\n *\n * Merge:\n *\n * Recursively shallow copy properties from the new record onto the existing\n * record.\n *\n * Replace:\n *\n * Shallow copy top-level properties from the new record onto the existing\n * record. Any top-level own properties of the existing record that are _not_\n * on the new record will be removed.\n *\n * Skip:\n *\n * Ignore new record, keep existing record.\n *\n * @name Collection#onConflict\n * @type {string}\n * @default \"merge\"\n */\n onConflict: 'merge'\n}\n\n/**\n * An ordered set of {@link Record} instances.\n *\n * @example Collection#constructor\n * // import { Collection, Record } from 'js-data';\n * const JSData = require('js-data');\n * const {Collection, Record} = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const user1 = new Record({ id: 1 });\n * const user2 = new Record({ id: 2 });\n * const UserCollection = new Collection([user1, user2]);\n * console.log(UserCollection.get(1) === user1);\n *\n * @class Collection\n * @extends Component\n * @param {array} [records] Initial set of records to insert into the\n * collection.\n * @param {object} [opts] Configuration options.\n * @param {string} [opts.commitOnMerge] See {@link Collection#commitOnMerge}.\n * @param {string} [opts.idAttribute] See {@link Collection#idAttribute}.\n * @param {string} [opts.onConflict=\"merge\"] See {@link Collection#onConflict}.\n * @param {string} [opts.mapper] See {@link Collection#mapper}.\n * @since 3.0.0\n */\nfunction Collection (records, opts) {\n utils.classCallCheck(this, Collection)\n Component.call(this, opts)\n\n if (records && !utils.isArray(records)) {\n opts = records\n records = []\n }\n if (utils.isString(opts)) {\n opts = { idAttribute: opts }\n }\n\n // Default values for arguments\n records || (records = [])\n opts || (opts = {})\n\n Object.defineProperties(this, {\n /**\n * Default Mapper for this collection. Optional. If a Mapper is provided, then\n * the collection will use the {@link Mapper#idAttribute} setting, and will\n * wrap records in {@link Mapper#recordClass}.\n *\n * @example Collection#mapper\n * const JSData = require('js-data');\n * const {Collection, Mapper} = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * class MyMapperClass extends Mapper {\n * foo () { return 'bar'; }\n * }\n * const myMapper = new MyMapperClass({ name: 'myMapper' });\n * const collection = new Collection(null, { mapper: myMapper });\n *\n * @name Collection#mapper\n * @type {Mapper}\n * @default null\n * @since 3.0.0\n */\n mapper: {\n value: undefined,\n writable: true\n },\n // Query class used by this collection\n queryClass: {\n value: undefined,\n writable: true\n }\n })\n\n // Apply user-provided configuration\n utils.fillIn(this, opts)\n // Fill in any missing options with the defaults\n utils.fillIn(this, utils.copy(COLLECTION_DEFAULTS))\n\n if (!this.queryClass) {\n this.queryClass = Query\n }\n\n const idAttribute = this.recordId()\n\n Object.defineProperties(this, {\n /**\n * The main index, which uses @{link Collection#recordId} as the key.\n *\n * @name Collection#index\n * @type {Index}\n */\n index: {\n value: new Index([idAttribute], {\n hashCode (obj) {\n return utils.get(obj, idAttribute)\n }\n })\n },\n\n /**\n * Object that holds the secondary indexes of this collection.\n *\n * @name Collection#indexes\n * @type {Object.}\n */\n indexes: {\n value: {}\n }\n })\n\n // Insert initial data into the collection\n if (utils.isObject(records) || (utils.isArray(records) && records.length)) {\n this.add(records)\n }\n}\n\nexport default Component.extend({\n constructor: Collection,\n\n /**\n * Used to bind to events emitted by records in this Collection.\n *\n * @method Collection#_onRecordEvent\n * @since 3.0.0\n * @private\n * @param {...*} [arg] Args passed to {@link Collection#emit}.\n */\n _onRecordEvent (...args) {\n if (this.emitRecordEvents) {\n this.emit(...args)\n }\n },\n\n /**\n * Insert the provided record or records.\n *\n * If a record is already in the collection then the provided record will\n * either merge with or replace the existing record based on the value of the\n * `onConflict` option.\n *\n * The collection's secondary indexes will be updated as each record is\n * visited.\n *\n * @method Collection#add\n * @since 3.0.0\n * @param {(Object|Object[]|Record|Record[])} data The record or records to insert.\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.commitOnMerge=true] See {@link Collection#commitOnMerge}.\n * @param {boolean} [opts.noValidate] See {@link Record#noValidate}.\n * @param {string} [opts.onConflict] See {@link Collection#onConflict}.\n * @returns {(Object|Object[]|Record|Record[])} The added record or records.\n */\n add (records, opts) {\n // Default values for arguments\n opts || (opts = {})\n\n // Fill in \"opts\" with the Collection's configuration\n utils._(opts, this)\n records = this.beforeAdd(records, opts) || records\n\n // Track whether just one record or an array of records is being inserted\n let singular = false\n const idAttribute = this.recordId()\n if (!utils.isArray(records)) {\n if (utils.isObject(records)) {\n records = [records]\n singular = true\n } else {\n throw utils.err(`${DOMAIN}#add`, 'records')(400, 'object or array', records)\n }\n }\n\n // Map the provided records to existing records.\n // New records will be inserted. If any records map to existing records,\n // they will be merged into the existing records according to the onConflict\n // option.\n records = records.map((record) => {\n let id = this.recordId(record)\n // Grab existing record if there is one\n const existing = id === undefined ? id : this.get(id)\n // If the currently visited record is just a reference to an existing\n // record, then there is nothing to be done. Exit early.\n if (record === existing) {\n return existing\n }\n\n if (existing) {\n // Here, the currently visited record corresponds to a record already\n // in the collection, so we need to merge them\n const onConflict = opts.onConflict || this.onConflict\n if (onConflict !== 'merge' && onConflict !== 'replace' && onConflict !== 'skip') {\n throw utils.err(`${DOMAIN}#add`, 'opts.onConflict')(400, 'one of (merge, replace, skip)', onConflict, true)\n }\n const existingNoValidate = existing._get(noValidatePath)\n if (opts.noValidate) {\n // Disable validation\n existing._set(noValidatePath, true)\n }\n if (onConflict === 'merge') {\n utils.deepMixIn(existing, record)\n } else if (onConflict === 'replace') {\n utils.forOwn(existing, (value, key) => {\n if (key !== idAttribute && record[key] === undefined) {\n existing[key] = undefined\n }\n })\n existing.set(record)\n } // else if(onConflict === 'skip'){ do nothing }\n\n if (opts.noValidate) {\n // Restore previous `noValidate` value\n existing._set(noValidatePath, existingNoValidate)\n }\n record = existing\n if (opts.commitOnMerge && utils.isFunction(record.commit)) {\n record.commit()\n }\n // Update all indexes in the collection\n this.updateIndexes(record)\n } else {\n // Here, the currently visted record does not correspond to any record\n // in the collection, so (optionally) instantiate this record and insert\n // it into the collection\n record = this.mapper ? this.mapper.createRecord(record, opts) : record\n this.index.insertRecord(record)\n utils.forOwn(this.indexes, function (index, name) {\n index.insertRecord(record)\n })\n if (record && utils.isFunction(record.on)) {\n record.on('all', this._onRecordEvent, this)\n }\n }\n return record\n })\n // Finally, return the inserted data\n const result = singular ? records[0] : records\n if (!opts.silent) {\n this.emit('add', result)\n }\n return this.afterAdd(records, opts, result) || result\n },\n\n /**\n * Lifecycle hook called by {@link Collection#add}. If this method returns a\n * value then {@link Collection#add} will return that same value.\n *\n * @method Collection#method\n * @since 3.0.0\n * @param {(Object|Object[]|Record|Record[])} result The record or records\n * that were added to this Collection by {@link Collection#add}.\n * @param {object} opts The `opts` argument passed to {@link Collection#add}.\n */\n afterAdd () {},\n\n /**\n * Lifecycle hook called by {@link Collection#remove}. If this method returns\n * a value then {@link Collection#remove} will return that same value.\n *\n * @method Collection#afterRemove\n * @since 3.0.0\n * @param {(string|number)} id The `id` argument passed to {@link Collection#remove}.\n * @param {object} opts The `opts` argument passed to {@link Collection#remove}.\n * @param {object} record The result that will be returned by {@link Collection#remove}.\n */\n afterRemove () {},\n\n /**\n * Lifecycle hook called by {@link Collection#removeAll}. If this method\n * returns a value then {@link Collection#removeAll} will return that same\n * value.\n *\n * @method Collection#afterRemoveAll\n * @since 3.0.0\n * @param {object} query The `query` argument passed to {@link Collection#removeAll}.\n * @param {object} opts The `opts` argument passed to {@link Collection#removeAll}.\n * @param {object} records The result that will be returned by {@link Collection#removeAll}.\n */\n afterRemoveAll () {},\n\n /**\n * Lifecycle hook called by {@link Collection#add}. If this method returns a\n * value then the `records` argument in {@link Collection#add} will be\n * re-assigned to the returned value.\n *\n * @method Collection#beforeAdd\n * @since 3.0.0\n * @param {(Object|Object[]|Record|Record[])} records The `records` argument passed to {@link Collection#add}.\n * @param {object} opts The `opts` argument passed to {@link Collection#add}.\n */\n beforeAdd () {},\n\n /**\n * Lifecycle hook called by {@link Collection#remove}.\n *\n * @method Collection#beforeRemove\n * @since 3.0.0\n * @param {(string|number)} id The `id` argument passed to {@link Collection#remove}.\n * @param {object} opts The `opts` argument passed to {@link Collection#remove}.\n */\n beforeRemove () {},\n\n /**\n * Lifecycle hook called by {@link Collection#removeAll}.\n *\n * @method Collection#beforeRemoveAll\n * @since 3.0.0\n * @param {object} query The `query` argument passed to {@link Collection#removeAll}.\n * @param {object} opts The `opts` argument passed to {@link Collection#removeAll}.\n */\n beforeRemoveAll () {},\n\n /**\n * Find all records between two boundaries.\n *\n * Shortcut for `collection.query().between(18, 30, { index: 'age' }).run()`\n *\n * @example\n * // Get all users ages 18 to 30\n * const users = collection.between(18, 30, { index: 'age' });\n *\n * @example\n * // Same as above\n * const users = collection.between([18], [30], { index: 'age' });\n *\n * @method Collection#between\n * @since 3.0.0\n * @param {array} leftKeys Keys defining the left boundary.\n * @param {array} rightKeys Keys defining the right boundary.\n * @param {object} [opts] Configuration options.\n * @param {string} [opts.index] Name of the secondary index to use in the\n * query. If no index is specified, the main index is used.\n * @param {boolean} [opts.leftInclusive=true] Whether to include records\n * on the left boundary.\n * @param {boolean} [opts.rightInclusive=false] Whether to include records\n * on the left boundary.\n * @param {boolean} [opts.limit] Limit the result to a certain number.\n * @param {boolean} [opts.offset] The number of resulting records to skip.\n * @returns {Object[]|Record[]} The result.\n */\n between (leftKeys, rightKeys, opts) {\n return this.query().between(leftKeys, rightKeys, opts).run()\n },\n\n /**\n * Create a new secondary index on the contents of the collection.\n *\n * @example\n * // Index users by age\n * collection.createIndex('age');\n *\n * @example\n * // Index users by status and role\n * collection.createIndex('statusAndRole', ['status', 'role']);\n *\n * @method Collection#createIndex\n * @since 3.0.0\n * @param {string} name The name of the new secondary index.\n * @param {string[]} [fieldList] Array of field names to use as the key or\n * compound key of the new secondary index. If no fieldList is provided, then\n * the name will also be the field that is used to index the collection.\n */\n createIndex (name, fieldList, opts) {\n if (utils.isString(name) && fieldList === undefined) {\n fieldList = [name]\n }\n opts || (opts = {})\n opts.hashCode || (opts.hashCode = (obj) => this.recordId(obj))\n const index = this.indexes[name] = new Index(fieldList, opts)\n this.index.visitAll(index.insertRecord, index)\n },\n\n /**\n * Find the record or records that match the provided query or pass the\n * provided filter function.\n *\n * Shortcut for `collection.query().filter(queryOrFn[, thisArg]).run()`\n *\n * @example Collection#filter\n * const JSData = require('js-data');\n * const { Collection } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const collection = new Collection([\n * { id: 1, status: 'draft', created_at_timestamp: new Date().getTime() }\n * ]);\n *\n * // Get the draft posts created less than three months ago\n * let posts = collection.filter({\n * where: {\n * status: {\n * '==': 'draft'\n * },\n * created_at_timestamp: {\n * '>=': (new Date().getTime() - (1000 \\* 60 \\* 60 \\* 24 \\* 30 \\* 3)) // 3 months ago\n * }\n * }\n * });\n * console.log(posts);\n *\n * // Use a custom filter function\n * posts = collection.filter((post) => post.id % 2 === 0);\n *\n * @method Collection#filter\n * @param {(Object|Function)} [queryOrFn={}] Selection query or filter\n * function.\n * @param {object} [thisArg] Context to which to bind `queryOrFn` if\n * `queryOrFn` is a function.\n * @returns {Array} The result.\n * @see query\n * @since 3.0.0\n */\n filter (query, thisArg) {\n return this.query().filter(query, thisArg).run()\n },\n\n /**\n * Iterate over all records.\n *\n * @example\n * collection.forEach(function (record) {\n * // do something\n * });\n *\n * @method Collection#forEach\n * @since 3.0.0\n * @param {Function} forEachFn Iteration function.\n * @param {*} [thisArg] Context to which to bind `forEachFn`.\n * @returns {Array} The result.\n */\n forEach (cb, thisArg) {\n this.index.visitAll(cb, thisArg)\n },\n\n /**\n * Get the record with the given id.\n *\n * @method Collection#get\n * @since 3.0.0\n * @param {(string|number)} id The primary key of the record to get.\n * @returns {(Object|Record)} The record with the given id.\n */\n get (id) {\n const instances = id === undefined ? [] : this.query().get(id).run()\n return instances.length ? instances[0] : undefined\n },\n\n /**\n * Find the record or records that match the provided keyLists.\n *\n * Shortcut for `collection.query().getAll(keyList1, keyList2, ...).run()`\n *\n * @example\n * // Get the posts where \"status\" is \"draft\" or \"inReview\"\n * const posts = collection.getAll('draft', 'inReview', { index: 'status' });\n *\n * @example\n * // Same as above\n * const posts = collection.getAll(['draft'], ['inReview'], { index: 'status' });\n *\n * @method Collection#getAll\n * @since 3.0.0\n * @param {...Array} [keyList] Provide one or more keyLists, and all\n * records matching each keyList will be retrieved. If no keyLists are\n * provided, all records will be returned.\n * @param {object} [opts] Configuration options.\n * @param {string} [opts.index] Name of the secondary index to use in the\n * query. If no index is specified, the main index is used.\n * @returns {Array} The result.\n */\n getAll (...args) {\n return this.query().getAll(...args).run()\n },\n\n /**\n * Return the index with the given name. If no name is provided, return the\n * main index. Throws an error if the specified index does not exist.\n *\n * @method Collection#getIndex\n * @since 3.0.0\n * @param {string} [name] The name of the index to retrieve.\n */\n getIndex (name) {\n const index = name ? this.indexes[name] : this.index\n if (!index) {\n throw utils.err(`${DOMAIN}#getIndex`, name)(404, 'index')\n }\n return index\n },\n\n /**\n * Limit the result.\n *\n * Shortcut for `collection.query().limit(maximumNumber).run()`\n *\n * @example\n * const posts = collection.limit(10);\n *\n * @method Collection#limit\n * @since 3.0.0\n * @param {number} num The maximum number of records to keep in the result.\n * @returns {Array} The result.\n */\n limit (num) {\n return this.query().limit(num).run()\n },\n\n /**\n * Apply a mapping function to all records.\n *\n * @example\n * const names = collection.map((user) => user.name);\n *\n * @method Collection#map\n * @since 3.0.0\n * @param {Function} mapFn Mapping function.\n * @param {*} [thisArg] Context to which to bind `mapFn`.\n * @returns {Array} The result of the mapping.\n */\n map (cb, thisArg) {\n const data = []\n this.index.visitAll(function (value) {\n data.push(cb.call(thisArg, value))\n })\n return data\n },\n\n /**\n * Return the result of calling the specified function on each record in this\n * collection's main index.\n *\n * @method Collection#mapCall\n * @since 3.0.0\n * @param {string} funcName Name of function to call\n * @parama {...*} [args] Remaining arguments to be passed to the function.\n * @returns {Array} The result.\n */\n mapCall (funcName, ...args) {\n const data = []\n this.index.visitAll(function (record) {\n data.push(record[funcName](...args))\n })\n return data\n },\n\n /**\n * Return all \"unsaved\" (not uniquely identifiable) records in this colleciton.\n *\n * @method Collection#prune\n * @param {object} [opts] Configuration options, passed to {@link Collection#removeAll}.\n * @since 3.0.0\n * @returns {Array} The removed records, if any.\n */\n prune (opts) {\n return this.removeAll(this.unsaved(), opts)\n },\n\n /**\n * Create a new query to be executed against the contents of the collection.\n * The result will be all or a subset of the contents of the collection.\n *\n * @example\n * // Grab page 2 of users between ages 18 and 30\n * collection.query()\n * .between(18, 30, { index: 'age' }) // between ages 18 and 30\n * .skip(10) // second page\n * .limit(10) // page size\n * .run();\n *\n * @method Collection#query\n * @since 3.0.0\n * @returns {Query} New query object.\n */\n query () {\n const Ctor = this.queryClass\n return new Ctor(this)\n },\n\n /**\n * Return the primary key of the given, or if no record is provided, return the\n * name of the field that holds the primary key of records in this Collection.\n *\n * @method Collection#recordId\n * @since 3.0.0\n * @param {(Object|Record)} [record] The record whose primary key is to be\n * returned.\n * @returns {(string|number)} Primary key or name of field that holds primary\n * key.\n */\n recordId (record) {\n if (record) {\n return utils.get(record, this.recordId())\n }\n return this.mapper ? this.mapper.idAttribute : this.idAttribute\n },\n\n /**\n * Reduce the data in the collection to a single value and return the result.\n *\n * @example\n * const totalVotes = collection.reduce((prev, record) => {\n * return prev + record.upVotes + record.downVotes;\n * }, 0);\n *\n * @method Collection#reduce\n * @since 3.0.0\n * @param {Function} cb Reduction callback.\n * @param {*} initialValue Initial value of the reduction.\n * @returns {*} The result.\n */\n reduce (cb, initialValue) {\n const data = this.getAll()\n return data.reduce(cb, initialValue)\n },\n\n /**\n * Remove the record with the given id from this Collection.\n *\n * @method Collection#remove\n * @since 3.0.0\n * @param {(string|number|object|Record)} idOrRecord The primary key of the\n * record to be removed, or a reference to the record that is to be removed.\n * @param {object} [opts] Configuration options.\n * @returns {Object|Record} The removed record, if any.\n */\n remove (idOrRecord, opts) {\n // Default values for arguments\n opts || (opts = {})\n this.beforeRemove(idOrRecord, opts)\n let record = utils.isSorN(idOrRecord) ? this.get(idOrRecord) : idOrRecord\n\n // The record is in the collection, remove it\n if (utils.isObject(record)) {\n record = this.index.removeRecord(record)\n if (record) {\n utils.forOwn(this.indexes, function (index, name) {\n index.removeRecord(record)\n })\n if (utils.isFunction(record.off)) {\n record.off('all', this._onRecordEvent, this)\n if (!opts.silent) {\n this.emit('remove', record)\n }\n }\n }\n }\n return this.afterRemove(idOrRecord, opts, record) || record\n },\n\n /**\n * Remove from this collection the given records or the records selected by\n * the given \"query\".\n *\n * @method Collection#removeAll\n * @since 3.0.0\n * @param {Object|Object[]|Record[]} [queryOrRecords={}] Records to be removed or selection query. See {@link query}.\n * @param {object} [queryOrRecords.where] See {@link query.where}.\n * @param {number} [queryOrRecords.offset] See {@link query.offset}.\n * @param {number} [queryOrRecords.limit] See {@link query.limit}.\n * @param {string|Array[]} [queryOrRecords.orderBy] See {@link query.orderBy}.\n * @param {object} [opts] Configuration options.\n * @returns {(Object[]|Record[])} The removed records, if any.\n */\n removeAll (queryOrRecords, opts) {\n // Default values for arguments\n opts || (opts = {})\n this.beforeRemoveAll(queryOrRecords, opts)\n let records = utils.isArray(queryOrRecords) ? queryOrRecords.slice() : this.filter(queryOrRecords)\n\n // Remove each selected record from the collection\n const optsCopy = utils.plainCopy(opts)\n optsCopy.silent = true\n records = records\n .map((record) => this.remove(record, optsCopy))\n .filter((record) => record)\n if (!opts.silent) {\n this.emit('remove', records)\n }\n return this.afterRemoveAll(queryOrRecords, opts, records) || records\n },\n\n /**\n * Skip a number of results.\n *\n * Shortcut for `collection.query().skip(numberToSkip).run()`\n *\n * @example\n * const posts = collection.skip(10);\n *\n * @method Collection#skip\n * @since 3.0.0\n * @param {number} num The number of records to skip.\n * @returns {Array} The result.\n */\n skip (num) {\n return this.query().skip(num).run()\n },\n\n /**\n * Return the plain JSON representation of all items in this collection.\n * Assumes records in this collection have a toJSON method.\n *\n * @method Collection#toJSON\n * @since 3.0.0\n * @param {object} [opts] Configuration options.\n * @param {string[]} [opts.with] Array of relation names or relation fields\n * to include in the representation.\n * @returns {Array} The records.\n */\n toJSON (opts) {\n return this.mapCall('toJSON', opts)\n },\n\n /**\n * Return all \"unsaved\" (not uniquely identifiable) records in this colleciton.\n *\n * @method Collection#unsaved\n * @since 3.0.0\n * @returns {Array} The unsaved records, if any.\n */\n unsaved (opts) {\n return this.index.get()\n },\n\n /**\n * Update a record's position in a single index of this collection. See\n * {@link Collection#updateIndexes} to update a record's position in all\n * indexes at once.\n *\n * @method Collection#updateIndex\n * @since 3.0.0\n * @param {object} record The record to update.\n * @param {object} [opts] Configuration options.\n * @param {string} [opts.index] The index in which to update the record's\n * position. If you don't specify an index then the record will be updated\n * in the main index.\n */\n updateIndex (record, opts) {\n opts || (opts = {})\n this.getIndex(opts.index).updateRecord(record)\n },\n\n /**\n * Updates all indexes in this collection for the provided record. Has no\n * effect if the record is not in the collection.\n *\n * @method Collection#updateIndexes\n * @since 3.0.0\n * @param {object} record TODO\n */\n updateIndexes (record) {\n this.index.updateRecord(record)\n utils.forOwn(this.indexes, function (index, name) {\n index.updateRecord(record)\n })\n }\n})\n\n/**\n * Fired when a record changes. Only works for records that have tracked changes.\n * See {@link Collection~changeListener} on how to listen for this event.\n *\n * @event Collection#change\n * @see Collection~changeListener\n */\n\n/**\n * Callback signature for the {@link Collection#event:change} event.\n *\n * @example\n * function onChange (record, changes) {\n * // do something\n * }\n * collection.on('change', onChange);\n *\n * @callback Collection~changeListener\n * @param {Record} The Record that changed.\n * @param {object} The changes.\n * @see Collection#event:change\n * @since 3.0.0\n */\n\n/**\n * Fired when one or more records are added to the Collection. See\n * {@link Collection~addListener} on how to listen for this event.\n *\n * @event Collection#add\n * @see Collection~addListener\n * @see Collection#event:add\n * @see Collection#add\n */\n\n/**\n * Callback signature for the {@link Collection#event:add} event.\n *\n * @example\n * function onAdd (recordOrRecords) {\n * // do something\n * }\n * collection.on('add', onAdd);\n *\n * @callback Collection~addListener\n * @param {Record|Record[]} The Record or Records that were added.\n * @see Collection#event:add\n * @see Collection#add\n * @since 3.0.0\n */\n\n/**\n * Fired when one or more records are removed from the Collection. See\n * {@link Collection~removeListener} for how to listen for this event.\n *\n * @event Collection#remove\n * @see Collection~removeListener\n * @see Collection#event:remove\n * @see Collection#remove\n * @see Collection#removeAll\n */\n\n/**\n * Callback signature for the {@link Collection#event:remove} event.\n *\n * @example\n * function onRemove (recordsOrRecords) {\n * // do something\n * }\n * collection.on('remove', onRemove);\n *\n * @callback Collection~removeListener\n * @param {Record|Record[]} Record or Records that were removed.\n * @see Collection#event:remove\n * @see Collection#remove\n * @see Collection#removeAll\n * @since 3.0.0\n */\n\n/**\n * Create a subclass of this Collection:\n * @example Collection.extend\n * const JSData = require('js-data');\n * const { Collection } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomCollectionClass extends Collection {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customCollection = new CustomCollectionClass();\n * console.log(customCollection.foo());\n * console.log(CustomCollectionClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherCollectionClass = Collection.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherCollection = new OtherCollectionClass();\n * console.log(otherCollection.foo());\n * console.log(OtherCollectionClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherCollectionClass () {\n * Collection.call(this);\n * this.created_at = new Date().getTime();\n * }\n * Collection.extend({\n * constructor: AnotherCollectionClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const anotherCollection = new AnotherCollectionClass();\n * console.log(anotherCollection.created_at);\n * console.log(anotherCollection.foo());\n * console.log(AnotherCollectionClass.beep());\n *\n * @method Collection.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this Collection class.\n * @since 3.0.0\n */\n","import utils from './utils'\nimport Component from './Component'\n\nconst DOMAIN = 'Schema'\n\n/**\n * A function map for each of the seven primitive JSON types defined by the core specification.\n * Each function will check a given value and return true or false if the value is an instance of that type.\n * ```\n * types.integer(1) // returns true\n * types.string({}) // returns false\n * ```\n * http://json-schema.org/latest/json-schema-core.html#anchor8\n * @name Schema.types\n * @type {object}\n */\nconst types = {\n array: utils.isArray,\n boolean: utils.isBoolean,\n integer: utils.isInteger,\n 'null': utils.isNull,\n number: utils.isNumber,\n object: utils.isObject,\n string: utils.isString\n}\n\n/**\n * @ignore\n */\nconst segmentToString = function (segment, prev) {\n let str = ''\n if (segment) {\n if (utils.isNumber(segment)) {\n str += `[${segment}]`\n } else if (prev) {\n str += `.${segment}`\n } else {\n str += `${segment}`\n }\n }\n return str\n}\n\n/**\n * @ignore\n */\nconst makePath = function (opts) {\n opts || (opts = {})\n let path = ''\n const segments = opts.path || []\n segments.forEach(function (segment) {\n path += segmentToString(segment, path)\n })\n path += segmentToString(opts.prop, path)\n return path\n}\n\n/**\n * @ignore\n */\nconst makeError = function (actual, expected, opts) {\n return {\n expected,\n actual: '' + actual,\n path: makePath(opts)\n }\n}\n\n/**\n * @ignore\n */\nconst addError = function (actual, expected, opts, errors) {\n errors.push(makeError(actual, expected, opts))\n}\n\n/**\n * @ignore\n */\nconst maxLengthCommon = function (keyword, value, schema, opts) {\n const max = schema[keyword]\n if (value.length > max) {\n return makeError(value.length, `length no more than ${max}`, opts)\n }\n}\n\n/**\n * @ignore\n */\nconst minLengthCommon = function (keyword, value, schema, opts) {\n const min = schema[keyword]\n if (value.length < min) {\n return makeError(value.length, `length no less than ${min}`, opts)\n }\n}\n\n/**\n * A map of all object member validation functions for each keyword defined in the JSON Schema.\n * @name Schema.validationKeywords\n * @type {object}\n */\nconst validationKeywords = {\n /**\n * Validates the provided value against all schemas defined in the Schemas `allOf` keyword.\n * The instance is valid against if and only if it is valid against all the schemas declared in the Schema's value.\n *\n * The value of this keyword MUST be an array. This array MUST have at least one element.\n * Each element of this array MUST be a valid JSON Schema.\n *\n * see http://json-schema.org/latest/json-schema-validation.html#anchor82\n *\n * @name Schema.validationKeywords.allOf\n * @method\n * @param {*} value Value to be validated.\n * @param {object} schema Schema containing the `allOf` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n allOf (value, schema, opts) {\n let allErrors = []\n schema.allOf.forEach(function (_schema) {\n allErrors = allErrors.concat(validate(value, _schema, opts) || [])\n })\n return allErrors.length ? allErrors : undefined\n },\n\n /**\n * Validates the provided value against all schemas defined in the Schemas `anyOf` keyword.\n * The instance is valid against this keyword if and only if it is valid against\n * at least one of the schemas in this keyword's value.\n *\n * The value of this keyword MUST be an array. This array MUST have at least one element.\n * Each element of this array MUST be an object, and each object MUST be a valid JSON Schema.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor85\n *\n * @name Schema.validationKeywords.anyOf\n * @method\n * @param {*} value Value to be validated.\n * @param {object} schema Schema containing the `anyOf` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n anyOf (value, schema, opts) {\n let validated = false\n let allErrors = []\n schema.anyOf.forEach(function (_schema) {\n const errors = validate(value, _schema, opts)\n if (errors) {\n allErrors = allErrors.concat(errors)\n } else {\n validated = true\n }\n })\n return validated ? undefined : allErrors\n },\n\n /**\n * http://json-schema.org/latest/json-schema-validation.html#anchor70\n *\n * @name Schema.validationKeywords.dependencies\n * @method\n * @param {*} value TODO\n * @param {object} schema TODO\n * @param {object} opts TODO\n */\n dependencies (value, schema, opts) {\n // TODO\n },\n\n /**\n * Validates the provided value against an array of possible values defined by the Schema's `enum` keyword\n * Validation succeeds if the value is deeply equal to one of the values in the array.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor76\n *\n * @name Schema.validationKeywords.enum\n * @method\n * @param {*} value Value to validate\n * @param {object} schema Schema containing the `enum` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n enum (value, schema, opts) {\n const possibleValues = schema['enum']\n if (utils.findIndex(possibleValues, (item) => utils.deepEqual(item, value)) === -1) {\n return makeError(value, `one of (${possibleValues.join(', ')})`, opts)\n }\n },\n\n /**\n * Validates each of the provided array values against a schema or an array of schemas defined by the Schema's `items` keyword\n * see http://json-schema.org/latest/json-schema-validation.html#anchor37 for validation rules.\n *\n * @name Schema.validationKeywords.items\n * @method\n * @param {*} value Array to be validated.\n * @param {object} schema Schema containing the items keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n items (value, schema, opts) {\n opts || (opts = {})\n // TODO: additionalItems\n let items = schema.items\n let errors = []\n const checkingTuple = utils.isArray(items)\n const length = value.length\n for (var prop = 0; prop < length; prop++) {\n if (checkingTuple) {\n // Validating a tuple, instead of just checking each item against the\n // same schema\n items = schema.items[prop]\n }\n opts.prop = prop\n errors = errors.concat(validate(value[prop], items, opts) || [])\n }\n return errors.length ? errors : undefined\n },\n\n /**\n * Validates the provided number against a maximum value defined by the Schema's `maximum` keyword\n * Validation succeeds if the value is a number, and is less than, or equal to, the value of this keyword.\n * http://json-schema.org/latest/json-schema-validation.html#anchor17\n *\n * @name Schema.validationKeywords.maximum\n * @method\n * @param {*} value Number to validate against the keyword.\n * @param {object} schema Schema containing the `maximum` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n maximum (value, schema, opts) {\n // Must be a number\n const maximum = schema.maximum\n // Must be a boolean\n // Depends on maximum\n // default: false\n const exclusiveMaximum = schema.exclusiveMaximum\n if (typeof value === typeof maximum && !(exclusiveMaximum ? maximum > value : maximum >= value)) {\n return exclusiveMaximum\n ? makeError(value, `no more than nor equal to ${maximum}`, opts)\n : makeError(value, `no more than ${maximum}`, opts)\n }\n },\n\n /**\n * Validates the length of the provided array against a maximum value defined by the Schema's `maxItems` keyword.\n * Validation succeeds if the length of the array is less than, or equal to the value of this keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor42\n *\n * @name Schema.validationKeywords.maxItems\n * @method\n * @param {*} value Array to be validated.\n * @param {object} schema Schema containing the `maxItems` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n maxItems (value, schema, opts) {\n if (utils.isArray(value)) {\n return maxLengthCommon('maxItems', value, schema, opts)\n }\n },\n\n /**\n * Validates the length of the provided string against a maximum value defined in the Schema's `maxLength` keyword.\n * Validation succeeds if the length of the string is less than, or equal to the value of this keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor26\n *\n * @name Schema.validationKeywords.maxLength\n * @method\n * @param {*} value String to be validated.\n * @param {object} schema Schema containing the `maxLength` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n maxLength (value, schema, opts) {\n return maxLengthCommon('maxLength', value, schema, opts)\n },\n\n /**\n * Validates the count of the provided object's properties against a maximum value defined in the Schema's `maxProperties` keyword.\n * Validation succeeds if the object's property count is less than, or equal to the value of this keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor54\n *\n * @name Schema.validationKeywords.maxProperties\n * @method\n * @param {*} value Object to be validated.\n * @param {object} schema Schema containing the `maxProperties` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n maxProperties (value, schema, opts) {\n // validate only objects\n if (!utils.isObject(value)) return\n const maxProperties = schema.maxProperties\n const length = Object.keys(value).length\n if (length > maxProperties) {\n return makeError(length, `no more than ${maxProperties} properties`, opts)\n }\n },\n\n /**\n * Validates the provided value against a minimum value defined by the Schema's `minimum` keyword\n * Validation succeeds if the value is a number and is greater than, or equal to, the value of this keyword.\n * http://json-schema.org/latest/json-schema-validation.html#anchor21\n *\n * @name Schema.validationKeywords.minimum\n * @method\n * @param {*} value Number to validate against the keyword.\n * @param {object} schema Schema containing the `minimum` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n minimum (value, schema, opts) {\n // Must be a number\n const minimum = schema.minimum\n // Must be a boolean\n // Depends on minimum\n // default: false\n const exclusiveMinimum = schema.exclusiveMinimum\n if (typeof value === typeof minimum && !(exclusiveMinimum ? value > minimum : value >= minimum)) {\n return exclusiveMinimum\n ? makeError(value, `no less than nor equal to ${minimum}`, opts)\n : makeError(value, `no less than ${minimum}`, opts)\n }\n },\n\n /**\n * Validates the length of the provided array against a minimum value defined by the Schema's `minItems` keyword.\n * Validation succeeds if the length of the array is greater than, or equal to the value of this keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor45\n *\n * @name Schema.validationKeywords.minItems\n * @method\n * @param {*} value Array to be validated.\n * @param {object} schema Schema containing the `minItems` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n minItems (value, schema, opts) {\n if (utils.isArray(value)) {\n return minLengthCommon('minItems', value, schema, opts)\n }\n },\n\n /**\n * Validates the length of the provided string against a minimum value defined in the Schema's `minLength` keyword.\n * Validation succeeds if the length of the string is greater than, or equal to the value of this keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor29\n *\n * @name Schema.validationKeywords.minLength\n * @method\n * @param {*} value String to be validated.\n * @param {object} schema Schema containing the `minLength` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n minLength (value, schema, opts) {\n return minLengthCommon('minLength', value, schema, opts)\n },\n\n /**\n * Validates the count of the provided object's properties against a minimum value defined in the Schema's `minProperties` keyword.\n * Validation succeeds if the object's property count is greater than, or equal to the value of this keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor57\n *\n * @name Schema.validationKeywords.minProperties\n * @method\n * @param {*} value Object to be validated.\n * @param {object} schema Schema containing the `minProperties` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n minProperties (value, schema, opts) {\n // validate only objects\n if (!utils.isObject(value)) return\n const minProperties = schema.minProperties\n const length = Object.keys(value).length\n if (length < minProperties) {\n return makeError(length, `no more than ${minProperties} properties`, opts)\n }\n },\n\n /**\n * Validates the provided number is a multiple of the number defined in the Schema's `multipleOf` keyword.\n * Validation succeeds if the number can be divided equally into the value of this keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor14\n *\n * @name Schema.validationKeywords.multipleOf\n * @method\n * @param {*} value Number to be validated.\n * @param {object} schema Schema containing the `multipleOf` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n multipleOf (value, schema, opts) {\n const multipleOf = schema.multipleOf\n if (utils.isNumber(value)) {\n if ((value / multipleOf) % 1 !== 0) {\n return makeError(value, `multipleOf ${multipleOf}`, opts)\n }\n }\n },\n\n /**\n * Validates the provided value is not valid with any of the schemas defined in the Schema's `not` keyword.\n * An instance is valid against this keyword if and only if it is NOT valid against the schemas in this keyword's value.\n *\n * see http://json-schema.org/latest/json-schema-validation.html#anchor91\n * @name Schema.validationKeywords.not\n * @method\n * @param {*} value to be checked.\n * @param {object} schema Schema containing the not keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n not (value, schema, opts) {\n if (!validate(value, schema.not, opts)) {\n // TODO: better messaging\n return makeError('succeeded', 'should have failed', opts)\n }\n },\n\n /**\n * Validates the provided value is valid with one and only one of the schemas defined in the Schema's `oneOf` keyword.\n * An instance is valid against this keyword if and only if it is valid against a single schemas in this keyword's value.\n *\n * see http://json-schema.org/latest/json-schema-validation.html#anchor88\n * @name Schema.validationKeywords.oneOf\n * @method\n * @param {*} value to be checked.\n * @param {object} schema Schema containing the `oneOf` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n oneOf (value, schema, opts) {\n let validated = false\n let allErrors = []\n schema.oneOf.forEach(function (_schema) {\n const errors = validate(value, _schema, opts)\n if (errors) {\n allErrors = allErrors.concat(errors)\n } else if (validated) {\n allErrors = [makeError('valid against more than one', 'valid against only one', opts)]\n validated = false\n return false\n } else {\n validated = true\n }\n })\n return validated ? undefined : allErrors\n },\n\n /**\n * Validates the provided string matches a pattern defined in the Schema's `pattern` keyword.\n * Validation succeeds if the string is a match of the regex value of this keyword.\n *\n * see http://json-schema.org/latest/json-schema-validation.html#anchor33\n * @name Schema.validationKeywords.pattern\n * @method\n * @param {*} value String to be validated.\n * @param {object} schema Schema containing the `pattern` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n pattern (value, schema, opts) {\n const pattern = schema.pattern\n if (utils.isString(value) && !value.match(pattern)) {\n return makeError(value, pattern, opts)\n }\n },\n\n /**\n * Validates the provided object's properties against a map of values defined in the Schema's `properties` keyword.\n * Validation succeeds if the object's property are valid with each of the schema's in the provided map.\n * Validation also depends on the additionalProperties and or patternProperties.\n *\n * see http://json-schema.org/latest/json-schema-validation.html#anchor64 for more info.\n *\n * @name Schema.validationKeywords.properties\n * @method\n * @param {*} value Object to be validated.\n * @param {object} schema Schema containing the `properties` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n properties (value, schema, opts) {\n opts || (opts = {})\n\n if (utils.isArray(value)) {\n return\n }\n\n // Can be a boolean or an object\n // Technically the default is an \"empty schema\", but here \"true\" is\n // functionally the same\n const additionalProperties = schema.additionalProperties === undefined ? true : schema.additionalProperties\n const validated = []\n // \"p\": The property set from \"properties\".\n // Default is an object\n const properties = schema.properties || {}\n // \"pp\": The property set from \"patternProperties\".\n // Default is an object\n const patternProperties = schema.patternProperties || {}\n let errors = []\n\n utils.forOwn(properties, function (_schema, prop) {\n opts.prop = prop\n errors = errors.concat(validate(value[prop], _schema, opts) || [])\n validated.push(prop)\n })\n\n const toValidate = utils.omit(value, validated)\n utils.forOwn(patternProperties, function (_schema, pattern) {\n utils.forOwn(toValidate, function (undef, prop) {\n if (prop.match(pattern)) {\n opts.prop = prop\n errors = errors.concat(validate(value[prop], _schema, opts) || [])\n validated.push(prop)\n }\n })\n })\n const keys = Object.keys(utils.omit(value, validated))\n // If \"s\" is not empty, validation fails\n if (additionalProperties === false) {\n if (keys.length) {\n const origProp = opts.prop\n opts.prop = ''\n addError(`extra fields: ${keys.join(', ')}`, 'no extra fields', opts, errors)\n opts.prop = origProp\n }\n } else if (utils.isObject(additionalProperties)) {\n // Otherwise, validate according to provided schema\n keys.forEach(function (prop) {\n opts.prop = prop\n errors = errors.concat(validate(value[prop], additionalProperties, opts) || [])\n })\n }\n return errors.length ? errors : undefined\n },\n\n /**\n * Validates the provided object's has all properties listed in the Schema's `properties` keyword array.\n * Validation succeeds if the object contains all properties provided in the array value of this keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor61\n *\n * @name Schema.validationKeywords.required\n * @method\n * @param {*} value Object to be validated.\n * @param {object} schema Schema containing the `required` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n required (value, schema, opts) {\n opts || (opts = {})\n const required = schema.required\n let errors = []\n if (!opts.existingOnly) {\n required.forEach(function (prop) {\n if (utils.get(value, prop) === undefined) {\n const prevProp = opts.prop\n opts.prop = prop\n addError(undefined, 'a value', opts, errors)\n opts.prop = prevProp\n }\n })\n }\n return errors.length ? errors : undefined\n },\n\n /**\n * Validates the provided value's type is equal to the type, or array of types, defined in the Schema's `type` keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor79\n *\n * @name Schema.validationKeywords.type\n * @method\n * @param {*} value Value to be validated.\n * @param {object} schema Schema containing the `type` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n type (value, schema, opts) {\n let type = schema.type\n let validType\n // Can be one of several types\n if (utils.isString(type)) {\n type = [type]\n }\n // Try to match the value against an expected type\n type.forEach(function (_type) {\n // TODO: throw an error if type is not defined\n if (types[_type](value, schema, opts)) {\n // Matched a type\n validType = _type\n return false\n }\n })\n // Value did not match any expected type\n if (!validType) {\n return makeError(value !== undefined && value !== null ? typeof value : '' + value, `one of (${type.join(', ')})`, opts)\n }\n // Run keyword validators for matched type\n // http://json-schema.org/latest/json-schema-validation.html#anchor12\n const validator = typeGroupValidators[validType]\n if (validator) {\n return validator(value, schema, opts)\n }\n },\n\n /**\n * Validates the provided array values are unique.\n * Validation succeeds if the items in the array are unique, but only if the value of this keyword is true\n * see http://json-schema.org/latest/json-schema-validation.html#anchor49\n *\n * @name Schema.validationKeywords.uniqueItems\n * @method\n * @param {*} value Array to be validated.\n * @param {object} schema Schema containing the `uniqueItems` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n uniqueItems (value, schema, opts) {\n if (value && value.length && schema.uniqueItems) {\n const length = value.length\n let item, i, j\n // Check n - 1 items\n for (i = length - 1; i > 0; i--) {\n item = value[i]\n // Only compare against unchecked items\n for (j = i - 1; j >= 0; j--) {\n // Found a duplicate\n if (utils.deepEqual(item, value[j])) {\n return makeError(item, 'no duplicates', opts)\n }\n }\n }\n }\n }\n}\n\n/**\n * @ignore\n */\nconst runOps = function (ops, value, schema, opts) {\n let errors = []\n ops.forEach(function (op) {\n if (schema[op] !== undefined) {\n errors = errors.concat(validationKeywords[op](value, schema, opts) || [])\n }\n })\n return errors.length ? errors : undefined\n}\n\n/**\n * Validation keywords validated for any type:\n *\n * - `enum`\n * - `type`\n * - `allOf`\n * - `anyOf`\n * - `oneOf`\n * - `not`\n *\n * @name Schema.ANY_OPS\n * @type {string[]}\n */\nconst ANY_OPS = ['enum', 'type', 'allOf', 'anyOf', 'oneOf', 'not']\n\n/**\n * Validation keywords validated for array types:\n *\n * - `items`\n * - `maxItems`\n * - `minItems`\n * - `uniqueItems`\n *\n * @name Schema.ARRAY_OPS\n * @type {string[]}\n */\nconst ARRAY_OPS = ['items', 'maxItems', 'minItems', 'uniqueItems']\n\n/**\n * Validation keywords validated for numeric (number and integer) types:\n *\n * - `multipleOf`\n * - `maximum`\n * - `minimum`\n *\n * @name Schema.NUMERIC_OPS\n * @type {string[]}\n */\nconst NUMERIC_OPS = ['multipleOf', 'maximum', 'minimum']\n\n/**\n * Validation keywords validated for object types:\n *\n * - `maxProperties`\n * - `minProperties`\n * - `required`\n * - `properties`\n * - `dependencies`\n *\n * @name Schema.OBJECT_OPS\n * @type {string[]}\n */\nconst OBJECT_OPS = ['maxProperties', 'minProperties', 'required', 'properties', 'dependencies']\n\n/**\n * Validation keywords validated for string types:\n *\n * - `maxLength`\n * - `minLength`\n * - `pattern`\n *\n * @name Schema.STRING_OPS\n * @type {string[]}\n */\nconst STRING_OPS = ['maxLength', 'minLength', 'pattern']\n\n/**\n * http://json-schema.org/latest/json-schema-validation.html#anchor75\n * @ignore\n */\nconst validateAny = function (value, schema, opts) {\n return runOps(ANY_OPS, value, schema, opts)\n}\n\n/**\n * Validates the provided value against a given Schema according to the http://json-schema.org/ v4 specification.\n *\n * @name Schema.validate\n * @method\n * @param {*} value Value to be validated.\n * @param {object} schema Valid Schema according to the http://json-schema.org/ v4 specification.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\nconst validate = function (value, schema, opts) {\n let errors = []\n opts || (opts = {})\n opts.ctx || (opts.ctx = { value, schema })\n let shouldPop\n let prevProp = opts.prop\n if (schema === undefined) {\n return\n }\n if (!utils.isObject(schema)) {\n throw utils.err(`${DOMAIN}#validate`)(500, `Invalid schema at path: \"${opts.path}\"`)\n }\n if (opts.path === undefined) {\n opts.path = []\n }\n // Track our location as we recurse\n if (opts.prop !== undefined) {\n shouldPop = true\n opts.path.push(opts.prop)\n opts.prop = undefined\n }\n // Validate against parent schema\n if (schema['extends']) {\n // opts.path = path\n // opts.prop = prop\n if (utils.isFunction(schema['extends'].validate)) {\n errors = errors.concat(schema['extends'].validate(value, opts) || [])\n } else {\n errors = errors.concat(validate(value, schema['extends'], opts) || [])\n }\n }\n if (value === undefined) {\n // Check if property is required\n if (schema.required === true && !opts.existingOnly) {\n addError(value, 'a value', opts, errors)\n }\n if (shouldPop) {\n opts.path.pop()\n opts.prop = prevProp\n }\n return errors.length ? errors : undefined\n }\n\n errors = errors.concat(validateAny(value, schema, opts) || [])\n if (shouldPop) {\n opts.path.pop()\n opts.prop = prevProp\n }\n return errors.length ? errors : undefined\n}\n\n// These strings are cached for optimal performance of the change detection\n// boolean - Whether a Record is changing in the current execution frame\nconst changingPath = 'changing'\n// string[] - Properties that have changed in the current execution frame\nconst changedPath = 'changed'\n// Object[] - History of change records\nconst changeHistoryPath = 'history'\n// boolean - Whether a Record is currently being instantiated\nconst creatingPath = 'creating'\n// number - The setTimeout change event id of a Record, if any\nconst eventIdPath = 'eventId'\n// boolean - Whether to skip validation for a Record's currently changing property\nconst noValidatePath = 'noValidate'\n// boolean - Whether to preserve Change History for a Record\nconst keepChangeHistoryPath = 'keepChangeHistory'\n// boolean - Whether to skip change notification for a Record's currently\n// changing property\nconst silentPath = 'silent'\nconst validationFailureMsg = 'validation failed'\n\n/**\n * A map of validation functions grouped by type.\n *\n * @name Schema.typeGroupValidators\n * @type {object}\n */\nconst typeGroupValidators = {\n /**\n * Validates the provided value against the schema using all of the validation keywords specific to instances of an array.\n * The validation keywords for the type `array` are:\n *```\n * ['items', 'maxItems', 'minItems', 'uniqueItems']\n *```\n * see http://json-schema.org/latest/json-schema-validation.html#anchor25\n *\n * @name Schema.typeGroupValidators.array\n * @method\n * @param {*} value Array to be validated.\n * @param {object} schema Schema containing at least one array keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n array: function (value, schema, opts) {\n return runOps(ARRAY_OPS, value, schema, opts)\n },\n\n /**\n * Validates the provided value against the schema using all of the validation keywords specific to instances of an integer.\n * The validation keywords for the type `integer` are:\n *```\n * ['multipleOf', 'maximum', 'minimum']\n *```\n * @name Schema.typeGroupValidators.integer\n * @method\n * @param {*} value Number to be validated.\n * @param {object} schema Schema containing at least one `integer` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n integer: function (value, schema, opts) {\n // Additional validations for numerics are the same\n return typeGroupValidators.numeric(value, schema, opts)\n },\n\n /**\n * Validates the provided value against the schema using all of the validation keywords specific to instances of an number.\n * The validation keywords for the type `number` are:\n *```\n * ['multipleOf', 'maximum', 'minimum']\n *```\n * @name Schema.typeGroupValidators.number\n * @method\n * @param {*} value Number to be validated.\n * @param {object} schema Schema containing at least one `number` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n number: function (value, schema, opts) {\n // Additional validations for numerics are the same\n return typeGroupValidators.numeric(value, schema, opts)\n },\n\n /**\n * Validates the provided value against the schema using all of the validation keywords specific to instances of a number or integer.\n * The validation keywords for the type `numeric` are:\n *```\n * ['multipleOf', 'maximum', 'minimum']\n *```\n * See http://json-schema.org/latest/json-schema-validation.html#anchor13.\n *\n * @name Schema.typeGroupValidators.numeric\n * @method\n * @param {*} value Number to be validated.\n * @param {object} schema Schema containing at least one `numeric` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n numeric: function (value, schema, opts) {\n return runOps(NUMERIC_OPS, value, schema, opts)\n },\n\n /**\n * Validates the provided value against the schema using all of the validation keywords specific to instances of an object.\n * The validation keywords for the type `object` are:\n *```\n * ['maxProperties', 'minProperties', 'required', 'properties', 'dependencies']\n *```\n * See http://json-schema.org/latest/json-schema-validation.html#anchor53.\n *\n * @name Schema.typeGroupValidators.object\n * @method\n * @param {*} value Object to be validated.\n * @param {object} schema Schema containing at least one `object` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n object: function (value, schema, opts) {\n return runOps(OBJECT_OPS, value, schema, opts)\n },\n\n /**\n * Validates the provided value against the schema using all of the validation keywords specific to instances of an string.\n * The validation keywords for the type `string` are:\n *```\n * ['maxLength', 'minLength', 'pattern']\n *```\n * See http://json-schema.org/latest/json-schema-validation.html#anchor25.\n *\n * @name Schema.typeGroupValidators.string\n * @method\n * @param {*} value String to be validated.\n * @param {object} schema Schema containing at least one `string` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n string: function (value, schema, opts) {\n return runOps(STRING_OPS, value, schema, opts)\n }\n}\n\n/**\n * js-data's Schema class.\n *\n * @example Schema#constructor\n * const JSData = require('js-data');\n * const { Schema } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const PostSchema = new Schema({\n * type: 'object',\n * properties: {\n * title: { type: 'string' }\n * }\n * });\n * PostSchema.validate({ title: 1234 });\n *\n * @class Schema\n * @extends Component\n * @param {object} definition Schema definition according to json-schema.org\n */\nfunction Schema (definition) {\n definition || (definition = {})\n // TODO: schema validation\n utils.fillIn(this, definition)\n\n if (this.type === 'object') {\n this.properties = this.properties || {}\n utils.forOwn(this.properties, (_definition, prop) => {\n if (!(_definition instanceof Schema)) {\n this.properties[prop] = new Schema(_definition)\n }\n })\n } else if (this.type === 'array' && this.items && !(this.items instanceof Schema)) {\n this.items = new Schema(this.items)\n }\n if (this.extends && !(this.extends instanceof Schema)) {\n this.extends = new Schema(this.extends)\n }\n ['allOf', 'anyOf', 'oneOf'].forEach((validationKeyword) => {\n if (this[validationKeyword]) {\n this[validationKeyword].forEach((_definition, i) => {\n if (!(_definition instanceof Schema)) {\n this[validationKeyword][i] = new Schema(_definition)\n }\n })\n }\n })\n}\n\nexport default Component.extend({\n constructor: Schema,\n\n /**\n * This adds ES5 getters/setters to the target based on the \"properties\" in\n * this Schema, which makes possible change tracking and validation on\n * property assignment.\n *\n * @name Schema#apply\n * @method\n * @param {object} target The prototype to which to apply this schema.\n */\n apply (target, opts) {\n opts || (opts = {})\n opts.getter || (opts.getter = '_get')\n opts.setter || (opts.setter = '_set')\n opts.unsetter || (opts.unsetter = '_unset')\n opts.track || (opts.track = this.track)\n const properties = this.properties || {}\n utils.forOwn(properties, (schema, prop) => {\n Object.defineProperty(\n target,\n prop,\n this.makeDescriptor(prop, schema, opts)\n )\n })\n },\n\n /**\n * Apply default values to the target object for missing values.\n *\n * @name Schema#applyDefaults\n * @method\n * @param {object} target The target to which to apply values for missing values.\n */\n applyDefaults (target) {\n if (!target) {\n return\n }\n const properties = this.properties || {}\n const hasSet = utils.isFunction(target.set) || utils.isFunction(target._set)\n utils.forOwn(properties, function (schema, prop) {\n if (schema.hasOwnProperty('default') && utils.get(target, prop) === undefined) {\n if (hasSet) {\n target.set(prop, utils.plainCopy(schema['default']), { silent: true })\n } else {\n utils.set(target, prop, utils.plainCopy(schema['default']))\n }\n }\n if (schema.type === 'object' && schema.properties) {\n if (hasSet) {\n const orig = target._get('noValidate')\n target._set('noValidate', true)\n utils.set(target, prop, utils.get(target, prop) || {}, { silent: true })\n target._set('noValidate', orig)\n } else {\n utils.set(target, prop, utils.get(target, prop) || {})\n }\n schema.applyDefaults(utils.get(target, prop))\n }\n })\n },\n\n /**\n * Assemble a property descriptor for tracking and validating changes to\n * a property according to the given schema. This method is called when\n * {@link Mapper#applySchema} is set to `true`.\n *\n * @name Schema#makeDescriptor\n * @method\n * @param {string} prop The property name.\n * @param {(Schema|object)} schema The schema for the property.\n * @param {object} [opts] Optional configuration.\n * @param {function} [opts.getter] Custom getter function.\n * @param {function} [opts.setter] Custom setter function.\n * @param {function} [opts.track] Whether to track changes.\n * @returns {object} A property descriptor for the given schema.\n */\n makeDescriptor (prop, schema, opts) {\n const descriptor = {\n // Better to allow configurability, but at the user's own risk\n configurable: true,\n // These properties are enumerable by default, but regardless of their\n // enumerability, they won't be \"own\" properties of individual records\n enumerable: schema.enumerable === undefined ? true : !!schema.enumerable\n }\n // Cache a few strings for optimal performance\n const keyPath = `props.${prop}`\n const previousPath = `previous.${prop}`\n const getter = opts.getter\n const setter = opts.setter\n const unsetter = opts.unsetter\n const track = utils.isBoolean(opts.track) ? opts.track : schema.track\n\n descriptor.get = function () {\n return this._get(keyPath)\n }\n\n if (utils.isFunction(schema.get)) {\n const originalGet = descriptor.get\n descriptor.get = function () {\n return schema.get.call(this, originalGet)\n }\n }\n\n descriptor.set = function (value) {\n // These are accessed a lot\n const _get = this[getter]\n const _set = this[setter]\n const _unset = this[unsetter]\n // Optionally check that the new value passes validation\n if (!_get(noValidatePath)) {\n const errors = schema.validate(value, { path: [prop] })\n if (errors) {\n // Immediately throw an error, preventing the record from getting into\n // an invalid state\n const error = new Error(validationFailureMsg)\n error.errors = errors\n throw error\n }\n }\n // TODO: Make it so tracking can be turned on for all properties instead of\n // only per-property\n if (track && !_get(creatingPath)) {\n // previous is versioned on database commit\n // props are versioned on set()\n const previous = _get(previousPath)\n const current = _get(keyPath)\n let changing = _get(changingPath)\n let changed = _get(changedPath)\n\n if (!changing) {\n // Track properties that are changing in the current event loop\n changed = []\n }\n\n // Add changing properties to this array once at most\n const index = changed.indexOf(prop)\n if (current !== value && index === -1) {\n changed.push(prop)\n }\n if (previous === value) {\n if (index >= 0) {\n changed.splice(index, 1)\n }\n }\n // No changes in current event loop\n if (!changed.length) {\n changing = false\n _unset(changingPath)\n _unset(changedPath)\n // Cancel pending change event\n if (_get(eventIdPath)) {\n clearTimeout(_get(eventIdPath))\n _unset(eventIdPath)\n }\n }\n // Changes detected in current event loop\n if (!changing && changed.length) {\n _set(changedPath, changed)\n _set(changingPath, true)\n // Saving the timeout id allows us to batch all changes in the same\n // event loop into a single \"change\"\n // TODO: Optimize\n _set(eventIdPath, setTimeout(() => {\n // Previous event loop where changes were gathered has ended, so\n // notify any listeners of those changes and prepare for any new\n // changes\n _unset(changedPath)\n _unset(eventIdPath)\n _unset(changingPath)\n // TODO: Optimize\n if (!_get(silentPath)) {\n let i\n for (i = 0; i < changed.length; i++) {\n this.emit('change:' + changed[i], this, utils.get(this, changed[i]))\n }\n\n const changes = utils.diffObjects({ [prop]: value }, { [prop]: current })\n\n if (_get(keepChangeHistoryPath)) {\n const changeRecord = utils.plainCopy(changes)\n changeRecord.timestamp = new Date().getTime()\n let changeHistory = _get(changeHistoryPath)\n !changeHistory && _set(changeHistoryPath, (changeHistory = []))\n changeHistory.push(changeRecord)\n }\n this.emit('change', this, changes)\n }\n _unset(silentPath)\n }, 0))\n }\n }\n _set(keyPath, value)\n return value\n }\n\n if (utils.isFunction(schema.set)) {\n const originalSet = descriptor.set\n descriptor.set = function (value) {\n return schema.set.call(this, value, originalSet)\n }\n }\n\n return descriptor\n },\n\n /**\n * Create a copy of the given value that contains only the properties defined\n * in this schema.\n *\n * @name Schema#pick\n * @method\n * @param {*} value The value to copy.\n * @returns {*} The copy.\n */\n pick (value) {\n if (value === undefined) {\n return\n }\n if (this.type === 'object') {\n let copy = {}\n const properties = this.properties\n if (properties) {\n utils.forOwn(properties, (_definition, prop) => {\n copy[prop] = _definition.pick(value[prop])\n })\n }\n if (this.extends) {\n utils.fillIn(copy, this.extends.pick(value))\n }\n // Conditionally copy properties not defined in \"properties\"\n if (this.additionalProperties) {\n for (var key in value) {\n if (!properties[key]) {\n copy[key] = utils.plainCopy(value[key])\n }\n }\n }\n return copy\n } else if (this.type === 'array') {\n return value.map((item) => {\n const _copy = this.items ? this.items.pick(item) : {}\n if (this.extends) {\n utils.fillIn(_copy, this.extends.pick(item))\n }\n return _copy\n })\n }\n return utils.plainCopy(value)\n },\n\n /**\n * Validate the provided value against this schema.\n *\n * @name Schema#validate\n * @method\n * @param {*} value Value to validate.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n validate (value, opts) {\n return validate(value, this, opts)\n }\n}, {\n ANY_OPS,\n ARRAY_OPS,\n NUMERIC_OPS,\n OBJECT_OPS,\n STRING_OPS,\n typeGroupValidators,\n types,\n validate,\n validationKeywords\n})\n\n/**\n * Create a subclass of this Schema:\n * @example Schema.extend\n * const JSData = require('js-data');\n * const { Schema } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomSchemaClass extends Schema {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customSchema = new CustomSchemaClass();\n * console.log(customSchema.foo());\n * console.log(CustomSchemaClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherSchemaClass = Schema.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherSchema = new OtherSchemaClass();\n * console.log(otherSchema.foo());\n * console.log(OtherSchemaClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherSchemaClass () {\n * Schema.call(this);\n * this.created_at = new Date().getTime();\n * }\n * Schema.extend({\n * constructor: AnotherSchemaClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const anotherSchema = new AnotherSchemaClass();\n * console.log(anotherSchema.created_at);\n * console.log(anotherSchema.foo());\n * console.log(AnotherSchemaClass.beep());\n *\n * @method Schema.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this Schema class.\n * @since 3.0.0\n */\n","import utils from './utils'\nimport Component from './Component'\nimport Record from './Record'\nimport Schema from './Schema'\nimport { Relation } from './relations'\nimport {\n belongsTo,\n belongsToType,\n hasMany,\n hasManyType,\n hasOne,\n hasOneType\n} from './decorators'\n\nconst DOMAIN = 'Mapper'\nconst applyDefaultsHooks = [\n 'beforeCreate',\n 'beforeCreateMany'\n]\nconst validatingHooks = [\n 'beforeCreate',\n 'beforeCreateMany',\n 'beforeUpdate',\n 'beforeUpdateAll',\n 'beforeUpdateMany'\n]\nconst makeNotify = function (num) {\n return function (...args) {\n const opts = args[args.length - num]\n const op = opts.op\n this.dbg(op, ...args)\n\n if (applyDefaultsHooks.indexOf(op) !== -1 && opts.applyDefaults !== false) {\n const schema = this.getSchema()\n if (schema && schema.applyDefaults) {\n let toProcess = args[0]\n if (!utils.isArray(toProcess)) {\n toProcess = [toProcess]\n }\n toProcess.forEach((record) => {\n schema.applyDefaults(record)\n })\n }\n }\n\n // Automatic validation\n if (validatingHooks.indexOf(op) !== -1 && !opts.noValidate) {\n // Save current value of option\n const originalExistingOnly = opts.existingOnly\n\n // For updates, ignore required fields if they aren't present\n if (op.indexOf('beforeUpdate') === 0 && opts.existingOnly === undefined) {\n opts.existingOnly = true\n }\n const errors = this.validate(args[op === 'beforeUpdate' ? 1 : 0], utils.pick(opts, ['existingOnly']))\n\n // Restore option\n opts.existingOnly = originalExistingOnly\n\n // Abort lifecycle due to validation errors\n if (errors) {\n const err = new Error('validation failed')\n err.errors = errors\n return utils.reject(err)\n }\n }\n\n // Emit lifecycle event\n if (opts.notify || (opts.notify === undefined && this.notify)) {\n setTimeout(() => {\n this.emit(op, ...args)\n })\n }\n }\n}\n\n// These are the default implementations of all of the lifecycle hooks\nconst notify = makeNotify(1)\nconst notify2 = makeNotify(2)\n\n// This object provides meta information used by Mapper#crud to actually\n// execute each lifecycle method\nconst LIFECYCLE_METHODS = {\n count: {\n defaults: [{}, {}],\n skip: true,\n types: []\n },\n destroy: {\n defaults: [{}, {}],\n skip: true,\n types: []\n },\n destroyAll: {\n defaults: [{}, {}],\n skip: true,\n types: []\n },\n find: {\n defaults: [undefined, {}],\n types: []\n },\n findAll: {\n defaults: [{}, {}],\n types: []\n },\n sum: {\n defaults: [undefined, {}, {}],\n skip: true,\n types: []\n },\n update: {\n adapterArgs (mapper, id, props, opts) {\n return [id, mapper.toJSON(props, opts), opts]\n },\n beforeAssign: 1,\n defaults: [undefined, {}, {}],\n types: []\n },\n updateAll: {\n adapterArgs (mapper, props, query, opts) {\n return [mapper.toJSON(props, opts), query, opts]\n },\n beforeAssign: 0,\n defaults: [{}, {}, {}],\n types: []\n },\n updateMany: {\n adapterArgs (mapper, records, opts) {\n return [records.map((record) => mapper.toJSON(record, opts)), opts]\n },\n beforeAssign: 0,\n defaults: [[], {}],\n types: []\n }\n}\n\nconst MAPPER_DEFAULTS = {\n /**\n * Hash of registered adapters. Don't modify directly. Use\n * {@link Mapper#registerAdapter} instead.\n *\n * @default {}\n * @name Mapper#_adapters\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/connecting-to-a-data-source\",\"Connecting to a data source\"]\n */\n _adapters: {},\n\n /**\n * Whether {@link Mapper#beforeCreate} and {@link Mapper#beforeCreateMany}\n * should automatically receive default values according to the Mapper's schema.\n *\n * @default true\n * @name Mapper#applyDefaults\n * @since 3.0.0\n * @type {boolean}\n */\n applyDefaults: true,\n\n /**\n * Whether to augment {@link Mapper#recordClass} with ES5 getters and setters\n * according to the properties defined in {@link Mapper#schema}. This makes\n * possible validation and change tracking on individual properties\n * when using the dot (e.g. `user.name = \"Bob\"`) operator to modify a\n * property, and is `true` by default.\n *\n * @default true\n * @name Mapper#applySchema\n * @since 3.0.0\n * @type {boolean}\n */\n applySchema: true,\n\n /**\n * The name of the registered adapter that this Mapper should used by default.\n *\n * @default \"http\"\n * @name Mapper#defaultAdapter\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/connecting-to-a-data-source\",\"Connecting to a data source\"]\n * @type {string}\n */\n defaultAdapter: 'http',\n\n /**\n * The field used as the unique identifier on records handled by this Mapper.\n *\n * @default id\n * @name Mapper#idAttribute\n * @since 3.0.0\n * @type {string}\n */\n idAttribute: 'id',\n\n /**\n * Whether records created from this mapper keep changeHistory on property changes.\n *\n * @default true\n * @name Mapper#keepChangeHistory\n * @since 3.0.0\n * @type {boolean}\n */\n keepChangeHistory: true,\n\n /**\n * Whether this Mapper should emit operational events.\n *\n * @default true\n * @name Mapper#notify\n * @since 3.0.0\n * @type {boolean}\n */\n notify: true,\n\n /**\n * Whether to skip validation when the Record instances are created.\n *\n * @default false\n * @name Mapper#noValidate\n * @since 3.0.0\n * @type {boolean}\n */\n noValidate: false,\n\n /**\n * Whether {@link Mapper#create}, {@link Mapper#createMany},\n * {@link Mapper#update}, {@link Mapper#updateAll}, {@link Mapper#updateMany},\n * {@link Mapper#find}, {@link Mapper#findAll}, {@link Mapper#destroy},\n * {@link Mapper#destroyAll}, {@link Mapper#count}, and {@link Mapper#sum}\n * should return a raw result object that contains both the instance data\n * returned by the adapter _and_ metadata about the operation.\n *\n * The default is to NOT return the result object, and instead return just the\n * instance data.\n *\n * @default false\n * @name Mapper#raw\n * @since 3.0.0\n * @type {boolean}\n */\n raw: false,\n\n /**\n * Whether records created from this mapper automatically validate their properties\n * when their properties are modified.\n *\n * @default true\n * @name Mapper#validateOnSet\n * @since 3.0.0\n * @type {boolean}\n */\n validateOnSet: true\n}\n\n/**\n * The core of JSData's [ORM/ODM][orm] implementation. Given a minimum amout of\n * meta information about a resource, a Mapper can perform generic CRUD\n * operations against that resource. Apart from its configuration, a Mapper is\n * stateless. The particulars of various persistence layers have been abstracted\n * into adapters, which a Mapper uses to perform its operations.\n *\n * The term \"Mapper\" comes from the [Data Mapper Pattern][pattern] described in\n * Martin Fowler's [Patterns of Enterprise Application Architecture][book]. A\n * Data Mapper moves data between [in-memory object instances][record] and a\n * relational or document-based database. JSData's Mapper can work with any\n * persistence layer you can write an adapter for.\n *\n * _(\"Model\" is a heavily overloaded term and is avoided in this documentation\n * to prevent confusion.)_\n *\n * [orm]: https://en.wikipedia.org/wiki/Object-relational_mapping\n *\n * @example\n * [pattern]: https://en.wikipedia.org/wiki/Data_mapper_pattern\n * [book]: http://martinfowler.com/books/eaa.html\n * [record]: Record.html\n * // Import and instantiate\n * import { Mapper } from 'js-data';\n * const UserMapper = new Mapper({ name: 'user' });\n *\n * @example\n * // Define a Mapper using the Container component\n * import { Container } from 'js-data';\n * const store = new Container();\n * store.defineMapper('user');\n *\n * @class Mapper\n * @extends Component\n * @param {object} opts Configuration options.\n * @param {boolean} [opts.applySchema=true] See {@link Mapper#applySchema}.\n * @param {boolean} [opts.debug=false] See {@link Component#debug}.\n * @param {string} [opts.defaultAdapter=http] See {@link Mapper#defaultAdapter}.\n * @param {string} [opts.idAttribute=id] See {@link Mapper#idAttribute}.\n * @param {object} [opts.methods] See {@link Mapper#methods}.\n * @param {string} opts.name See {@link Mapper#name}.\n * @param {boolean} [opts.notify] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw=false] See {@link Mapper#raw}.\n * @param {Function|boolean} [opts.recordClass] See {@link Mapper#recordClass}.\n * @param {Object|Schema} [opts.schema] See {@link Mapper#schema}.\n * @returns {Mapper} A new {@link Mapper} instance.\n * @see http://www.js-data.io/v3.0/docs/components-of-jsdata#mapper\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#mapper\",\"Components of JSData: Mapper\"]\n * @tutorial [\"http://www.js-data.io/v3.0/docs/modeling-your-data\",\"Modeling your data\"]\n */\nfunction Mapper (opts) {\n utils.classCallCheck(this, Mapper)\n Component.call(this)\n opts || (opts = {})\n\n // Prepare certain properties to be non-enumerable\n Object.defineProperties(this, {\n _adapters: {\n value: undefined,\n writable: true\n },\n\n /**\n * The {@link Container} that holds this Mapper. __Do not modify.__\n *\n * @name Mapper#lifecycleMethods\n * @since 3.0.0\n * @type {Object}\n */\n datastore: {\n value: undefined,\n writable: true\n },\n\n /**\n * The meta information describing this Mapper's available lifecycle\n * methods. __Do not modify.__\n *\n * @name Mapper#lifecycleMethods\n * @since 3.0.0\n * @type {Object}\n */\n lifecycleMethods: {\n value: LIFECYCLE_METHODS\n },\n\n /**\n * Set to `false` to force the Mapper to work with POJO objects only.\n *\n * @example\n * // Use POJOs only.\n * import { Mapper, Record } from 'js-data';\n * const UserMapper = new Mapper({ recordClass: false });\n * UserMapper.recordClass // false;\n * const user = UserMapper.createRecord();\n * user instanceof Record; // false\n *\n * @example\n * // Set to a custom class to have records wrapped in your custom class.\n * import { Mapper, Record } from 'js-data';\n * // Custom class\n * class User {\n * constructor (props = {}) {\n * for (var key in props) {\n * if (props.hasOwnProperty(key)) {\n * this[key] = props[key];\n * }\n * }\n * }\n * }\n * const UserMapper = new Mapper({ recordClass: User });\n * UserMapper.recordClass; // function User() {}\n * const user = UserMapper.createRecord();\n * user instanceof Record; // false\n * user instanceof User; // true\n *\n *\n * @example\n * // Extend the {@link Record} class.\n * import { Mapper, Record } from 'js-data';\n * // Custom class\n * class User extends Record {\n * constructor () {\n * super(props);\n * }\n * }\n * const UserMapper = new Mapper({ recordClass: User });\n * UserMapper.recordClass; // function User() {}\n * const user = UserMapper.createRecord();\n * user instanceof Record; // true\n * user instanceof User; // true\n *\n * @name Mapper#recordClass\n * @default {@link Record}\n * @see Record\n * @since 3.0.0\n */\n recordClass: {\n value: undefined,\n writable: true\n },\n\n /**\n * This Mapper's {@link Schema}.\n *\n * @example Mapper#schema\n * const JSData = require('js-data');\n * const { Mapper } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const UserMapper = new Mapper({\n * name: 'user',\n * schema: {\n * properties: {\n * id: { type: 'number' },\n * first: { type: 'string', track: true },\n * last: { type: 'string', track: true },\n * role: { type: 'string', track: true, required: true },\n * age: { type: 'integer', track: true },\n * is_active: { type: 'number' }\n * }\n * }\n * });\n * const user = UserMapper.createRecord({\n * id: 1,\n * name: 'John',\n * role: 'admin'\n * });\n * user.on('change', function (user, changes) {\n * console.log(changes);\n * });\n * user.on('change:role', function (user, value) {\n * console.log('change:role - ' + value);\n * });\n * user.role = 'owner';\n *\n * @name Mapper#schema\n * @see Schema\n * @since 3.0.0\n * @type {Schema}\n */\n schema: {\n value: undefined,\n writable: true\n }\n })\n\n // Apply user-provided configuration\n utils.fillIn(this, opts)\n // Fill in any missing options with the defaults\n utils.fillIn(this, utils.copy(MAPPER_DEFAULTS))\n\n /**\n * The name for this Mapper. This is the minimum amount of meta information\n * required for a Mapper to be able to execute CRUD operations for a\n * Resource.\n *\n * @name Mapper#name\n * @since 3.0.0\n * @type {string}\n */\n if (!this.name) {\n throw utils.err(`new ${DOMAIN}`, 'opts.name')(400, 'string', this.name)\n }\n\n // Setup schema, with an empty default schema if necessary\n if (this.schema) {\n this.schema.type || (this.schema.type = 'object')\n if (!(this.schema instanceof Schema)) {\n this.schema = new Schema(this.schema || { type: 'object' })\n }\n }\n\n // Create a subclass of Record that's tied to this Mapper\n if (this.recordClass === undefined) {\n const superClass = Record\n this.recordClass = superClass.extend({\n constructor: (function Record () {\n var subClass = function Record (props, opts) {\n utils.classCallCheck(this, subClass)\n superClass.call(this, props, opts)\n }\n return subClass\n })()\n })\n }\n\n if (this.recordClass) {\n this.recordClass.mapper = this\n\n /**\n * Functions that should be added to the prototype of {@link Mapper#recordClass}.\n *\n * @name Mapper#methods\n * @since 3.0.0\n * @type {Object}\n */\n if (utils.isObject(this.methods)) {\n utils.addHiddenPropsToTarget(this.recordClass.prototype, this.methods)\n }\n\n // We can only apply the schema to the prototype of this.recordClass if the\n // class extends Record\n if (Record.prototype.isPrototypeOf(Object.create(this.recordClass.prototype)) && this.schema && this.schema.apply && this.applySchema) {\n this.schema.apply(this.recordClass.prototype)\n }\n }\n}\n\nexport default Component.extend({\n constructor: Mapper,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#count}. If this method\n * returns a promise then {@link Mapper#count} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterCount\n * @param {object} query The `query` argument passed to {@link Mapper#count}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#count}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterCount: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#create}. If this method\n * returns a promise then {@link Mapper#create} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterCreate\n * @param {object} props The `props` argument passed to {@link Mapper#create}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#create}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterCreate: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#createMany}. If this method\n * returns a promise then {@link Mapper#createMany} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterCreateMany\n * @param {array} records The `records` argument passed to {@link Mapper#createMany}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#createMany}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterCreateMany: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#destroy}. If this method\n * returns a promise then {@link Mapper#destroy} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterDestroy\n * @param {(string|number)} id The `id` argument passed to {@link Mapper#destroy}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#destroy}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterDestroy: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#destroyAll}. If this method\n * returns a promise then {@link Mapper#destroyAll} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterDestroyAll\n * @param {*} data The `data` returned by the adapter.\n * @param {query} query The `query` argument passed to {@link Mapper#destroyAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#destroyAll}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterDestroyAll: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#find}. If this method\n * returns a promise then {@link Mapper#find} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterFind\n * @param {(string|number)} id The `id` argument passed to {@link Mapper#find}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#find}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterFind: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#findAll}. If this method\n * returns a promise then {@link Mapper#findAll} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterFindAll\n * @param {object} query The `query` argument passed to {@link Mapper#findAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#findAll}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterFindAll: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#sum}. If this method\n * returns a promise then {@link Mapper#sum} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterSum\n * @param {object} query The `query` argument passed to {@link Mapper#sum}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#sum}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterSum: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#update}. If this method\n * returns a promise then {@link Mapper#update} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterUpdate\n * @param {(string|number)} id The `id` argument passed to {@link Mapper#update}.\n * @param {props} props The `props` argument passed to {@link Mapper#update}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#update}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterUpdate: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#updateAll}. If this method\n * returns a promise then {@link Mapper#updateAll} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterUpdateAll\n * @param {object} props The `props` argument passed to {@link Mapper#updateAll}.\n * @param {object} query The `query` argument passed to {@link Mapper#updateAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#updateAll}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterUpdateAll: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#updateMany}. If this method\n * returns a promise then {@link Mapper#updateMany} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterUpdateMany\n * @param {array} records The `records` argument passed to {@link Mapper#updateMany}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#updateMany}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterUpdateMany: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#create}. If this method\n * returns a promise then {@link Mapper#create} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeCreate\n * @param {object} props The `props` argument passed to {@link Mapper#create}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#create}.\n * @since 3.0.0\n */\n beforeCreate: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#createMany}. If this method\n * returns a promise then {@link Mapper#createMany} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeCreateMany\n * @param {array} records The `records` argument passed to {@link Mapper#createMany}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#createMany}.\n * @since 3.0.0\n */\n beforeCreateMany: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#count}. If this method\n * returns a promise then {@link Mapper#count} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeCount\n * @param {object} query The `query` argument passed to {@link Mapper#count}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#count}.\n * @since 3.0.0\n */\n beforeCount: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#destroy}. If this method\n * returns a promise then {@link Mapper#destroy} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeDestroy\n * @param {(string|number)} id The `id` argument passed to {@link Mapper#destroy}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#destroy}.\n * @since 3.0.0\n */\n beforeDestroy: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#destroyAll}. If this method\n * returns a promise then {@link Mapper#destroyAll} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeDestroyAll\n * @param {query} query The `query` argument passed to {@link Mapper#destroyAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#destroyAll}.\n * @since 3.0.0\n */\n beforeDestroyAll: notify,\n\n /**\n * Mappers lifecycle hook called by {@link Mapper#find}. If this method\n * returns a promise then {@link Mapper#find} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeFind\n * @param {(string|number)} id The `id` argument passed to {@link Mapper#find}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#find}.\n * @since 3.0.0\n */\n beforeFind: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#findAll}. If this method\n * returns a promise then {@link Mapper#findAll} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeFindAll\n * @param {object} query The `query` argument passed to {@link Mapper#findAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#findAll}.\n * @since 3.0.0\n */\n beforeFindAll: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#sum}. If this method\n * returns a promise then {@link Mapper#sum} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeSum\n * @param {string} field The `field` argument passed to {@link Mapper#sum}.\n * @param {object} query The `query` argument passed to {@link Mapper#sum}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#sum}.\n * @since 3.0.0\n */\n beforeSum: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#update}. If this method\n * returns a promise then {@link Mapper#update} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeUpdate\n * @param {(string|number)} id The `id` argument passed to {@link Mapper#update}.\n * @param {props} props The `props` argument passed to {@link Mapper#update}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#update}.\n * @since 3.0.0\n */\n beforeUpdate: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#updateAll}. If this method\n * returns a promise then {@link Mapper#updateAll} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeUpdateAll\n * @param {object} props The `props` argument passed to {@link Mapper#updateAll}.\n * @param {object} query The `query` argument passed to {@link Mapper#updateAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#updateAll}.\n * @since 3.0.0\n */\n beforeUpdateAll: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#updateMany}. If this method\n * returns a promise then {@link Mapper#updateMany} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeUpdateMany\n * @param {array} records The `records` argument passed to {@link Mapper#updateMany}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#updateMany}.\n * @since 3.0.0\n */\n beforeUpdateMany: notify,\n\n /**\n * This method is called at the end of most lifecycle methods. It does the\n * following:\n *\n * 1. If `opts.raw` is `true`, add this Mapper's configuration to the `opts`\n * argument as metadata for the operation.\n * 2. Wrap the result data appropriately using {@link Mapper#wrap}, which\n * calls {@link Mapper#createRecord}.\n *\n * @method Mapper#_end\n * @private\n * @since 3.0.0\n */\n _end (result, opts, skip) {\n if (opts.raw) {\n utils._(result, opts)\n }\n if (skip) {\n return result\n }\n let _data = opts.raw ? result.data : result\n if (_data && utils.isFunction(this.wrap)) {\n _data = this.wrap(_data, opts)\n if (opts.raw) {\n result.data = _data\n } else {\n result = _data\n }\n }\n return result\n },\n\n /**\n * Define a belongsTo relationship. Only useful if you're managing your\n * Mappers manually and not using a Container or DataStore component.\n *\n * @example\n * PostMapper.belongsTo(UserMapper, {\n * // post.user_id points to user.id\n * foreignKey: 'user_id'\n * // user records will be attached to post records at \"post.user\"\n * localField: 'user'\n * });\n *\n * CommentMapper.belongsTo(UserMapper, {\n * // comment.user_id points to user.id\n * foreignKey: 'user_id'\n * // user records will be attached to comment records at \"comment.user\"\n * localField: 'user'\n * });\n * CommentMapper.belongsTo(PostMapper, {\n * // comment.post_id points to post.id\n * foreignKey: 'post_id'\n * // post records will be attached to comment records at \"comment.post\"\n * localField: 'post'\n * });\n *\n * @method Mapper#belongsTo\n * @see http://www.js-data.io/v3.0/docs/relations\n * @since 3.0.0\n */\n belongsTo (relatedMapper, opts) {\n return belongsTo(relatedMapper, opts)(this)\n },\n\n /**\n * Select records according to the `query` argument and return the count.\n *\n * {@link Mapper#beforeCount} will be called before calling the adapter.\n * {@link Mapper#afterCount} will be called after calling the adapter.\n *\n * @example\n * // Get the number of published blog posts\n * PostMapper.count({ status: 'published' }).then((numPublished) => {\n * console.log(numPublished); // e.g. 45\n * });\n *\n * @method Mapper#count\n * @param {object} [query={}] Selection query. See {@link query}.\n * @param {object} [query.where] See {@link query.where}.\n * @param {number} [query.offset] See {@link query.offset}.\n * @param {number} [query.limit] See {@link query.limit}.\n * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}.\n * @param {object} [opts] Configuration options. Refer to the `count` method\n * of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @returns {Promise} Resolves with the count of the selected records.\n * @since 3.0.0\n */\n count (query, opts) {\n return this.crud('count', query, opts)\n },\n\n /**\n * Fired during {@link Mapper#create}. See\n * {@link Mapper~beforeCreateListener} for how to listen for this event.\n *\n * @event Mapper#beforeCreate\n * @see Mapper~beforeCreateListener\n * @see Mapper#create\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeCreate} event.\n *\n * @example\n * function onBeforeCreate (props, opts) {\n * // do something\n * }\n * store.on('beforeCreate', onBeforeCreate);\n *\n * @callback Mapper~beforeCreateListener\n * @param {object} props The `props` argument passed to {@link Mapper#beforeCreate}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#beforeCreate}.\n * @see Mapper#event:beforeCreate\n * @see Mapper#create\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#create}. See\n * {@link Mapper~afterCreateListener} for how to listen for this event.\n *\n * @event Mapper#afterCreate\n * @see Mapper~afterCreateListener\n * @see Mapper#create\n */\n /**\n * Callback signature for the {@link Mapper#event:afterCreate} event.\n *\n * @example\n * function onAfterCreate (props, opts, result) {\n * // do something\n * }\n * store.on('afterCreate', onAfterCreate);\n *\n * @callback Mapper~afterCreateListener\n * @param {object} props The `props` argument passed to {@link Mapper#afterCreate}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#afterCreate}.\n * @param {object} result The `result` argument passed to {@link Mapper#afterCreate}.\n * @see Mapper#event:afterCreate\n * @see Mapper#create\n * @since 3.0.0\n */\n /**\n * Create and save a new the record using the provided `props`.\n *\n * {@link Mapper#beforeCreate} will be called before calling the adapter.\n * {@link Mapper#afterCreate} will be called after calling the adapter.\n *\n * @example\n * // Create and save a new blog post\n * PostMapper.create({\n * title: 'Modeling your data',\n * status: 'draft'\n * }).then((post) => {\n * console.log(post); // { id: 1234, status: 'draft', ... }\n * });\n *\n * @fires Mapper#beforeCreate\n * @fires Mapper#afterCreate\n * @method Mapper#create\n * @param {object} props The properties for the new record.\n * @param {object} [opts] Configuration options. Refer to the `create` method\n * of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @param {string[]} [opts.with=[]] Relations to create in a cascading\n * create if `props` contains nested relations. NOT performed in a\n * transaction. Each nested create will result in another {@link Mapper#create}\n * or {@link Mapper#createMany} call.\n * @param {string[]} [opts.pass=[]] Relations to send to the adapter as part\n * of the payload. Normally relations are not sent.\n * @returns {Promise} Resolves with the created record.\n * @since 3.0.0\n */\n create (props, opts) {\n // Default values for arguments\n props || (props = {})\n opts || (opts = {})\n const originalRecord = props\n let parentRelationMap = {}\n let adapterResponse = {}\n\n // Fill in \"opts\" with the Mapper's configuration\n utils._(opts, this)\n opts.adapter = this.getAdapterName(opts)\n\n opts.op = 'beforeCreate'\n return this._runHook(opts.op, props, opts).then((props) => {\n opts.with || (opts.with = [])\n return this._createParentRecordIfRequired(props, opts)\n }).then((relationMap) => {\n parentRelationMap = relationMap\n }).then(() => {\n opts.op = 'create'\n return this._invokeAdapterMethod(opts.op, props, opts)\n }).then((result) => {\n adapterResponse = result\n }).then(() => {\n const createdProps = opts.raw ? adapterResponse.data : adapterResponse\n\n return this._createOrAssignChildRecordIfRequired(createdProps, {\n opts,\n parentRelationMap,\n originalProps: props\n })\n }).then((createdProps) => {\n return this._commitChanges(originalRecord, createdProps)\n }).then((record) => {\n if (opts.raw) {\n adapterResponse.data = record\n } else {\n adapterResponse = record\n }\n const result = this._end(adapterResponse, opts)\n opts.op = 'afterCreate'\n return this._runHook(opts.op, props, opts, result)\n })\n },\n\n _commitChanges (recordOrRecords, newValues) {\n if (utils.isArray(recordOrRecords)) {\n return recordOrRecords.map((record, i) => this._commitChanges(record, newValues[i]))\n }\n\n utils.set(recordOrRecords, newValues, { silent: true })\n\n if (utils.isFunction(recordOrRecords.commit)) {\n recordOrRecords.commit()\n }\n\n return recordOrRecords\n },\n\n /**\n * Use {@link Mapper#createRecord} instead.\n * @deprecated\n * @method Mapper#createInstance\n * @param {Object|Array} props See {@link Mapper#createRecord}.\n * @param {object} [opts] See {@link Mapper#createRecord}.\n * @returns {Object|Array} See {@link Mapper#createRecord}.\n * @see Mapper#createRecord\n * @since 3.0.0\n */\n createInstance (props, opts) {\n return this.createRecord(props, opts)\n },\n\n /**\n * Creates parent record for relation types like BelongsTo or HasMany with localKeys\n * in order to satisfy foreignKey dependency (so called child records).\n * @param {object} props See {@link Mapper#create}.\n * @param {object} opts See {@link Mapper#create}.\n * @returns {Object} cached parent records map\n * @see Mapper#create\n * @since 3.0.0\n */\n _createParentRecordIfRequired (props, opts) {\n const tasks = []\n const relations = []\n\n utils.forEachRelation(this, opts, (def, optsCopy) => {\n if (!def.isRequiresParentId() || !def.getLocalField(props)) {\n return\n }\n\n optsCopy.raw = false\n relations.push(def)\n tasks.push(def.createParentRecord(props, optsCopy))\n })\n\n return utils.Promise.all(tasks).then(records => {\n return relations.reduce((map, relation, index) => {\n relation.setLocalField(map, records[index])\n return map\n }, {})\n })\n },\n\n /**\n * Creates child record for relation types like HasOne or HasMany with foreignKey\n * in order to satisfy foreignKey dependency (so called parent records).\n * @param {object} props See {@link Mapper#create}.\n * @param {object} context contains collected information.\n * @param {object} context.opts See {@link Mapper#create}.\n * @param {object} context.parentRelationMap contains parent records map\n * @param {object} context.originalProps contains data passed into {@link Mapper#create} method\n * @return {Promise} updated props\n * @see Mapper#create\n * @since 3.0.0\n */\n _createOrAssignChildRecordIfRequired (props, context) {\n const tasks = []\n\n utils.forEachRelation(this, context.opts, (def, optsCopy) => {\n const relationData = def.getLocalField(context.originalProps)\n\n if (!relationData) {\n return\n }\n\n optsCopy.raw = false\n // Create hasMany and hasOne after the main create because we needed\n // a generated id to attach to these items\n if (def.isRequiresChildId()) {\n tasks.push(def.createChildRecord(props, relationData, optsCopy))\n } else if (def.isRequiresParentId()) {\n const parent = def.getLocalField(context.parentRelationMap)\n\n if (parent) {\n def.setLocalField(props, parent)\n }\n }\n })\n\n return utils.Promise.all(tasks)\n .then(() => props)\n },\n\n /**\n * Fired during {@link Mapper#createMany}. See\n * {@link Mapper~beforeCreateManyListener} for how to listen for this event.\n *\n * @event Mapper#beforeCreateMany\n * @see Mapper~beforeCreateManyListener\n * @see Mapper#createMany\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeCreateMany} event.\n *\n * @example\n * function onBeforeCreateMany (records, opts) {\n * // do something\n * }\n * store.on('beforeCreateMany', onBeforeCreateMany);\n *\n * @callback Mapper~beforeCreateManyListener\n * @param {object} records The `records` argument received by {@link Mapper#beforeCreateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreateMany}.\n * @see Mapper#event:beforeCreateMany\n * @see Mapper#createMany\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#createMany}. See\n * {@link Mapper~afterCreateManyListener} for how to listen for this event.\n *\n * @event Mapper#afterCreateMany\n * @see Mapper~afterCreateManyListener\n * @see Mapper#createMany\n */\n /**\n * Callback signature for the {@link Mapper#event:afterCreateMany} event.\n *\n * @example\n * function onAfterCreateMany (records, opts, result) {\n * // do something\n * }\n * store.on('afterCreateMany', onAfterCreateMany);\n *\n * @callback Mapper~afterCreateManyListener\n * @param {object} records The `records` argument received by {@link Mapper#afterCreateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterCreateMany}.\n * @param {object} result The `result` argument received by {@link Mapper#afterCreateMany}.\n * @see Mapper#event:afterCreateMany\n * @see Mapper#createMany\n * @since 3.0.0\n */\n /**\n * Given an array of records, batch create them via an adapter.\n *\n * {@link Mapper#beforeCreateMany} will be called before calling the adapter.\n * {@link Mapper#afterCreateMany} will be called after calling the adapter.\n *\n * @example\n * // Create and save several new blog posts\n * PostMapper.createMany([{\n * title: 'Modeling your data',\n * status: 'draft'\n * }, {\n * title: 'Reading data',\n * status: 'draft'\n * }]).then((posts) => {\n * console.log(posts[0]); // { id: 1234, status: 'draft', ... }\n * console.log(posts[1]); // { id: 1235, status: 'draft', ... }\n * });\n *\n * @fires Mapper#beforeCreate\n * @fires Mapper#afterCreate\n * @method Mapper#createMany\n * @param {Record[]} records Array of records to be created in one batch.\n * @param {object} [opts] Configuration options. Refer to the `createMany`\n * method of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @param {string[]} [opts.with=[]] Relations to create in a cascading\n * create if `records` contains nested relations. NOT performed in a\n * transaction. Each nested create will result in another {@link Mapper#createMany}\n * call.\n * @param {string[]} [opts.pass=[]] Relations to send to the adapter as part\n * of the payload. Normally relations are not sent.\n * @returns {Promise} Resolves with the created records.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/saving-data\",\"Saving data\"]\n */\n createMany (records, opts) {\n // Default values for arguments\n records || (records = [])\n opts || (opts = {})\n const originalRecords = records\n let adapterResponse\n\n // Fill in \"opts\" with the Mapper's configuration\n utils._(opts, this)\n opts.adapter = this.getAdapterName(opts)\n\n // beforeCreateMany lifecycle hook\n opts.op = 'beforeCreateMany'\n return this._runHook(opts.op, records, opts).then((records) => {\n // Deep pre-create belongsTo relations\n const belongsToRelationData = {}\n opts.with || (opts.with = [])\n let tasks = []\n utils.forEachRelation(this, opts, (def, optsCopy) => {\n const relationData = records\n .map((record) => def.getLocalField(record))\n .filter(Boolean)\n if (def.type === belongsToType && relationData.length === records.length) {\n // Create belongsTo relation first because we need a generated id to\n // attach to the child\n optsCopy.raw = false\n tasks.push(def.createLinked(relationData, optsCopy).then((relatedRecords) => {\n records.forEach((record, i) => def.setForeignKey(record, relatedRecords[i]))\n }).then((relatedRecords) => {\n def.setLocalField(belongsToRelationData, relatedRecords)\n }))\n }\n })\n return utils.Promise.all(tasks).then(() => {\n opts.op = 'createMany'\n return this._invokeAdapterMethod(opts.op, records, opts)\n }).then((result) => {\n adapterResponse = result\n }).then(() => {\n const createdRecordsData = opts.raw ? adapterResponse.data : adapterResponse\n\n // Deep post-create hasOne relations\n tasks = []\n utils.forEachRelation(this, opts, (def, optsCopy) => {\n const relationData = records\n .map((record) => def.getLocalField(record))\n .filter(Boolean)\n if (relationData.length !== records.length) {\n return\n }\n\n optsCopy.raw = false\n const belongsToData = def.getLocalField(belongsToRelationData)\n let task\n // Create hasMany and hasOne after the main create because we needed\n // a generated id to attach to these items\n if (def.type === hasManyType) {\n // Not supported\n this.log('warn', 'deep createMany of hasMany type not supported!')\n } else if (def.type === hasOneType) {\n createdRecordsData.forEach((createdRecordData, i) => {\n def.setForeignKey(createdRecordData, relationData[i])\n })\n task = def.getRelation().createMany(relationData, optsCopy).then((relatedData) => {\n createdRecordsData.forEach((createdRecordData, i) => {\n def.setLocalField(createdRecordData, relatedData[i])\n })\n })\n } else if (def.type === belongsToType && belongsToData && belongsToData.length === createdRecordsData.length) {\n createdRecordsData.forEach((createdRecordData, i) => {\n def.setLocalField(createdRecordData, belongsToData[i])\n })\n }\n if (task) {\n tasks.push(task)\n }\n })\n return utils.Promise.all(tasks).then(() => {\n return this._commitChanges(originalRecords, createdRecordsData)\n })\n })\n }).then((records) => {\n if (opts.raw) {\n adapterResponse.data = records\n } else {\n adapterResponse = records\n }\n const result = this._end(adapterResponse, opts)\n opts.op = 'afterCreateMany'\n return this._runHook(opts.op, records, opts, result)\n })\n },\n\n /**\n * Create an unsaved, uncached instance of this Mapper's\n * {@link Mapper#recordClass}.\n *\n * Returns `props` if `props` is already an instance of\n * {@link Mapper#recordClass}.\n *\n * __Note:__ This method does __not__ interact with any adapter, and does\n * __not__ save any data. It only creates new objects in memory.\n *\n * @example\n * // Create empty unsaved record instance\n * const post = PostMapper.createRecord();\n *\n * @example\n * // Create an unsaved record instance with inital properties\n * const post = PostMapper.createRecord({\n * title: 'Modeling your data',\n * status: 'draft'\n * });\n *\n * @example\n * // Create a record instance that corresponds to a saved record\n * const post = PostMapper.createRecord({\n * // JSData thinks this record has been saved if it has a primary key\n * id: 1234,\n * title: 'Modeling your data',\n * status: 'draft'\n * });\n *\n * @example\n * // Create record instances from an array\n * const posts = PostMapper.createRecord([{\n * title: 'Modeling your data',\n * status: 'draft'\n * }, {\n * title: 'Reading data',\n * status: 'draft'\n * }]);\n *\n * @example\n * // Records are validated by default\n * import { Mapper } from 'js-data';\n * const PostMapper = new Mapper({\n * name: 'post',\n * schema: { properties: { title: { type: 'string' } } }\n * });\n * try {\n * const post = PostMapper.createRecord({\n * title: 1234,\n * });\n * } catch (err) {\n * console.log(err.errors); // [{ expected: 'one of (string)', actual: 'number', path: 'title' }]\n * }\n *\n * @example\n * // Skip validation\n * import { Mapper } from 'js-data';\n * const PostMapper = new Mapper({\n * name: 'post',\n * schema: { properties: { title: { type: 'string' } } }\n * });\n * const post = PostMapper.createRecord({\n * title: 1234,\n * }, { noValidate: true });\n * console.log(post.isValid()); // false\n *\n * @method Mapper#createRecord\n * @param {Object|Object[]} props The properties for the Record instance or an\n * array of property objects for the Record instances.\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}.\n * @returns {Record|Record[]} The Record instance or Record instances.\n * @since 3.0.0\n */\n createRecord (props, opts) {\n props || (props = {})\n if (utils.isArray(props)) {\n return props.map((_props) => this.createRecord(_props, opts))\n }\n if (!utils.isObject(props)) {\n throw utils.err(`${DOMAIN}#createRecord`, 'props')(400, 'array or object', props)\n }\n\n if (this.relationList) {\n this.relationList.forEach(function (def) {\n def.ensureLinkedDataHasProperType(props, opts)\n })\n }\n const RecordCtor = this.recordClass\n\n return (!RecordCtor || props instanceof RecordCtor) ? props : new RecordCtor(props, opts)\n },\n\n /**\n * Lifecycle invocation method. You probably won't call this method directly.\n *\n * @method Mapper#crud\n * @param {string} method Name of the lifecycle method to invoke.\n * @param {...*} args Arguments to pass to the lifecycle method.\n * @returns {Promise}\n * @since 3.0.0\n */\n crud (method, ...args) {\n const config = this.lifecycleMethods[method]\n if (!config) {\n throw utils.err(`${DOMAIN}#crud`, method)(404, 'method')\n }\n\n const upper = `${method.charAt(0).toUpperCase()}${method.substr(1)}`\n const before = `before${upper}`\n const after = `after${upper}`\n\n let op, adapter\n\n // Default values for arguments\n config.defaults.forEach((value, i) => {\n if (args[i] === undefined) {\n args[i] = utils.copy(value)\n }\n })\n\n const opts = args[args.length - 1]\n\n // Fill in \"opts\" with the Mapper's configuration\n utils._(opts, this)\n adapter = opts.adapter = this.getAdapterName(opts)\n\n // before lifecycle hook\n op = opts.op = before\n return utils.resolve(this[op](...args)).then((_value) => {\n if (args[config.beforeAssign] !== undefined) {\n // Allow for re-assignment from lifecycle hook\n args[config.beforeAssign] = _value === undefined ? args[config.beforeAssign] : _value\n }\n // Now delegate to the adapter\n op = opts.op = method\n args = config.adapterArgs ? config.adapterArgs(this, ...args) : args\n this.dbg(op, ...args)\n return utils.resolve(this.getAdapter(adapter)[op](this, ...args))\n }).then((result) => {\n result = this._end(result, opts, !!config.skip)\n args.push(result)\n // after lifecycle hook\n op = opts.op = after\n return utils.resolve(this[op](...args)).then((_result) => {\n // Allow for re-assignment from lifecycle hook\n return _result === undefined ? result : _result\n })\n })\n },\n\n /**\n * Fired during {@link Mapper#destroy}. See\n * {@link Mapper~beforeDestroyListener} for how to listen for this event.\n *\n * @event Mapper#beforeDestroy\n * @see Mapper~beforeDestroyListener\n * @see Mapper#destroy\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeDestroy} event.\n *\n * @example\n * function onBeforeDestroy (id, opts) {\n * // do something\n * }\n * store.on('beforeDestroy', onBeforeDestroy);\n *\n * @callback Mapper~beforeDestroyListener\n * @param {string|number} id The `id` argument passed to {@link Mapper#beforeDestroy}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#beforeDestroy}.\n * @see Mapper#event:beforeDestroy\n * @see Mapper#destroy\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#destroy}. See\n * {@link Mapper~afterDestroyListener} for how to listen for this event.\n *\n * @event Mapper#afterDestroy\n * @see Mapper~afterDestroyListener\n * @see Mapper#destroy\n */\n /**\n * Callback signature for the {@link Mapper#event:afterDestroy} event.\n *\n * @example\n * function onAfterDestroy (id, opts, result) {\n * // do something\n * }\n * store.on('afterDestroy', onAfterDestroy);\n *\n * @callback Mapper~afterDestroyListener\n * @param {string|number} id The `id` argument passed to {@link Mapper#afterDestroy}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#afterDestroy}.\n * @param {object} result The `result` argument passed to {@link Mapper#afterDestroy}.\n * @see Mapper#event:afterDestroy\n * @see Mapper#destroy\n * @since 3.0.0\n */\n /**\n * Using an adapter, destroy the record with the given primary key.\n *\n * {@link Mapper#beforeDestroy} will be called before destroying the record.\n * {@link Mapper#afterDestroy} will be called after destroying the record.\n *\n * @example\n * // Destroy a specific blog post\n * PostMapper.destroy(1234).then(() => {\n * // Blog post #1234 has been destroyed\n * });\n *\n * @example\n * // Get full response\n * PostMapper.destroy(1234, { raw: true }).then((result) => {\n * console.log(result.deleted); e.g. 1\n * console.log(...); // etc., more metadata can be found on the result\n * });\n *\n * @fires Mapper#beforeDestroy\n * @fires Mapper#afterDestroy\n * @method Mapper#destroy\n * @param {(string|number)} id The primary key of the record to destroy.\n * @param {object} [opts] Configuration options. Refer to the `destroy` method\n * of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @returns {Promise} Resolves when the record has been destroyed. Resolves\n * even if no record was found to be destroyed.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/saving-data\",\"Saving data\"]\n */\n destroy (id, opts) {\n return this.crud('destroy', id, opts)\n },\n\n /**\n * Fired during {@link Mapper#destroyAll}. See\n * {@link Mapper~beforeDestroyAllListener} for how to listen for this event.\n *\n * @event Mapper#beforeDestroyAll\n * @see Mapper~beforeDestroyAllListener\n * @see Mapper#destroyAll\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeDestroyAll} event.\n *\n * @example\n * function onBeforeDestroyAll (query, opts) {\n * // do something\n * }\n * store.on('beforeDestroyAll', onBeforeDestroyAll);\n *\n * @callback Mapper~beforeDestroyAllListener\n * @param {object} query The `query` argument passed to {@link Mapper#beforeDestroyAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#beforeDestroyAll}.\n * @see Mapper#event:beforeDestroyAll\n * @see Mapper#destroyAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#destroyAll}. See\n * {@link Mapper~afterDestroyAllListener} for how to listen for this event.\n *\n * @event Mapper#afterDestroyAll\n * @see Mapper~afterDestroyAllListener\n * @see Mapper#destroyAll\n */\n /**\n * Callback signature for the {@link Mapper#event:afterDestroyAll} event.\n *\n * @example\n * function onAfterDestroyAll (query, opts, result) {\n * // do something\n * }\n * store.on('afterDestroyAll', onAfterDestroyAll);\n *\n * @callback Mapper~afterDestroyAllListener\n * @param {object} query The `query` argument passed to {@link Mapper#afterDestroyAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#afterDestroyAll}.\n * @param {object} result The `result` argument passed to {@link Mapper#afterDestroyAll}.\n * @see Mapper#event:afterDestroyAll\n * @see Mapper#destroyAll\n * @since 3.0.0\n */\n /**\n * Destroy the records selected by `query` via an adapter. If no `query` is\n * provided then all records will be destroyed.\n *\n * {@link Mapper#beforeDestroyAll} will be called before destroying the records.\n * {@link Mapper#afterDestroyAll} will be called after destroying the records.\n *\n * @example\n * // Destroy all blog posts\n * PostMapper.destroyAll().then(() => {\n * // All blog posts have been destroyed\n * });\n *\n * @example\n * // Destroy all \"draft\" blog posts\n * PostMapper.destroyAll({ status: 'draft' }).then(() => {\n * // All \"draft\" blog posts have been destroyed\n * });\n *\n * @example\n * // Get full response\n * const query = null;\n * const options = { raw: true };\n * PostMapper.destroyAll(query, options).then((result) => {\n * console.log(result.deleted); e.g. 14\n * console.log(...); // etc., more metadata can be found on the result\n * });\n *\n * @fires Mapper#beforeDestroyAll\n * @fires Mapper#afterDestroyAll\n * @method Mapper#destroyAll\n * @param {object} [query={}] Selection query. See {@link query}.\n * @param {object} [query.where] See {@link query.where}.\n * @param {number} [query.offset] See {@link query.offset}.\n * @param {number} [query.limit] See {@link query.limit}.\n * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}.\n * @param {object} [opts] Configuration options. Refer to the `destroyAll`\n * method of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @returns {Promise} Resolves when the records have been destroyed. Resolves\n * even if no records were found to be destroyed.\n * @see query\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/saving-data\",\"Saving data\"]\n */\n destroyAll (query, opts) {\n return this.crud('destroyAll', query, opts)\n },\n\n /**\n * Fired during {@link Mapper#find}. See\n * {@link Mapper~beforeFindListener} for how to listen for this event.\n *\n * @event Mapper#beforeFind\n * @see Mapper~beforeFindListener\n * @see Mapper#find\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeFind} event.\n *\n * @example\n * function onBeforeFind (id, opts) {\n * // do something\n * }\n * store.on('beforeFind', onBeforeFind);\n *\n * @callback Mapper~beforeFindListener\n * @param {string|number} id The `id` argument passed to {@link Mapper#beforeFind}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#beforeFind}.\n * @see Mapper#event:beforeFind\n * @see Mapper#find\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#find}. See\n * {@link Mapper~afterFindListener} for how to listen for this event.\n *\n * @event Mapper#afterFind\n * @see Mapper~afterFindListener\n * @see Mapper#find\n */\n /**\n * Callback signature for the {@link Mapper#event:afterFind} event.\n *\n * @example\n * function onAfterFind (id, opts, result) {\n * // do something\n * }\n * store.on('afterFind', onAfterFind);\n *\n * @callback Mapper~afterFindListener\n * @param {string|number} id The `id` argument passed to {@link Mapper#afterFind}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#afterFind}.\n * @param {object} result The `result` argument passed to {@link Mapper#afterFind}.\n * @see Mapper#event:afterFind\n * @see Mapper#find\n * @since 3.0.0\n */\n /**\n * Retrieve via an adapter the record with the given primary key.\n *\n * {@link Mapper#beforeFind} will be called before calling the adapter.\n * {@link Mapper#afterFind} will be called after calling the adapter.\n *\n * @example\n * PostMapper.find(1).then((post) => {\n * console.log(post); // { id: 1, ...}\n * });\n *\n * @example\n * // Get full response\n * PostMapper.find(1, { raw: true }).then((result) => {\n * console.log(result.data); // { id: 1, ...}\n * console.log(result.found); // 1\n * console.log(...); // etc., more metadata can be found on the result\n * });\n *\n * @fires Mapper#beforeFind\n * @fires Mapper#afterFind\n * @method Mapper#find\n * @param {(string|number)} id The primary key of the record to retrieve.\n * @param {object} [opts] Configuration options. Refer to the `find` method\n * of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @param {string[]} [opts.with=[]] Relations to eager load in the request.\n * @returns {Promise} Resolves with the found record. Resolves with\n * `undefined` if no record was found.\n * @see http://www.js-data.io/v3.0/docs/reading-data\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/reading-data\",\"Reading data\"]\n */\n find (id, opts) {\n return this.crud('find', id, opts)\n },\n\n /**\n * Fired during {@link Mapper#findAll}. See\n * {@link Mapper~beforeFindAllListener} for how to listen for this event.\n *\n * @event Mapper#beforeFindAll\n * @see Mapper~beforeFindAllListener\n * @see Mapper#findAll\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeFindAll} event.\n *\n * @example\n * function onBeforeFindAll (query, opts) {\n * // do something\n * }\n * store.on('beforeFindAll', onBeforeFindAll);\n *\n * @callback Mapper~beforeFindAllListener\n * @param {object} query The `query` argument passed to {@link Mapper#beforeFindAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#beforeFindAll}.\n * @see Mapper#event:beforeFindAll\n * @see Mapper#findAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#findAll}. See\n * {@link Mapper~afterFindAllListener} for how to listen for this event.\n *\n * @event Mapper#afterFindAll\n * @see Mapper~afterFindAllListener\n * @see Mapper#findAll\n */\n /**\n * Callback signature for the {@link Mapper#event:afterFindAll} event.\n *\n * @example\n * function onAfterFindAll (query, opts, result) {\n * // do something\n * }\n * store.on('afterFindAll', onAfterFindAll);\n *\n * @callback Mapper~afterFindAllListener\n * @param {object} query The `query` argument passed to {@link Mapper#afterFindAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#afterFindAll}.\n * @param {object} result The `result` argument passed to {@link Mapper#afterFindAll}.\n * @see Mapper#event:afterFindAll\n * @see Mapper#findAll\n * @since 3.0.0\n */\n /**\n * Using the `query` argument, select records to retrieve via an adapter.\n *\n * {@link Mapper#beforeFindAll} will be called before calling the adapter.\n * {@link Mapper#afterFindAll} will be called after calling the adapter.\n *\n * @example\n * // Find all \"published\" blog posts\n * PostMapper.findAll({ status: 'published' }).then((posts) => {\n * console.log(posts); // [{ id: 1, status: 'published', ...}, ...]\n * });\n *\n * @example\n * // Get full response\n * PostMapper.findAll({ status: 'published' }, { raw: true }).then((result) => {\n * console.log(result.data); // [{ id: 1, status: 'published', ...}, ...]\n * console.log(result.found); // e.g. 13\n * console.log(...); // etc., more metadata can be found on the result\n * });\n *\n * @fires Mapper#beforeFindAll\n * @fires Mapper#afterFindAll\n * @method Mapper#findAll\n * @param {object} [query={}] Selection query. See {@link query}.\n * @param {object} [query.where] See {@link query.where}.\n * @param {number} [query.offset] See {@link query.offset}.\n * @param {number} [query.limit] See {@link query.limit}.\n * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}.\n * @param {object} [opts] Configuration options. Refer to the `findAll` method\n * of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @param {string[]} [opts.with=[]] Relations to eager load in the request.\n * @returns {Promise} Resolves with the found records, if any.\n * @see query\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/reading-data\",\"Reading data\"]\n */\n findAll (query, opts) {\n return this.crud('findAll', query, opts)\n },\n\n /**\n * Return the registered adapter with the given name or the default adapter if\n * no name is provided.\n *\n * @method Mapper#getAdapter\n * @param {string} [name] The name of the adapter to retrieve.\n * @returns {Adapter} The adapter.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/connecting-to-a-data-source\",\"Connecting to a data source\"]\n */\n getAdapter (name) {\n this.dbg('getAdapter', 'name:', name)\n const adapter = this.getAdapterName(name)\n if (!adapter) {\n throw utils.err(`${DOMAIN}#getAdapter`, 'name')(400, 'string', name)\n }\n return this.getAdapters()[adapter]\n },\n\n /**\n * Return the name of a registered adapter based on the given name or options,\n * or the name of the default adapter if no name provided.\n *\n * @method Mapper#getAdapterName\n * @param {(Object|string)} [opts] The name of an adapter or options, if any.\n * @returns {string} The name of the adapter.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/connecting-to-a-data-source\",\"Connecting to a data source\"]\n */\n getAdapterName (opts) {\n opts || (opts = {})\n if (utils.isString(opts)) {\n opts = { adapter: opts }\n }\n return opts.adapter || opts.defaultAdapter\n },\n\n /**\n * Get the object of registered adapters for this Mapper.\n *\n * @method Mapper#getAdapters\n * @returns {Object} {@link Mapper#_adapters}\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/connecting-to-a-data-source\",\"Connecting to a data source\"]\n */\n getAdapters () {\n return this._adapters\n },\n\n /**\n * Returns this Mapper's {@link Schema}.\n *\n * @method Mapper#getSchema\n * @returns {Schema} This Mapper's {@link Schema}.\n * @see Mapper#schema\n * @since 3.0.0\n */\n getSchema () {\n return this.schema\n },\n\n /**\n * Defines a hasMany relationship. Only useful if you're managing your\n * Mappers manually and not using a Container or DataStore component.\n *\n * @example\n * UserMapper.hasMany(PostMapper, {\n * // post.user_id points to user.id\n * foreignKey: 'user_id'\n * // post records will be attached to user records at \"user.posts\"\n * localField: 'posts'\n * });\n *\n * @method Mapper#hasMany\n * @see http://www.js-data.io/v3.0/docs/relations\n * @since 3.0.0\n */\n hasMany (relatedMapper, opts) {\n return hasMany(relatedMapper, opts)(this)\n },\n\n /**\n * Defines a hasOne relationship. Only useful if you're managing your Mappers\n * manually and not using a {@link Container} or {@link DataStore} component.\n *\n * @example\n * UserMapper.hasOne(ProfileMapper, {\n * // profile.user_id points to user.id\n * foreignKey: 'user_id'\n * // profile records will be attached to user records at \"user.profile\"\n * localField: 'profile'\n * });\n *\n * @method Mapper#hasOne\n * @see http://www.js-data.io/v3.0/docs/relations\n * @since 3.0.0\n */\n hasOne (relatedMapper, opts) {\n return hasOne(relatedMapper, opts)(this)\n },\n\n /**\n * Return whether `record` is an instance of this Mapper's recordClass.\n *\n * @example\n * const post = PostMapper.createRecord();\n *\n * console.log(PostMapper.is(post)); // true\n * // Equivalent to what's above\n * console.log(post instanceof PostMapper.recordClass); // true\n *\n * @method Mapper#is\n * @param {Object|Record} record The record to check.\n * @returns {boolean} Whether `record` is an instance of this Mapper's\n * {@link Mapper#recordClass}.\n * @since 3.0.0\n */\n is (record) {\n const recordClass = this.recordClass\n return recordClass ? record instanceof recordClass : false\n },\n\n /**\n * Register an adapter on this Mapper under the given name.\n *\n * @method Mapper#registerAdapter\n * @param {string} name The name of the adapter to register.\n * @param {Adapter} adapter The adapter to register.\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.default=false] Whether to make the adapter the\n * default adapter for this Mapper.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/connecting-to-a-data-source\",\"Connecting to a data source\"]\n */\n registerAdapter (name, adapter, opts) {\n opts || (opts = {})\n this.getAdapters()[name] = adapter\n // Optionally make it the default adapter for the target.\n if (opts === true || opts.default) {\n this.defaultAdapter = name\n }\n },\n\n _runHook (hookName, ...hookArgs) {\n const defaultValueIndex = hookName.indexOf('after') === 0 ? hookArgs.length - 1 : 0\n\n return utils.resolve(this[hookName](...hookArgs))\n .then((overridenResult) => overridenResult === undefined ? hookArgs[defaultValueIndex] : overridenResult)\n },\n\n _invokeAdapterMethod (method, propsOrRecords, opts) {\n const conversionOptions = { with: opts.pass || [] }\n let object\n\n this.dbg(opts.op, propsOrRecords, opts)\n\n if (utils.isArray(propsOrRecords)) {\n object = propsOrRecords.map(record => this.toJSON(record, conversionOptions))\n } else {\n object = this.toJSON(propsOrRecords, conversionOptions)\n }\n\n return this.getAdapter(opts.adapter)[method](this, object, opts)\n },\n\n /**\n * Select records according to the `query` argument, and aggregate the sum\n * value of the property specified by `field`.\n *\n * {@link Mapper#beforeSum} will be called before calling the adapter.\n * {@link Mapper#afterSum} will be called after calling the adapter.\n *\n * @example\n * PurchaseOrderMapper.sum('amount', { status: 'paid' }).then((amountPaid) => {\n * console.log(amountPaid); // e.g. 451125.34\n * });\n *\n * @method Mapper#sum\n * @param {string} field The field to sum.\n * @param {object} [query={}] Selection query. See {@link query}.\n * @param {object} [query.where] See {@link query.where}.\n * @param {number} [query.offset] See {@link query.offset}.\n * @param {number} [query.limit] See {@link query.limit}.\n * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}.\n * @param {object} [opts] Configuration options. Refer to the `sum` method\n * of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @returns {Promise} Resolves with the aggregated sum.\n * @since 3.0.0\n */\n sum (field, query, opts) {\n return this.crud('sum', field, query, opts)\n },\n\n /**\n * Return a plain object representation of the given record. Relations can\n * be optionally be included. Non-schema properties can be excluded.\n *\n * @example\n * import { Mapper, Schema } from 'js-data';\n * const PersonMapper = new Mapper({\n * name: 'person',\n * schema: {\n * properties: {\n * name: { type: 'string' },\n * id: { type: 'string' }\n * }\n * }\n * });\n * const person = PersonMapper.createRecord({ id: 1, name: 'John', foo: 'bar' });\n * // \"foo\" is stripped by toJSON()\n * console.log(PersonMapper.toJSON(person)); // {\"id\":1,\"name\":\"John\"}\n *\n * const PersonRelaxedMapper = new Mapper({\n * name: 'personRelaxed',\n * schema: {\n * properties: {\n * name: { type: 'string' },\n * id: { type: 'string' }\n * },\n * additionalProperties: true\n * }\n * });\n * const person2 = PersonRelaxedMapper.createRecord({ id: 1, name: 'John', foo: 'bar' });\n * // \"foo\" is not stripped by toJSON\n * console.log(PersonRelaxedMapper.toJSON(person2)); // {\"id\":1,\"name\":\"John\",\"foo\":\"bar\"}\n *\n * @method Mapper#toJSON\n * @param {Record|Record[]} records Record or records from which to create a\n * POJO representation.\n * @param {object} [opts] Configuration options.\n * @param {string[]} [opts.with] Array of relation names or relation fields\n * to include in the POJO representation.\n * @param {boolean} [opts.withAll] Whether to simply include all relations in\n * the representation. Overrides `opts.with`.\n * @returns {Object|Object[]} POJO representation of the record or records.\n * @since 3.0.0\n */\n toJSON (records, opts) {\n let record\n opts || (opts = {})\n if (utils.isArray(records)) {\n return records.map((record) => this.toJSON(record, opts))\n } else {\n record = records\n }\n const relationFields = (this ? this.relationFields : []) || []\n let json = {}\n\n // Copy properties defined in the schema\n if (this && this.schema) {\n json = this.schema.pick(record)\n } else {\n for (var key in record) {\n if (relationFields.indexOf(key) === -1) {\n json[key] = utils.plainCopy(record[key])\n }\n }\n }\n\n // The user wants to include relations in the resulting plain object representation\n if (this && opts.withAll) {\n opts.with = relationFields.slice()\n }\n if (this && opts.with) {\n if (utils.isString(opts.with)) {\n opts.with = [opts.with]\n }\n utils.forEachRelation(this, opts, (def, optsCopy) => {\n const relationData = def.getLocalField(record)\n if (relationData) {\n // The actual recursion\n if (utils.isArray(relationData)) {\n def.setLocalField(json, relationData.map((item) => {\n return def.getRelation().toJSON(item, optsCopy)\n }))\n } else {\n def.setLocalField(json, def.getRelation().toJSON(relationData, optsCopy))\n }\n }\n })\n }\n return json\n },\n\n /**\n * Fired during {@link Mapper#update}. See\n * {@link Mapper~beforeUpdateListener} for how to listen for this event.\n *\n * @event Mapper#beforeUpdate\n * @see Mapper~beforeUpdateListener\n * @see Mapper#update\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeUpdate} event.\n *\n * @example\n * function onBeforeUpdate (id, props, opts) {\n * // do something\n * }\n * store.on('beforeUpdate', onBeforeUpdate);\n *\n * @callback Mapper~beforeUpdateListener\n * @param {string|number} id The `id` argument passed to {@link Mapper#beforeUpdate}.\n * @param {object} props The `props` argument passed to {@link Mapper#beforeUpdate}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#beforeUpdate}.\n * @see Mapper#event:beforeUpdate\n * @see Mapper#update\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#update}. See\n * {@link Mapper~afterUpdateListener} for how to listen for this event.\n *\n * @event Mapper#afterUpdate\n * @see Mapper~afterUpdateListener\n * @see Mapper#update\n */\n /**\n * Callback signature for the {@link Mapper#event:afterUpdate} event.\n *\n * @example\n * function onAfterUpdate (id, props, opts, result) {\n * // do something\n * }\n * store.on('afterUpdate', onAfterUpdate);\n *\n * @callback Mapper~afterUpdateListener\n * @param {string|number} id The `id` argument passed to {@link Mapper#afterUpdate}.\n * @param {object} props The `props` argument passed to {@link Mapper#afterUpdate}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#afterUpdate}.\n * @param {object} result The `result` argument passed to {@link Mapper#afterUpdate}.\n * @see Mapper#event:afterUpdate\n * @see Mapper#update\n * @since 3.0.0\n */\n /**\n * Using an adapter, update the record with the primary key specified by the\n * `id` argument.\n *\n * {@link Mapper#beforeUpdate} will be called before updating the record.\n * {@link Mapper#afterUpdate} will be called after updating the record.\n *\n * @example\n * // Update a specific post\n * PostMapper.update(1234, {\n * status: 'published',\n * published_at: new Date()\n * }).then((post) => {\n * console.log(post); // { id: 1234, status: 'published', ... }\n * });\n *\n * @fires Mapper#beforeUpdate\n * @fires Mapper#afterUpdate\n * @method Mapper#update\n * @param {(string|number)} id The primary key of the record to update.\n * @param {object} props The update to apply to the record.\n * @param {object} [opts] Configuration options. Refer to the `update` method\n * of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * transaction.\n * @returns {Promise} Resolves with the updated record. Rejects if the record\n * could not be found.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/saving-data\",\"Saving data\"]\n */\n update (id, props, opts) {\n return this.crud('update', id, props, opts)\n },\n\n /**\n * Fired during {@link Mapper#updateAll}. See\n * {@link Mapper~beforeUpdateAllListener} for how to listen for this event.\n *\n * @event Mapper#beforeUpdateAll\n * @see Mapper~beforeUpdateAllListener\n * @see Mapper#updateAll\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeUpdateAll} event.\n *\n * @example\n * function onBeforeUpdateAll (props, query, opts) {\n * // do something\n * }\n * store.on('beforeUpdateAll', onBeforeUpdateAll);\n *\n * @callback Mapper~beforeUpdateAllListener\n * @param {object} props The `props` argument received by {@link Mapper#beforeUpdateAll}.\n * @param {object} query The `query` argument received by {@link Mapper#beforeUpdateAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateAll}.\n * @see Mapper#event:beforeUpdateAll\n * @see Mapper#updateAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#updateAll}. See\n * {@link Mapper~afterUpdateAllListener} for how to listen for this event.\n *\n * @event Mapper#afterUpdateAll\n * @see Mapper~afterUpdateAllListener\n * @see Mapper#updateAll\n */\n /**\n * Callback signature for the {@link Mapper#event:afterUpdateAll} event.\n *\n * @example\n * function onAfterUpdateAll (props, query, opts, result) {\n * // do something\n * }\n * store.on('afterUpdateAll', onAfterUpdateAll);\n *\n * @callback Mapper~afterUpdateAllListener\n * @param {object} props The `props` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} query The `query` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} result The `result` argument received by {@link Mapper#afterUpdateAll}.\n * @see Mapper#event:afterUpdateAll\n * @see Mapper#updateAll\n * @since 3.0.0\n */\n /**\n * Using the `query` argument, perform the a single updated to the selected\n * records.\n *\n * {@link Mapper#beforeUpdateAll} will be called before making the update.\n * {@link Mapper#afterUpdateAll} will be called after making the update.\n *\n * @example\n * // Turn all of John's blog posts into drafts.\n * const update = { status: draft: published_at: null };\n * const query = { userId: 1234 };\n * PostMapper.updateAll(update, query).then((posts) => {\n * console.log(posts); // [...]\n * });\n *\n * @fires Mapper#beforeUpdateAll\n * @fires Mapper#afterUpdateAll\n * @method Mapper#updateAll\n * @param {object} props Update to apply to selected records.\n * @param {object} [query={}] Selection query. See {@link query}.\n * @param {object} [query.where] See {@link query.where}.\n * @param {number} [query.offset] See {@link query.offset}.\n * @param {number} [query.limit] See {@link query.limit}.\n * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}.\n * @param {object} [opts] Configuration options. Refer to the `updateAll`\n * method of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @returns {Promise} Resolves with the update records, if any.\n * @see query\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/saving-data\",\"Saving data\"]\n */\n updateAll (props, query, opts) {\n return this.crud('updateAll', props, query, opts)\n },\n\n /**\n * Fired during {@link Mapper#updateMany}. See\n * {@link Mapper~beforeUpdateManyListener} for how to listen for this event.\n *\n * @event Mapper#beforeUpdateMany\n * @see Mapper~beforeUpdateManyListener\n * @see Mapper#updateMany\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeUpdateMany} event.\n *\n * @example\n * function onBeforeUpdateMany (records, opts) {\n * // do something\n * }\n * store.on('beforeUpdateMany', onBeforeUpdateMany);\n *\n * @callback Mapper~beforeUpdateManyListener\n * @param {object} records The `records` argument received by {@link Mapper#beforeUpdateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateMany}.\n * @see Mapper#event:beforeUpdateMany\n * @see Mapper#updateMany\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#updateMany}. See\n * {@link Mapper~afterUpdateManyListener} for how to listen for this event.\n *\n * @event Mapper#afterUpdateMany\n * @see Mapper~afterUpdateManyListener\n * @see Mapper#updateMany\n */\n /**\n * Callback signature for the {@link Mapper#event:afterUpdateMany} event.\n *\n * @example\n * function onAfterUpdateMany (records, opts, result) {\n * // do something\n * }\n * store.on('afterUpdateMany', onAfterUpdateMany);\n *\n * @callback Mapper~afterUpdateManyListener\n * @param {object} records The `records` argument received by {@link Mapper#afterUpdateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateMany}.\n * @param {object} result The `result` argument received by {@link Mapper#afterUpdateMany}.\n * @see Mapper#event:afterUpdateMany\n * @see Mapper#updateMany\n * @since 3.0.0\n */\n /**\n * Given an array of updates, perform each of the updates via an adapter. Each\n * \"update\" is a hash of properties with which to update an record. Each\n * update must contain the primary key of the record to be updated.\n *\n * {@link Mapper#beforeUpdateMany} will be called before making the update.\n * {@link Mapper#afterUpdateMany} will be called after making the update.\n *\n * @example\n * PostMapper.updateMany([\n * { id: 1234, status: 'draft' },\n * { id: 2468, status: 'published', published_at: new Date() }\n * ]).then((posts) => {\n * console.log(posts); // [...]\n * });\n *\n * @fires Mapper#beforeUpdateMany\n * @fires Mapper#afterUpdateMany\n * @method Mapper#updateMany\n * @param {Record[]} records Array up record updates.\n * @param {object} [opts] Configuration options. Refer to the `updateMany`\n * method of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @returns {Promise} Resolves with the updated records. Rejects if any of the\n * records could be found.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/saving-data\",\"Saving data\"]\n */\n updateMany (records, opts) {\n return this.crud('updateMany', records, opts)\n },\n\n /**\n * Validate the given record or records according to this Mapper's\n * {@link Schema}. If there are no validation errors then the return value\n * will be `undefined`.\n *\n * @example\n * import {Mapper, Schema} from 'js-data'\n * const PersonSchema = new Schema({\n * properties: {\n * name: { type: 'string' },\n * id: { type: 'string' }\n * }\n * });\n * const PersonMapper = new Mapper({\n * name: 'person',\n * schema: PersonSchema\n * });\n * let errors = PersonMapper.validate({ name: 'John' });\n * console.log(errors); // undefined\n * errors = PersonMapper.validate({ name: 123 });\n * console.log(errors); // [{ expected: 'one of (string)', actual: 'number', path: 'name' }]\n *\n * @method Mapper#validate\n * @param {Object|Object[]} record The record or records to validate.\n * @param {object} [opts] Configuration options. Passed to\n * {@link Schema#validate}.\n * @returns {Object[]} Array of errors or `undefined` if no errors.\n * @since 3.0.0\n */\n validate (record, opts) {\n opts || (opts = {})\n const schema = this.getSchema()\n if (!schema) {\n return\n }\n const _opts = utils.pick(opts, ['existingOnly'])\n if (utils.isArray(record)) {\n const errors = record.map((_record) => schema.validate(_record, utils.pick(_opts, ['existingOnly'])))\n\n return errors.some(Boolean) ? errors : undefined\n }\n return schema.validate(record, _opts)\n },\n\n /**\n * Method used to wrap data returned by an adapter with this Mapper's\n * {@link Mapper#recordClass}. This method is used by all of a Mapper's CRUD\n * methods. The provided implementation of this method assumes that the `data`\n * passed to it is a record or records that need to be wrapped with\n * {@link Mapper#createRecord}. Override with care.\n *\n * Provided implementation of {@link Mapper#wrap}:\n *\n * ```\n * function (data, opts) {\n * return this.createRecord(data, opts);\n * }\n * ```\n *\n * @example\n * const PostMapper = new Mapper({\n * name: 'post',\n * // Override to customize behavior\n * wrap (data, opts) {\n * const originalWrap = this.constructor.prototype.wrap;\n * // Let's say \"GET /post\" doesn't return JSON quite like JSData expects,\n * // but the actual post records are nested under a \"posts\" field. So,\n * // we override Mapper#wrap to handle this special case.\n * if (opts.op === 'findAll') {\n * return originalWrap.call(this, data.posts, opts);\n * }\n * // Otherwise perform original behavior\n * return originalWrap.call(this, data, opts);\n * }\n * });\n *\n * @method Mapper#wrap\n * @param {Object|Object[]} data The record or records to be wrapped.\n * @param {object} [opts] Configuration options. Passed to {@link Mapper#createRecord}.\n * @returns {Record|Record[]} The wrapped record or records.\n * @since 3.0.0\n */\n wrap (data, opts) {\n return this.createRecord(data, opts)\n },\n\n /**\n * @ignore\n */\n defineRelations () {\n // Setup the mapper's relations, including generating Mapper#relationList\n // and Mapper#relationFields\n utils.forOwn(this.relations, (group, type) => {\n utils.forOwn(group, (relations, _name) => {\n if (utils.isObject(relations)) {\n relations = [relations]\n }\n relations.forEach((def) => {\n const relatedMapper = this.datastore.getMapperByName(_name) || _name\n def.getRelation = () => this.datastore.getMapper(_name)\n\n if (typeof Relation[type] !== 'function') {\n throw utils.err(DOMAIN, 'defineRelations')(400, 'relation type (hasOne, hasMany, etc)', type, true)\n }\n\n this[type](relatedMapper, def)\n })\n })\n })\n }\n})\n\n/**\n * Create a subclass of this Mapper:\n *\n * @example Mapper.extend\n * const JSData = require('js-data');\n * const { Mapper } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomMapperClass extends Mapper {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * };\n * const customMapper = new CustomMapperClass();\n * console.log(customMapper.foo());\n * console.log(CustomMapperClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherMapperClass = Mapper.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherMapper = new OtherMapperClass();\n * console.log(otherMapper.foo());\n * console.log(OtherMapperClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherMapperClass () {\n * Mapper.call(this);\n * this.created_at = new Date().getTime();\n * }\n * Mapper.extend({\n * constructor: AnotherMapperClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * })\n * const anotherMapper = new AnotherMapperClass();\n * console.log(anotherMapper.created_at);\n * console.log(anotherMapper.foo());\n * console.log(AnotherMapperClass.beep());\n *\n * @method Mapper.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this Mapper class.\n * @since 3.0.0\n */\n","import utils from './utils'\nimport Component from './Component'\nimport Mapper from './Mapper'\n\nconst DOMAIN = 'Container'\n\nexport const proxiedMapperMethods = [\n /**\n * Wrapper for {@link Mapper#count}.\n *\n * @example\n * // Get the number of published blog posts\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.count('post', { status: 'published' }).then((numPublished) => {\n * console.log(numPublished); // e.g. 45\n * });\n *\n * @method Container#count\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} [query] See {@link Mapper#count}.\n * @param {object} [opts] See {@link Mapper#count}.\n * @returns {Promise} See {@link Mapper#count}.\n * @see Mapper#count\n * @since 3.0.0\n */\n 'count',\n\n /**\n * Fired during {@link Container#create}. See\n * {@link Container~beforeCreateListener} for how to listen for this event.\n *\n * @event Container#beforeCreate\n * @see Container~beforeCreateListener\n * @see Container#create\n */\n /**\n * Callback signature for the {@link Container#event:beforeCreate} event.\n *\n * @example\n * function onBeforeCreate (mapperName, props, opts) {\n * // do something\n * }\n * store.on('beforeCreate', onBeforeCreate);\n *\n * @callback Container~beforeCreateListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeCreate}.\n * @param {object} props The `props` argument received by {@link Mapper#beforeCreate}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreate}.\n * @see Container#event:beforeCreate\n * @see Container#create\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#create}. See\n * {@link Container~afterCreateListener} for how to listen for this event.\n *\n * @event Container#afterCreate\n * @see Container~afterCreateListener\n * @see Container#create\n */\n /**\n * Callback signature for the {@link Container#event:afterCreate} event.\n *\n * @example\n * function onAfterCreate (mapperName, props, opts, result) {\n * // do something\n * }\n * store.on('afterCreate', onAfterCreate);\n *\n * @callback Container~afterCreateListener\n * @param {string} name The `name` argument received by {@link Mapper#afterCreate}.\n * @param {object} props The `props` argument received by {@link Mapper#afterCreate}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterCreate}.\n * @param {object} result The `result` argument received by {@link Mapper#afterCreate}.\n * @see Container#event:afterCreate\n * @see Container#create\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#create}.\n *\n * @example\n * // Create and save a new blog post\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.create('post', {\n * title: 'Modeling your data',\n * status: 'draft'\n * }).then((post) => {\n * console.log(post); // { id: 1234, status: 'draft', ... }\n * });\n *\n * @fires Container#beforeCreate\n * @fires Container#afterCreate\n * @method Container#create\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} props See {@link Mapper#create}.\n * @param {object} [opts] See {@link Mapper#create}.\n * @returns {Promise} See {@link Mapper#create}.\n * @see Mapper#create\n * @since 3.0.0\n */\n 'create',\n\n /**\n * Fired during {@link Container#createMany}. See\n * {@link Container~beforeCreateManyListener} for how to listen for this event.\n *\n * @event Container#beforeCreateMany\n * @see Container~beforeCreateManyListener\n * @see Container#createMany\n */\n /**\n * Callback signature for the {@link Container#event:beforeCreateMany} event.\n *\n * @example\n * function onBeforeCreateMany (mapperName, records, opts) {\n * // do something\n * }\n * store.on('beforeCreateMany', onBeforeCreateMany);\n *\n * @callback Container~beforeCreateManyListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeCreateMany}.\n * @param {object} records The `records` argument received by {@link Mapper#beforeCreateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreateMany}.\n * @see Container#event:beforeCreateMany\n * @see Container#createMany\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#createMany}. See\n * {@link Container~afterCreateManyListener} for how to listen for this event.\n *\n * @event Container#afterCreateMany\n * @see Container~afterCreateManyListener\n * @see Container#createMany\n */\n /**\n * Callback signature for the {@link Container#event:afterCreateMany} event.\n *\n * @example\n * function onAfterCreateMany (mapperName, records, opts, result) {\n * // do something\n * }\n * store.on('afterCreateMany', onAfterCreateMany);\n *\n * @callback Container~afterCreateManyListener\n * @param {string} name The `name` argument received by {@link Mapper#afterCreateMany}.\n * @param {object} records The `records` argument received by {@link Mapper#afterCreateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterCreateMany}.\n * @param {object} result The `result` argument received by {@link Mapper#afterCreateMany}.\n * @see Container#event:afterCreateMany\n * @see Container#createMany\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#createMany}.\n *\n * @example\n * // Create and save several new blog posts\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.createMany('post', [{\n * title: 'Modeling your data',\n * status: 'draft'\n * }, {\n * title: 'Reading data',\n * status: 'draft'\n * }]).then((posts) => {\n * console.log(posts[0]); // { id: 1234, status: 'draft', ... }\n * console.log(posts[1]); // { id: 1235, status: 'draft', ... }\n * });\n *\n * @fires Container#beforeCreateMany\n * @fires Container#afterCreateMany\n * @method Container#createMany\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {Record[]} records See {@link Mapper#createMany}.\n * @param {object} [opts] See {@link Mapper#createMany}.\n * @returns {Promise} See {@link Mapper#createMany}.\n * @see Mapper#createMany\n * @since 3.0.0\n */\n 'createMany',\n\n /**\n * Wrapper for {@link Mapper#createRecord}.\n *\n * __Note:__ This method does __not__ interact with any adapter, and does\n * __not__ save any data. It only creates new objects in memory.\n *\n * @example\n * // Create empty unsaved record instance\n * import { Container } from 'js-data';\n * const store = new Container();\n * store.defineMapper('post');\n * const post = PostMapper.createRecord();\n *\n * @method Container#createRecord\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {Object|Object[]} props See {@link Mapper#createRecord}.\n * @param {object} [opts] See {@link Mapper#createRecord}.\n * @returns {Promise} See {@link Mapper#createRecord}.\n * @see Mapper#createRecord\n * @since 3.0.0\n */\n 'createRecord',\n\n /**\n * Fired during {@link Container#destroy}. See\n * {@link Container~beforeDestroyListener} for how to listen for this event.\n *\n * @event Container#beforeDestroy\n * @see Container~beforeDestroyListener\n * @see Container#destroy\n */\n /**\n * Callback signature for the {@link Container#event:beforeDestroy} event.\n *\n * @example\n * function onBeforeDestroy (mapperName, id, opts) {\n * // do something\n * }\n * store.on('beforeDestroy', onBeforeDestroy);\n *\n * @callback Container~beforeDestroyListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeDestroy}.\n * @param {string|number} id The `id` argument received by {@link Mapper#beforeDestroy}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroy}.\n * @see Container#event:beforeDestroy\n * @see Container#destroy\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#destroy}. See\n * {@link Container~afterDestroyListener} for how to listen for this event.\n *\n * @event Container#afterDestroy\n * @see Container~afterDestroyListener\n * @see Container#destroy\n */\n /**\n * Callback signature for the {@link Container#event:afterDestroy} event.\n *\n * @example\n * function onAfterDestroy (mapperName, id, opts, result) {\n * // do something\n * }\n * store.on('afterDestroy', onAfterDestroy);\n *\n * @callback Container~afterDestroyListener\n * @param {string} name The `name` argument received by {@link Mapper#afterDestroy}.\n * @param {string|number} id The `id` argument received by {@link Mapper#afterDestroy}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterDestroy}.\n * @param {object} result The `result` argument received by {@link Mapper#afterDestroy}.\n * @see Container#event:afterDestroy\n * @see Container#destroy\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#destroy}.\n *\n * @example\n * // Destroy a specific blog post\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.destroy('post', 1234).then(() => {\n * // Blog post #1234 has been destroyed\n * });\n *\n * @fires Container#beforeDestroy\n * @fires Container#afterDestroy\n * @method Container#destroy\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(string|number)} id See {@link Mapper#destroy}.\n * @param {object} [opts] See {@link Mapper#destroy}.\n * @returns {Promise} See {@link Mapper#destroy}.\n * @see Mapper#destroy\n * @since 3.0.0\n */\n 'destroy',\n\n /**\n * Fired during {@link Container#destroyAll}. See\n * {@link Container~beforeDestroyAllListener} for how to listen for this event.\n *\n * @event Container#beforeDestroyAll\n * @see Container~beforeDestroyAllListener\n * @see Container#destroyAll\n */\n /**\n * Callback signature for the {@link Container#event:beforeDestroyAll} event.\n *\n * @example\n * function onBeforeDestroyAll (mapperName, query, opts) {\n * // do something\n * }\n * store.on('beforeDestroyAll', onBeforeDestroyAll);\n *\n * @callback Container~beforeDestroyAllListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeDestroyAll}.\n * @param {object} query The `query` argument received by {@link Mapper#beforeDestroyAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroyAll}.\n * @see Container#event:beforeDestroyAll\n * @see Container#destroyAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#destroyAll}. See\n * {@link Container~afterDestroyAllListener} for how to listen for this event.\n *\n * @event Container#afterDestroyAll\n * @see Container~afterDestroyAllListener\n * @see Container#destroyAll\n */\n /**\n * Callback signature for the {@link Container#event:afterDestroyAll} event.\n *\n * @example\n * function onAfterDestroyAll (mapperName, query, opts, result) {\n * // do something\n * }\n * store.on('afterDestroyAll', onAfterDestroyAll);\n *\n * @callback Container~afterDestroyAllListener\n * @param {string} name The `name` argument received by {@link Mapper#afterDestroyAll}.\n * @param {object} query The `query` argument received by {@link Mapper#afterDestroyAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterDestroyAll}.\n * @param {object} result The `result` argument received by {@link Mapper#afterDestroyAll}.\n * @see Container#event:afterDestroyAll\n * @see Container#destroyAll\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#destroyAll}.\n *\n * @example\n * // Destroy all \"draft\" blog posts\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.destroyAll('post', { status: 'draft' }).then(() => {\n * // All \"draft\" blog posts have been destroyed\n * });\n *\n * @fires Container#beforeDestroyAll\n * @fires Container#afterDestroyAll\n * @method Container#destroyAll\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} [query] See {@link Mapper#destroyAll}.\n * @param {object} [opts] See {@link Mapper#destroyAll}.\n * @returns {Promise} See {@link Mapper#destroyAll}.\n * @see Mapper#destroyAll\n * @since 3.0.0\n */\n 'destroyAll',\n\n /**\n * Fired during {@link Container#find}. See\n * {@link Container~beforeFindListener} for how to listen for this event.\n *\n * @event Container#beforeFind\n * @see Container~beforeFindListener\n * @see Container#find\n */\n /**\n * Callback signature for the {@link Container#event:beforeFind} event.\n *\n * @example\n * function onBeforeFind (mapperName, id, opts) {\n * // do something\n * }\n * store.on('beforeFind', onBeforeFind);\n *\n * @callback Container~beforeFindListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeFind}.\n * @param {string|number} id The `id` argument received by {@link Mapper#beforeFind}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeFind}.\n * @see Container#event:beforeFind\n * @see Container#find\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#find}. See\n * {@link Container~afterFindListener} for how to listen for this event.\n *\n * @event Container#afterFind\n * @see Container~afterFindListener\n * @see Container#find\n */\n /**\n * Callback signature for the {@link Container#event:afterFind} event.\n *\n * @example\n * function onAfterFind (mapperName, id, opts, result) {\n * // do something\n * }\n * store.on('afterFind', onAfterFind);\n *\n * @callback Container~afterFindListener\n * @param {string} name The `name` argument received by {@link Mapper#afterFind}.\n * @param {string|number} id The `id` argument received by {@link Mapper#afterFind}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterFind}.\n * @param {object} result The `result` argument received by {@link Mapper#afterFind}.\n * @see Container#event:afterFind\n * @see Container#find\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#find}.\n *\n * @example\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.find('post', 1).then((post) => {\n * console.log(post) // { id: 1, ...}\n * });\n *\n * @fires Container#beforeFind\n * @fires Container#afterFind\n * @method Container#find\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(string|number)} id See {@link Mapper#find}.\n * @param {object} [opts] See {@link Mapper#find}.\n * @returns {Promise} See {@link Mapper#find}.\n * @see Mapper#find\n * @since 3.0.0\n */\n 'find',\n\n /**\n * Fired during {@link Container#findAll}. See\n * {@link Container~beforeFindAllListener} for how to listen for this event.\n *\n * @event Container#beforeFindAll\n * @see Container~beforeFindAllListener\n * @see Container#findAll\n */\n /**\n * Callback signature for the {@link Container#event:beforeFindAll} event.\n *\n * @example\n * function onBeforeFindAll (mapperName, query, opts) {\n * // do something\n * }\n * store.on('beforeFindAll', onBeforeFindAll);\n *\n * @callback Container~beforeFindAllListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeFindAll}.\n * @param {object} query The `query` argument received by {@link Mapper#beforeFindAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeFindAll}.\n * @see Container#event:beforeFindAll\n * @see Container#findAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#findAll}. See\n * {@link Container~afterFindAllListener} for how to listen for this event.\n *\n * @event Container#afterFindAll\n * @see Container~afterFindAllListener\n * @see Container#findAll\n */\n /**\n * Callback signature for the {@link Container#event:afterFindAll} event.\n *\n * @example\n * function onAfterFindAll (mapperName, query, opts, result) {\n * // do something\n * }\n * store.on('afterFindAll', onAfterFindAll);\n *\n * @callback Container~afterFindAllListener\n * @param {string} name The `name` argument received by {@link Mapper#afterFindAll}.\n * @param {object} query The `query` argument received by {@link Mapper#afterFindAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterFindAll}.\n * @param {object} result The `result` argument received by {@link Mapper#afterFindAll}.\n * @see Container#event:afterFindAll\n * @see Container#findAll\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#createRecord}.\n *\n * @example\n * // Find all \"published\" blog posts\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.findAll('post', { status: 'published' }).then((posts) => {\n * console.log(posts); // [{ id: 1, ...}, ...]\n * });\n *\n * @fires Container#beforeFindAll\n * @fires Container#afterFindAll\n * @method Container#findAll\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} [query] See {@link Mapper#findAll}.\n * @param {object} [opts] See {@link Mapper#findAll}.\n * @returns {Promise} See {@link Mapper#findAll}.\n * @see Mapper#findAll\n * @since 3.0.0\n */\n 'findAll',\n\n /**\n * Wrapper for {@link Mapper#getSchema}.\n *\n * @method Container#getSchema\n * @param {string} name Name of the {@link Mapper} to target.\n * @returns {Schema} See {@link Mapper#getSchema}.\n * @see Mapper#getSchema\n * @since 3.0.0\n */\n 'getSchema',\n\n /**\n * Wrapper for {@link Mapper#is}.\n *\n * @example\n * import { Container } from 'js-data';\n * const store = new Container();\n * store.defineMapper('post');\n * const post = store.createRecord();\n *\n * console.log(store.is('post', post)); // true\n * // Equivalent to what's above\n * console.log(post instanceof store.getMapper('post').recordClass); // true\n *\n * @method Container#is\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {Object|Record} record See {@link Mapper#is}.\n * @returns {boolean} See {@link Mapper#is}.\n * @see Mapper#is\n * @since 3.0.0\n */\n 'is',\n\n /**\n * Wrapper for {@link Mapper#sum}.\n *\n * @example\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('purchase_order');\n *\n * store.sum('purchase_order', 'amount', { status: 'paid' }).then((amountPaid) => {\n * console.log(amountPaid); // e.g. 451125.34\n * });\n *\n * @method Container#sum\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {string} field See {@link Mapper#sum}.\n * @param {object} [query] See {@link Mapper#sum}.\n * @param {object} [opts] See {@link Mapper#sum}.\n * @returns {Promise} See {@link Mapper#sum}.\n * @see Mapper#sum\n * @since 3.0.0\n */\n 'sum',\n\n /**\n * Wrapper for {@link Mapper#toJSON}.\n *\n * @example\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('person', {\n * schema: {\n * properties: {\n * name: { type: 'string' },\n * id: { type: 'string' }\n * }\n * }\n * });\n * const person = store.createRecord('person', { id: 1, name: 'John', foo: 'bar' });\n * // \"foo\" is stripped by toJSON()\n * console.log(store.toJSON('person', person)); // {\"id\":1,\"name\":\"John\"}\n *\n * store.defineMapper('personRelaxed', {\n * schema: {\n * properties: {\n * name: { type: 'string' },\n * id: { type: 'string' }\n * },\n * additionalProperties: true\n * }\n * });\n * const person2 = store.createRecord('personRelaxed', { id: 1, name: 'John', foo: 'bar' });\n * // \"foo\" is not stripped by toJSON\n * console.log(store.toJSON('personRelaxed', person2)); // {\"id\":1,\"name\":\"John\",\"foo\":\"bar\"}\n *\n * @method Container#toJSON\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {Record|Record[]} records See {@link Mapper#toJSON}.\n * @param {object} [opts] See {@link Mapper#toJSON}.\n * @returns {Object|Object[]} See {@link Mapper#toJSON}.\n * @see Mapper#toJSON\n * @since 3.0.0\n */\n 'toJSON',\n\n /**\n * Fired during {@link Container#update}. See\n * {@link Container~beforeUpdateListener} for how to listen for this event.\n *\n * @event Container#beforeUpdate\n * @see Container~beforeUpdateListener\n * @see Container#update\n */\n /**\n * Callback signature for the {@link Container#event:beforeUpdate} event.\n *\n * @example\n * function onBeforeUpdate (mapperName, id, props, opts) {\n * // do something\n * }\n * store.on('beforeUpdate', onBeforeUpdate);\n *\n * @callback Container~beforeUpdateListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeUpdate}.\n * @param {string|number} id The `id` argument received by {@link Mapper#beforeUpdate}.\n * @param {object} props The `props` argument received by {@link Mapper#beforeUpdate}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdate}.\n * @see Container#event:beforeUpdate\n * @see Container#update\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#update}. See\n * {@link Container~afterUpdateListener} for how to listen for this event.\n *\n * @event Container#afterUpdate\n * @see Container~afterUpdateListener\n * @see Container#update\n */\n /**\n * Callback signature for the {@link Container#event:afterUpdate} event.\n *\n * @example\n * function onAfterUpdate (mapperName, id, props, opts, result) {\n * // do something\n * }\n * store.on('afterUpdate', onAfterUpdate);\n *\n * @callback Container~afterUpdateListener\n * @param {string} name The `name` argument received by {@link Mapper#afterUpdate}.\n * @param {string|number} id The `id` argument received by {@link Mapper#afterUpdate}.\n * @param {object} props The `props` argument received by {@link Mapper#afterUpdate}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdate}.\n * @param {object} result The `result` argument received by {@link Mapper#afterUpdate}.\n * @see Container#event:afterUpdate\n * @see Container#update\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#update}.\n *\n * @example\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.update('post', 1234, {\n * status: 'published',\n * published_at: new Date()\n * }).then((post) => {\n * console.log(post); // { id: 1234, status: 'published', ... }\n * });\n *\n * @fires Container#beforeUpdate\n * @fires Container#afterUpdate\n * @method Container#update\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(string|number)} id See {@link Mapper#update}.\n * @param {object} record See {@link Mapper#update}.\n * @param {object} [opts] See {@link Mapper#update}.\n * @returns {Promise} See {@link Mapper#update}.\n * @see Mapper#update\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/saving-data\",\"Saving data\"]\n */\n 'update',\n\n /**\n * Fired during {@link Container#updateAll}. See\n * {@link Container~beforeUpdateAllListener} for how to listen for this event.\n *\n * @event Container#beforeUpdateAll\n * @see Container~beforeUpdateAllListener\n * @see Container#updateAll\n */\n /**\n * Callback signature for the {@link Container#event:beforeUpdateAll} event.\n *\n * @example\n * function onBeforeUpdateAll (mapperName, props, query, opts) {\n * // do something\n * }\n * store.on('beforeUpdateAll', onBeforeUpdateAll);\n *\n * @callback Container~beforeUpdateAllListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeUpdateAll}.\n * @param {object} props The `props` argument received by {@link Mapper#beforeUpdateAll}.\n * @param {object} query The `query` argument received by {@link Mapper#beforeUpdateAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateAll}.\n * @see Container#event:beforeUpdateAll\n * @see Container#updateAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#updateAll}. See\n * {@link Container~afterUpdateAllListener} for how to listen for this event.\n *\n * @event Container#afterUpdateAll\n * @see Container~afterUpdateAllListener\n * @see Container#updateAll\n */\n /**\n * Callback signature for the {@link Container#event:afterUpdateAll} event.\n *\n * @example\n * function onAfterUpdateAll (mapperName, props, query, opts, result) {\n * // do something\n * }\n * store.on('afterUpdateAll', onAfterUpdateAll);\n *\n * @callback Container~afterUpdateAllListener\n * @param {string} name The `name` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} props The `props` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} query The `query` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} result The `result` argument received by {@link Mapper#afterUpdateAll}.\n * @see Container#event:afterUpdateAll\n * @see Container#updateAll\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#updateAll}.\n *\n * @example\n * // Turn all of John's blog posts into drafts.\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * const update = { status: draft: published_at: null };\n * const query = { userId: 1234 };\n * store.updateAll('post', update, query).then((posts) => {\n * console.log(posts); // [...]\n * });\n *\n * @fires Container#beforeUpdateAll\n * @fires Container#afterUpdateAll\n * @method Container#updateAll\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} update See {@link Mapper#updateAll}.\n * @param {object} [query] See {@link Mapper#updateAll}.\n * @param {object} [opts] See {@link Mapper#updateAll}.\n * @returns {Promise} See {@link Mapper#updateAll}.\n * @see Mapper#updateAll\n * @since 3.0.0\n */\n 'updateAll',\n\n /**\n * Fired during {@link Container#updateMany}. See\n * {@link Container~beforeUpdateManyListener} for how to listen for this event.\n *\n * @event Container#beforeUpdateMany\n * @see Container~beforeUpdateManyListener\n * @see Container#updateMany\n */\n /**\n * Callback signature for the {@link Container#event:beforeUpdateMany} event.\n *\n * @example\n * function onBeforeUpdateMany (mapperName, records, opts) {\n * // do something\n * }\n * store.on('beforeUpdateMany', onBeforeUpdateMany);\n *\n * @callback Container~beforeUpdateManyListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeUpdateMany}.\n * @param {object} records The `records` argument received by {@link Mapper#beforeUpdateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateMany}.\n * @see Container#event:beforeUpdateMany\n * @see Container#updateMany\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#updateMany}. See\n * {@link Container~afterUpdateManyListener} for how to listen for this event.\n *\n * @event Container#afterUpdateMany\n * @see Container~afterUpdateManyListener\n * @see Container#updateMany\n */\n /**\n * Callback signature for the {@link Container#event:afterUpdateMany} event.\n *\n * @example\n * function onAfterUpdateMany (mapperName, records, opts, result) {\n * // do something\n * }\n * store.on('afterUpdateMany', onAfterUpdateMany);\n *\n * @callback Container~afterUpdateManyListener\n * @param {string} name The `name` argument received by {@link Mapper#afterUpdateMany}.\n * @param {object} records The `records` argument received by {@link Mapper#afterUpdateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateMany}.\n * @param {object} result The `result` argument received by {@link Mapper#afterUpdateMany}.\n * @see Container#event:afterUpdateMany\n * @see Container#updateMany\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#updateMany}.\n *\n * @example\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.updateMany('post', [\n * { id: 1234, status: 'draft' },\n * { id: 2468, status: 'published', published_at: new Date() }\n * ]).then((posts) => {\n * console.log(posts); // [...]\n * });\n *\n * @fires Container#beforeUpdateMany\n * @fires Container#afterUpdateMany\n * @method Container#updateMany\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(Object[]|Record[])} records See {@link Mapper#updateMany}.\n * @param {object} [opts] See {@link Mapper#updateMany}.\n * @returns {Promise} See {@link Mapper#updateMany}.\n * @see Mapper#updateMany\n * @since 3.0.0\n */\n 'updateMany',\n\n /**\n * Wrapper for {@link Mapper#validate}.\n *\n * @example\n * import { Container } from 'js-data';\n * const store = new Container();\n * store.defineMapper('post', {\n * schema: {\n * properties: {\n * name: { type: 'string' },\n * id: { type: 'string' }\n * }\n * }\n * });\n * let errors = store.validate('post', { name: 'John' });\n * console.log(errors); // undefined\n * errors = store.validate('post', { name: 123 });\n * console.log(errors); // [{ expected: 'one of (string)', actual: 'number', path: 'name' }]\n *\n * @method Container#validate\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(Object[]|Record[])} records See {@link Mapper#validate}.\n * @param {object} [opts] See {@link Mapper#validate}.\n * @returns {Promise} See {@link Mapper#validate}.\n * @see Mapper#validate\n * @since 3.0.0\n */\n 'validate'\n]\n\n/**\n * The `Container` class is a place to define and store {@link Mapper} instances.\n *\n * `Container` makes it easy to manage your Mappers. Without a container, you\n * need to manage Mappers yourself, including resolving circular dependencies\n * among relations. All Mappers in a container share the same adapters, so you\n * don't have to register adapters for every single Mapper.\n *\n * @example Container#constructor\n * // import { Container } from 'js-data';\n * const JSData = require('js-data');\n * const {Container} = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n *\n * @class Container\n * @extends Component\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.debug=false] See {@link Component#debug}.\n * @param {Constructor} [opts.mapperClass] See {@link Container#mapperClass}.\n * @param {object} [opts.mapperDefaults] See {@link Container#mapperDefaults}.\n * @since 3.0.0\n */\nexport function Container (opts) {\n utils.classCallCheck(this, Container)\n Component.call(this)\n opts || (opts = {})\n\n Object.defineProperties(this, {\n /**\n * The adapters registered with this Container, which are also shared by all\n * Mappers in this Container.\n *\n * @name Container#_adapters\n * @see Container#registerAdapter\n * @since 3.0.0\n * @type {Object}\n */\n _adapters: {\n value: {}\n },\n\n /**\n * The the mappers in this container\n *\n * @name Container#_mappers\n * @see Mapper\n * @since 3.0.0\n * @type {Object}\n */\n _mappers: {\n value: {}\n },\n\n /**\n * Constructor function to use in {@link Container#defineMapper} to create new\n * {@link Mapper} instances. {@link Container#mapperClass} should extend\n * {@link Mapper}. By default {@link Mapper} is used to instantiate Mappers.\n *\n * @example Container#mapperClass\n * // import { Container, Mapper } from 'js-data';\n * const JSData = require('js-data');\n * const { Container, Mapper } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * class MyMapperClass extends Mapper {\n * foo () { return 'bar' }\n * }\n * const store = new Container({\n * mapperClass: MyMapperClass\n * });\n * store.defineMapper('user');\n * console.log(store.getMapper('user').foo());\n *\n * @name Container#mapperClass\n * @see Mapper\n * @since 3.0.0\n * @type {Constructor}\n */\n mapperClass: {\n value: undefined,\n writable: true\n }\n })\n\n // Apply options provided by the user\n utils.fillIn(this, opts)\n\n /**\n * Defaults options to pass to {@link Container#mapperClass} when creating a\n * new {@link Mapper}.\n *\n * @example Container#mapperDefaults\n * // import { Container } from 'js-data';\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container({\n * mapperDefaults: {\n * idAttribute: '_id'\n * }\n * });\n * store.defineMapper('user');\n * console.log(store.getMapper('user').idAttribute);\n *\n * @default {}\n * @name Container#mapperDefaults\n * @since 3.0.0\n * @type {Object}\n */\n this.mapperDefaults = this.mapperDefaults || {}\n\n // Use the Mapper class if the user didn't provide a mapperClass\n this.mapperClass || (this.mapperClass = Mapper)\n}\n\nconst props = {\n constructor: Container,\n\n /**\n * Register a new event listener on this Container.\n *\n * Proxy for {@link Component#on}. If an event was emitted by a {@link Mapper}\n * in the Container, then the name of the {@link Mapper} will be prepended to\n * the arugments passed to the listener.\n *\n * @example Container#on\n * // import { Container } from 'js-data';\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * store.on('foo', function (...args) { console.log(args.join(':')) });\n * store.defineMapper('user');\n * store.emit('foo', 'arg1', 'arg2');\n * store.getMapper('user').emit('foo', 'arg1', 'arg2');\n *\n * @method Container#on\n * @param {string} event Name of event to subsribe to.\n * @param {Function} listener Listener function to handle the event.\n * @param {*} [ctx] Optional content in which to invoke the listener.\n * @since 3.0.0\n */\n\n /**\n * Used to bind to events emitted by mappers in this container.\n *\n * @method Container#_onMapperEvent\n * @param {string} name Name of the mapper that emitted the event.\n * @param {...*} [args] Args See {@link Mapper#emit}.\n * @private\n * @since 3.0.0\n */\n _onMapperEvent (name, ...args) {\n const type = args.shift()\n this.emit(type, name, ...args)\n },\n\n /**\n * Return a container scoped to a particular mapper.\n *\n * @example Container#as\n * // import { Container } from 'js-data';\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * const UserMapper = store.defineMapper('user');\n * const UserStore = store.as('user');\n *\n * const user1 = store.createRecord('user', { name: 'John' });\n * const user2 = UserStore.createRecord({ name: 'John' });\n * const user3 = UserMapper.createRecord({ name: 'John' });\n * console.log(user1 === user2);\n * console.log(user2 === user3);\n * console.log(user1 === user3);\n *\n * @method Container#as\n * @param {string} name Name of the {@link Mapper}.\n * @returns {Object} A container scoped to a particular mapper.\n * @since 3.0.0\n */\n as (name) {\n const props = {}\n const original = this\n proxiedMapperMethods.forEach(function (method) {\n props[method] = {\n writable: true,\n value (...args) {\n return original[method](name, ...args)\n }\n }\n })\n props.getMapper = {\n writable: true,\n value () {\n return original.getMapper(name)\n }\n }\n return Object.create(this, props)\n },\n\n /**\n * Create a new mapper and register it in this container.\n *\n * @example Container#defineMapper\n * // import { Container } from 'js-data';\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container({\n * mapperDefaults: { foo: 'bar' }\n * });\n * // Container#defineMapper returns a direct reference to the newly created\n * // Mapper.\n * const UserMapper = store.defineMapper('user');\n * console.log(UserMapper === store.getMapper('user'));\n * console.log(UserMapper === store.as('user').getMapper());\n * console.log(UserMapper.foo);\n *\n * @method Container#defineMapper\n * @param {string} name Name under which to register the new {@link Mapper}.\n * {@link Mapper#name} will be set to this value.\n * @param {object} [opts] Configuration options. Passed to\n * {@link Container#mapperClass} when creating the new {@link Mapper}.\n * @returns {Mapper} The newly created instance of {@link Mapper}.\n * @see Container#as\n * @since 3.0.0\n */\n defineMapper (name, opts) {\n // For backwards compatibility with defineResource\n if (utils.isObject(name)) {\n opts = name\n name = opts.name\n }\n if (!utils.isString(name)) {\n throw utils.err(`${DOMAIN}#defineMapper`, 'name')(400, 'string', name)\n }\n\n // Default values for arguments\n opts || (opts = {})\n // Set Mapper#name\n opts.name = name\n opts.relations || (opts.relations = {})\n\n // Check if the user is overriding the datastore's default mapperClass\n const mapperClass = opts.mapperClass || this.mapperClass\n delete opts.mapperClass\n\n // Apply the datastore's defaults to the options going into the mapper\n utils.fillIn(opts, this.mapperDefaults)\n\n // Instantiate a mapper\n const mapper = this._mappers[name] = new mapperClass(opts) // eslint-disable-line\n mapper.relations || (mapper.relations = {})\n // Make sure the mapper's name is set\n mapper.name = name\n // All mappers in this datastore will share adapters\n mapper._adapters = this.getAdapters()\n\n mapper.datastore = this\n\n mapper.on('all', (...args) => this._onMapperEvent(name, ...args))\n mapper.defineRelations()\n\n return mapper\n },\n\n defineResource (name, opts) {\n console.warn('DEPRECATED: defineResource is deprecated, use defineMapper instead')\n return this.defineMapper(name, opts)\n },\n\n /**\n * Return the registered adapter with the given name or the default adapter if\n * no name is provided.\n *\n * @method Container#getAdapter\n * @param {string} [name] The name of the adapter to retrieve.\n * @returns {Adapter} The adapter.\n * @since 3.0.0\n */\n getAdapter (name) {\n const adapter = this.getAdapterName(name)\n if (!adapter) {\n throw utils.err(`${DOMAIN}#getAdapter`, 'name')(400, 'string', name)\n }\n return this.getAdapters()[adapter]\n },\n\n /**\n * Return the name of a registered adapter based on the given name or options,\n * or the name of the default adapter if no name provided.\n *\n * @method Container#getAdapterName\n * @param {(Object|string)} [opts] The name of an adapter or options, if any.\n * @returns {string} The name of the adapter.\n * @since 3.0.0\n */\n getAdapterName (opts) {\n opts || (opts = {})\n if (utils.isString(opts)) {\n opts = { adapter: opts }\n }\n return opts.adapter || this.mapperDefaults.defaultAdapter\n },\n\n /**\n * Return the registered adapters of this container.\n *\n * @method Container#getAdapters\n * @returns {Adapter}\n * @since 3.0.0\n */\n getAdapters () {\n return this._adapters\n },\n\n /**\n * Return the mapper registered under the specified name.\n *\n * @example Container#getMapper\n * // import { Container } from 'js-data';\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * // Container#defineMapper returns a direct reference to the newly created\n * // Mapper.\n * const UserMapper = store.defineMapper('user');\n * console.log(UserMapper === store.getMapper('user'));\n * console.log(UserMapper === store.as('user').getMapper());\n * store.getMapper('profile'); // throws Error, there is no mapper with name \"profile\"\n *\n * @method Container#getMapper\n * @param {string} name {@link Mapper#name}.\n * @returns {Mapper}\n * @since 3.0.0\n */\n getMapper (name) {\n const mapper = this.getMapperByName(name)\n if (!mapper) {\n throw utils.err(`${DOMAIN}#getMapper`, name)(404, 'mapper')\n }\n return mapper\n },\n\n /**\n * Return the mapper registered under the specified name.\n * Doesn't throw error if mapper doesn't exist.\n *\n * @example Container#getMapperByName\n * // import { Container } from 'js-data';\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * // Container#defineMapper returns a direct reference to the newly created\n * // Mapper.\n * const UserMapper = store.defineMapper('user');\n * console.log(UserMapper === store.getMapper('user'));\n * console.log(UserMapper === store.as('user').getMapper());\n * console.log(store.getMapper('profile')); // Does NOT throw an error\n *\n * @method Container#getMapperByName\n * @param {string} name {@link Mapper#name}.\n * @returns {Mapper}\n * @since 3.0.0\n */\n getMapperByName (name) {\n return this._mappers[name]\n },\n\n /**\n * Register an adapter on this container under the given name. Adapters\n * registered on a container are shared by all mappers in the container.\n *\n * @example\n * import { Container } from 'js-data';\n * import { RethinkDBAdapter } from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n *\n * @method Container#registerAdapter\n * @param {string} name The name of the adapter to register.\n * @param {Adapter} adapter The adapter to register.\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.default=false] Whether to make the adapter the\n * default adapter for all Mappers in this container.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/connecting-to-a-data-source\",\"Connecting to a data source\"]\n */\n registerAdapter (name, adapter, opts) {\n opts || (opts = {})\n this.getAdapters()[name] = adapter\n // Optionally make it the default adapter for the target.\n if (opts === true || opts.default) {\n this.mapperDefaults.defaultAdapter = name\n utils.forOwn(this._mappers, function (mapper) {\n mapper.defaultAdapter = name\n })\n }\n }\n}\n\nproxiedMapperMethods.forEach(function (method) {\n props[method] = function (name, ...args) {\n return this.getMapper(name)[method](...args)\n }\n})\n\nComponent.extend(props)\n\n/**\n * Create a subclass of this Container:\n * @example Container.extend\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomContainerClass extends Container {\n * foo () { return 'bar' }\n * static beep () { return 'boop' }\n * }\n * const customContainer = new CustomContainerClass();\n * console.log(customContainer.foo());\n * console.log(CustomContainerClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherContainerClass = Container.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherContainer = new OtherContainerClass();\n * console.log(otherContainer.foo());\n * console.log(OtherContainerClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherContainerClass () {\n * Container.call(this);\n * this.created_at = new Date().getTime();\n * }\n * Container.extend({\n * constructor: AnotherContainerClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * })\n * const anotherContainer = new AnotherContainerClass();\n * console.log(anotherContainer.created_at);\n * console.log(anotherContainer.foo());\n * console.log(AnotherContainerClass.beep());\n *\n * @method Container.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this Container class.\n * @since 3.0.0\n */\n","import utils from './utils'\n\nimport {\n belongsToType,\n hasManyType,\n hasOneType\n} from './decorators'\nimport {proxiedMapperMethods, Container} from './Container'\nimport Collection from './Collection'\n\nconst DOMAIN = 'SimpleStore'\nconst proxiedCollectionMethods = [\n /**\n * Wrapper for {@link Collection#add}.\n *\n * @example SimpleStore#add\n * const JSData = require('js-data');\n * const { SimpleStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new SimpleStore();\n * store.defineMapper('book');\n *\n * // Add one book to the in-memory store:\n * store.add('book', { id: 1, title: 'Respect your Data' });\n * // Add multiple books to the in-memory store:\n * store.add('book', [\n * { id: 2, title: 'Easy data recipes' },\n * { id: 3, title: 'Active Record 101' }\n * ]);\n *\n * @fires SimpleStore#add\n * @method SimpleStore#add\n * @param {(string|number)} name Name of the {@link Mapper} to target.\n * @param {(Object|Object[]|Record|Record[])} data See {@link Collection#add}.\n * @param {object} [opts] Configuration options. See {@link Collection#add}.\n * @returns {(Object|Object[]|Record|Record[])} See {@link Collection#add}.\n * @see Collection#add\n * @see Collection#add\n * @since 3.0.0\n */\n 'add',\n\n /**\n * Wrapper for {@link Collection#between}.\n *\n * @example\n * // Get all users ages 18 to 30\n * const users = store.between('user', 18, 30, { index: 'age' });\n *\n * @example\n * // Same as above\n * const users = store.between('user', [18], [30], { index: 'age' });\n *\n * @method SimpleStore#between\n * @param {(string|number)} name Name of the {@link Mapper} to target.\n * @param {array} leftKeys See {@link Collection#between}.\n * @param {array} rightKeys See {@link Collection#between}.\n * @param {object} [opts] Configuration options. See {@link Collection#between}.\n * @returns {Object[]|Record[]} See {@link Collection#between}.\n * @see Collection#between\n * @see Collection#between\n * @since 3.0.0\n */\n 'between',\n\n /**\n * Wrapper for {@link Collection#createIndex}.\n *\n * @example\n * // Index users by age\n * store.createIndex('user', 'age');\n *\n * @example\n * // Index users by status and role\n * store.createIndex('user', 'statusAndRole', ['status', 'role']);\n *\n * @method SimpleStore#createIndex\n * @param {(string|number)} name Name of the {@link Mapper} to target.\n * @param {string} name See {@link Collection#createIndex}.\n * @param {string[]} [fieldList] See {@link Collection#createIndex}.\n * @see Collection#createIndex\n * @see Collection#createIndex\n * @since 3.0.0\n */\n 'createIndex',\n\n /**\n * Wrapper for {@link Collection#filter}.\n *\n * @example SimpleStore#filter\n * const JSData = require('js-data');\n * const { SimpleStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new SimpleStore();\n * store.defineMapper('post');\n * store.add('post', [\n * { id: 1, status: 'draft', created_at_timestamp: new Date().getTime() }\n * ]);\n *\n * // Get the draft posts created less than three months ago\n * let posts = store.filter('post', {\n * where: {\n * status: {\n * '==': 'draft'\n * },\n * created_at_timestamp: {\n * '>=': (new Date().getTime() - (1000 \\* 60 \\* 60 \\* 24 \\* 30 \\* 3)) // 3 months ago\n * }\n * }\n * });\n * console.log(posts);\n *\n * // Use a custom filter function\n * posts = store.filter('post', function (post) { return post.id % 2 === 0 });\n *\n * @method SimpleStore#filter\n * @param {(string|number)} name Name of the {@link Mapper} to target.\n * @param {(Object|Function)} [queryOrFn={}] See {@link Collection#filter}.\n * @param {object} [thisArg] See {@link Collection#filter}.\n * @returns {Array} See {@link Collection#filter}.\n * @see Collection#filter\n * @see Collection#filter\n * @since 3.0.0\n */\n 'filter',\n\n /**\n * Wrapper for {@link Collection#get}.\n *\n * @example SimpleStore#get\n * const JSData = require('js-data');\n * const { SimpleStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new SimpleStore();\n * store.defineMapper('post');\n * store.add('post', [\n * { id: 1, status: 'draft', created_at_timestamp: new Date().getTime() }\n * ]);\n *\n * console.log(store.get('post', 1)); // {...}\n * console.log(store.get('post', 2)); // undefined\n *\n * @method SimpleStore#get\n * @param {(string|number)} name Name of the {@link Mapper} to target.\n * @param {(string|number)} id See {@link Collection#get}.\n * @returns {(Object|Record)} See {@link Collection#get}.\n * @see Collection#get\n * @see Collection#get\n * @since 3.0.0\n */\n 'get',\n\n /**\n * Wrapper for {@link Collection#getAll}.\n *\n * @example\n * // Get the posts where \"status\" is \"draft\" or \"inReview\"\n * const posts = store.getAll('post', 'draft', 'inReview', { index: 'status' });\n *\n * @example\n * // Same as above\n * const posts = store.getAll('post', ['draft'], ['inReview'], { index: 'status' });\n *\n * @method SimpleStore#getAll\n * @param {(string|number)} name Name of the {@link Mapper} to target.\n * @param {...Array} [keyList] See {@link Collection#getAll}.\n * @param {object} [opts] See {@link Collection#getAll}.\n * @returns {Array} See {@link Collection#getAll}.\n * @see Collection#getAll\n * @see Collection#getAll\n * @since 3.0.0\n */\n 'getAll',\n\n /**\n * Wrapper for {@link Collection#prune}.\n *\n * @method SimpleStore#prune\n * @param {object} [opts] See {@link Collection#prune}.\n * @returns {Array} See {@link Collection#prune}.\n * @see Collection#prune\n * @see Collection#prune\n * @since 3.0.0\n */\n 'prune',\n\n /**\n * Wrapper for {@link Collection#query}.\n *\n * @example\n * // Grab page 2 of users between ages 18 and 30\n * store.query('user')\n * .between(18, 30, { index: 'age' }) // between ages 18 and 30\n * .skip(10) // second page\n * .limit(10) // page size\n * .run();\n *\n * @method SimpleStore#query\n * @param {(string|number)} name Name of the {@link Mapper} to target.\n * @returns {Query} See {@link Collection#query}.\n * @see Collection#query\n * @see Collection#query\n * @since 3.0.0\n */\n 'query',\n\n /**\n * Wrapper for {@link Collection#toJSON}.\n *\n * @example\n * store.defineMapper('post', {\n * schema: {\n * properties: {\n * id: { type: 'number' },\n * title: { type: 'string' }\n * }\n * }\n * });\n * store.add('post', [\n * { id: 1, status: 'published', title: 'Respect your Data' },\n * { id: 2, status: 'draft', title: 'Connecting to a data source' }\n * ]);\n * console.log(store.toJSON('post'));\n * const draftsJSON = store.query('post')\n * .filter({ status: 'draft' })\n * .mapCall('toJSON')\n * .run();\n *\n * @method SimpleStore#toJSON\n * @param {(string|number)} name Name of the {@link Mapper} to target.\n * @param {object} [opts] See {@link Collection#toJSON}.\n * @returns {Array} See {@link Collection#toJSON}.\n * @see Collection#toJSON\n * @see Collection#toJSON\n * @since 3.0.0\n */\n 'toJSON',\n\n /**\n * Wrapper for {@link Collection#unsaved}.\n *\n * @method SimpleStore#unsaved\n * @returns {Array} See {@link Collection#unsaved}.\n * @see Collection#unsaved\n * @see Collection#unsaved\n * @since 3.0.0\n */\n 'unsaved'\n]\nconst ownMethodsForScoping = [\n 'addToCache',\n 'cachedFind',\n 'cachedFindAll',\n 'cacheFind',\n 'cacheFindAll',\n 'hashQuery'\n]\n\nconst cachedFn = function (name, hashOrId, opts) {\n const cached = this._completedQueries[name][hashOrId]\n if (utils.isFunction(cached)) {\n return cached(name, hashOrId, opts)\n }\n return cached\n}\n\nconst SIMPLESTORE_DEFAULTS = {\n /**\n * Whether to use the pending query if a `find` request for the specified\n * record is currently underway. Can be set to `true`, `false`, or to a\n * function that returns `true` or `false`.\n *\n * @default true\n * @name SimpleStore#usePendingFind\n * @since 3.0.0\n * @type {boolean|Function}\n */\n usePendingFind: true,\n\n /**\n * Whether to use the pending query if a `findAll` request for the given query\n * is currently underway. Can be set to `true`, `false`, or to a function that\n * returns `true` or `false`.\n *\n * @default true\n * @name SimpleStore#usePendingFindAll\n * @since 3.0.0\n * @type {boolean|Function}\n */\n usePendingFindAll: true\n}\n\n/**\n * The `SimpleStore` class is an extension of {@link Container}. Not only does\n * `SimpleStore` manage mappers, but also collections. `SimpleStore` implements the\n * asynchronous {@link Mapper} methods, such as {@link Mapper#find} and\n * {@link Mapper#create}. If you use the asynchronous `SimpleStore` methods\n * instead of calling them directly on the mappers, then the results of the\n * method calls will be inserted into the store's collections. You can think of\n * a `SimpleStore` as an [Identity Map](https://en.wikipedia.org/wiki/Identity_map_pattern)\n * for the [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping)\n * (the Mappers).\n *\n * ```javascript\n * import { SimpleStore } from 'js-data';\n * ```\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n * const store = new SimpleStore();\n *\n * // SimpleStore#defineMapper returns a direct reference to the newly created\n * // Mapper.\n * const UserMapper = store.defineMapper('user');\n *\n * // SimpleStore#as returns the store scoped to a particular Mapper.\n * const UserStore = store.as('user');\n *\n * // Call \"find\" on \"UserMapper\" (Stateless ORM)\n * UserMapper.find(1).then((user) => {\n * // retrieved a \"user\" record via the http adapter, but that's it\n *\n * // Call \"find\" on \"store\" targeting \"user\" (Stateful SimpleStore)\n * return store.find('user', 1); // same as \"UserStore.find(1)\"\n * }).then((user) => {\n * // not only was a \"user\" record retrieved, but it was added to the\n * // store's \"user\" collection\n * const cachedUser = store.getCollection('user').get(1);\n * console.log(user === cachedUser); // true\n * });\n *\n * @class SimpleStore\n * @extends Container\n * @param {object} [opts] Configuration options. See {@link Container}.\n * @param {boolean} [opts.collectionClass={@link Collection}] See {@link SimpleStore#collectionClass}.\n * @param {boolean} [opts.debug=false] See {@link Component#debug}.\n * @param {boolean|Function} [opts.usePendingFind=true] See {@link SimpleStore#usePendingFind}.\n * @param {boolean|Function} [opts.usePendingFindAll=true] See {@link SimpleStore#usePendingFindAll}.\n * @returns {SimpleStore}\n * @see Container\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#SimpleStore\",\"Components of JSData: SimpleStore\"]\n * @tutorial [\"http://www.js-data.io/v3.0/docs/working-with-the-SimpleStore\",\"Working with the SimpleStore\"]\n * @tutorial [\"http://www.js-data.io/v3.0/docs/jsdata-and-the-browser\",\"Notes on using JSData in the Browser\"]\n */\nfunction SimpleStore (opts) {\n utils.classCallCheck(this, SimpleStore)\n\n opts || (opts = {})\n // Fill in any missing options with the defaults\n utils.fillIn(opts, SIMPLESTORE_DEFAULTS)\n Container.call(this, opts)\n\n this.collectionClass = this.collectionClass || Collection\n this._collections = {}\n this._pendingQueries = {}\n this._completedQueries = {}\n}\n\nconst props = {\n constructor: SimpleStore,\n\n /**\n * Internal method used to handle Mapper responses.\n *\n * @method SimpleStore#_end\n * @private\n * @param {string} name Name of the {@link Collection} to which to\n * add the data.\n * @param {object} result The result from a Mapper.\n * @param {object} [opts] Configuration options.\n * @returns {(Object|Array)} Result.\n */\n _end (name, result, opts) {\n let data = opts.raw ? result.data : result\n if (data && utils.isFunction(this.addToCache)) {\n data = this.addToCache(name, data, opts)\n if (opts.raw) {\n result.data = data\n } else {\n result = data\n }\n }\n return result\n },\n\n /**\n * Register a new event listener on this SimpleStore.\n *\n * Proxy for {@link Container#on}. If an event was emitted by a Mapper or\n * Collection in the SimpleStore, then the name of the Mapper or Collection will\n * be prepended to the arugments passed to the provided event handler.\n *\n * @example\n * // Listen for all \"afterCreate\" events in a SimpleStore\n * store.on('afterCreate', (mapperName, props, opts, result) => {\n * console.log(mapperName); // \"post\"\n * console.log(props.id); // undefined\n * console.log(result.id); // 1234\n * });\n * store.create('post', { title: 'Modeling your data' }).then((post) => {\n * console.log(post.id); // 1234\n * });\n *\n * @example\n * // Listen for the \"add\" event on a collection\n * store.on('add', (mapperName, records) => {\n * console.log(records); // [...]\n * });\n *\n * @example\n * // Listen for \"change\" events on a record\n * store.on('change', (mapperName, record, changes) => {\n * console.log(changes); // { changed: { title: 'Modeling your data' } }\n * });\n * post.title = 'Modeling your data';\n *\n * @method SimpleStore#on\n * @param {string} event Name of event to subsribe to.\n * @param {Function} listener Listener function to handle the event.\n * @param {*} [ctx] Optional content in which to invoke the listener.\n */\n\n /**\n * Used to bind to events emitted by collections in this store.\n *\n * @method SimpleStore#_onCollectionEvent\n * @private\n * @param {string} name Name of the collection that emitted the event.\n * @param {...*} [args] Args passed to {@link Collection#emit}.\n */\n _onCollectionEvent (name, ...args) {\n const type = args.shift()\n this.emit(type, name, ...args)\n },\n\n /**\n * This method takes the data received from {@link SimpleStore#find},\n * {@link SimpleStore#findAll}, {@link SimpleStore#update}, etc., and adds the\n * data to the store. _You don't need to call this method directly._\n *\n * If you're using the http adapter and your response data is in an unexpected\n * format, you may need to override this method so the right data gets added\n * to the store.\n *\n * @example\n * const store = new SimpleStore({\n * addToCache (mapperName, data, opts) {\n * // Let's say for a particular Resource, response data is in a weird format\n * if (name === 'comment') {\n * // Re-assign the variable to add the correct records into the stores\n * data = data.items;\n * }\n * // Now perform default behavior\n * return SimpleStore.prototype.addToCache.call(this, mapperName, data, opts);\n * }\n * });\n *\n * @example\n * // Extend using ES2015 class syntax.\n * class MyStore extends SimpleStore {\n * addToCache (mapperName, data, opts) {\n * // Let's say for a particular Resource, response data is in a weird format\n * if (name === 'comment') {\n * // Re-assign the variable to add the correct records into the stores\n * data = data.items;\n * }\n * // Now perform default behavior\n * return super.addToCache(mapperName, data, opts);\n * }\n * }\n * const store = new MyStore();\n *\n * @method SimpleStore#addToCache\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {*} data Data from which data should be selected for add.\n * @param {object} [opts] Configuration options.\n */\n addToCache (name, data, opts) {\n return this.getCollection(name).add(data, opts)\n },\n\n /**\n * Return the store scoped to a particular mapper/collection pair.\n *\n * @example SimpleStore.as\n * const JSData = require('js-data');\n * const { SimpleStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new SimpleStore();\n * const UserMapper = store.defineMapper('user');\n * const UserStore = store.as('user');\n *\n * const user1 = store.createRecord('user', { name: 'John' });\n * const user2 = UserStore.createRecord({ name: 'John' });\n * const user3 = UserMapper.createRecord({ name: 'John' });\n * console.log(user1 === user2);\n * console.log(user2 === user3);\n * console.log(user1 === user3);\n *\n * @method SimpleStore#as\n * @param {string} name Name of the {@link Mapper}.\n * @returns {Object} The store, scoped to a particular Mapper/Collection pair.\n * @since 3.0.0\n */\n as (name) {\n const props = {}\n const original = this\n const methods = ownMethodsForScoping\n .concat(proxiedMapperMethods)\n .concat(proxiedCollectionMethods)\n\n methods.forEach(function (method) {\n props[method] = {\n writable: true,\n value (...args) {\n return original[method](name, ...args)\n }\n }\n })\n props.getMapper = {\n writable: true,\n value () {\n return original.getMapper(name)\n }\n }\n props.getCollection = {\n writable: true,\n value () {\n return original.getCollection(name)\n }\n }\n return Object.create(this, props)\n },\n\n /**\n * Retrieve a cached `find` result, if any. This method is called during\n * {@link SimpleStore#find} to determine if {@link Mapper#find} needs to be\n * called. If this method returns `undefined` then {@link Mapper#find} will\n * be called. Otherwise {@link SimpleStore#find} will immediately resolve with\n * the return value of this method.\n *\n * When using {@link SimpleStore} in the browser, you can override this method\n * to implement your own cache-busting strategy.\n *\n * @example\n * const store = new SimpleStore({\n * cachedFind (mapperName, id, opts) {\n * // Let's say for a particular Resource, we always want to pull fresh from the server\n * if (mapperName === 'schedule') {\n * // Return undefined to trigger a Mapper#find call\n * return;\n * }\n * // Otherwise perform default behavior\n * return SimpleStore.prototype.cachedFind.call(this, mapperName, id, opts);\n * }\n * });\n *\n * @example\n * // Extend using ES2015 class syntax.\n * class MyStore extends SimpleStore {\n * cachedFind (mapperName, id, opts) {\n * // Let's say for a particular Resource, we always want to pull fresh from the server\n * if (mapperName === 'schedule') {\n * // Return undefined to trigger a Mapper#find call\n * return;\n * }\n * // Otherwise perform default behavior\n * return super.cachedFind(mapperName, id, opts);\n * }\n * }\n * const store = new MyStore();\n *\n * @method SimpleStore#cachedFind\n * @param {string} name The `name` argument passed to {@link SimpleStore#find}.\n * @param {(string|number)} id The `id` argument passed to {@link SimpleStore#find}.\n * @param {object} opts The `opts` argument passed to {@link SimpleStore#find}.\n * @since 3.0.0\n */\n cachedFind: cachedFn,\n\n /**\n * Retrieve a cached `findAll` result, if any. This method is called during\n * {@link SimpleStore#findAll} to determine if {@link Mapper#findAll} needs to be\n * called. If this method returns `undefined` then {@link Mapper#findAll} will\n * be called. Otherwise {@link SimpleStore#findAll} will immediately resolve with\n * the return value of this method.\n *\n * When using {@link SimpleStore} in the browser, you can override this method\n * to implement your own cache-busting strategy.\n *\n * @example\n * const store = new SimpleStore({\n * cachedFindAll (mapperName, hash, opts) {\n * // Let's say for a particular Resource, we always want to pull fresh from the server\n * if (mapperName === 'schedule') {\n * // Return undefined to trigger a Mapper#findAll call\n * return undefined;\n * }\n * // Otherwise perform default behavior\n * return SimpleStore.prototype.cachedFindAll.call(this, mapperName, hash, opts);\n * }\n * });\n *\n * @example\n * // Extend using ES2015 class syntax.\n * class MyStore extends SimpleStore {\n * cachedFindAll (mapperName, hash, opts) {\n * // Let's say for a particular Resource, we always want to pull fresh from the server\n * if (mapperName === 'schedule') {\n * // Return undefined to trigger a Mapper#findAll call\n * return undefined;\n * }\n * // Otherwise perform default behavior\n * return super.cachedFindAll(mapperName, hash, opts);\n * }\n * }\n * const store = new MyStore();\n *\n * @method SimpleStore#cachedFindAll\n * @param {string} name The `name` argument passed to {@link SimpleStore#findAll}.\n * @param {string} hash The result of calling {@link SimpleStore#hashQuery} on\n * the `query` argument passed to {@link SimpleStore#findAll}.\n * @param {object} opts The `opts` argument passed to {@link SimpleStore#findAll}.\n * @since 3.0.0\n */\n cachedFindAll: cachedFn,\n\n /**\n * Mark a {@link Mapper#find} result as cached by adding an entry to\n * {@link SimpleStore#_completedQueries}. By default, once a `find` entry is\n * added it means subsequent calls to the same Resource with the same `id`\n * argument will immediately resolve with the result of calling\n * {@link SimpleStore#get} instead of delegating to {@link Mapper#find}.\n *\n * As part of implementing your own caching strategy, you may choose to\n * override this method.\n *\n * @example\n * const store = new SimpleStore({\n * cacheFind (mapperName, data, id, opts) {\n * // Let's say for a particular Resource, we always want to pull fresh from the server\n * if (mapperName === 'schedule') {\n * // Return without saving an entry to SimpleStore#_completedQueries\n * return;\n * }\n * // Otherwise perform default behavior\n * return SimpleStore.prototype.cacheFind.call(this, mapperName, data, id, opts);\n * }\n * });\n *\n * @example\n * // Extend using ES2015 class syntax.\n * class MyStore extends SimpleStore {\n * cacheFind (mapperName, data, id, opts) {\n * // Let's say for a particular Resource, we always want to pull fresh from the server\n * if (mapperName === 'schedule') {\n * // Return without saving an entry to SimpleStore#_completedQueries\n * return;\n * }\n * // Otherwise perform default behavior\n * return super.cacheFind(mapperName, data, id, opts);\n * }\n * }\n * const store = new MyStore();\n *\n * @method SimpleStore#cacheFind\n * @param {string} name The `name` argument passed to {@link SimpleStore#find}.\n * @param {*} data The result to cache.\n * @param {(string|number)} id The `id` argument passed to {@link SimpleStore#find}.\n * @param {object} opts The `opts` argument passed to {@link SimpleStore#find}.\n * @since 3.0.0\n */\n cacheFind (name, data, id, opts) {\n this._completedQueries[name][id] = (name, id, opts) => this.get(name, id)\n },\n\n /**\n * Mark a {@link Mapper#findAll} result as cached by adding an entry to\n * {@link SimpleStore#_completedQueries}. By default, once a `findAll` entry is\n * added it means subsequent calls to the same Resource with the same `query`\n * argument will immediately resolve with the result of calling\n * {@link SimpleStore#filter} instead of delegating to {@link Mapper#findAll}.\n *\n * As part of implementing your own caching strategy, you may choose to\n * override this method.\n *\n * @example\n * const store = new SimpleStore({\n * cachedFindAll (mapperName, data, hash, opts) {\n * // Let's say for a particular Resource, we always want to pull fresh from the server\n * if (mapperName === 'schedule') {\n * // Return without saving an entry to SimpleStore#_completedQueries\n * return;\n * }\n * // Otherwise perform default behavior.\n * return SimpleStore.prototype.cachedFindAll.call(this, mapperName, data, hash, opts);\n * }\n * });\n *\n * @example\n * // Extend using ES2015 class syntax.\n * class MyStore extends SimpleStore {\n * cachedFindAll (mapperName, data, hash, opts) {\n * // Let's say for a particular Resource, we always want to pull fresh from the server\n * if (mapperName === 'schedule') {\n * // Return without saving an entry to SimpleStore#_completedQueries\n * return;\n * }\n * // Otherwise perform default behavior.\n * return super.cachedFindAll(mapperName, data, hash, opts);\n * }\n * }\n * const store = new MyStore();\n *\n * @method SimpleStore#cacheFindAll\n * @param {string} name The `name` argument passed to {@link SimpleStore#findAll}.\n * @param {*} data The result to cache.\n * @param {string} hash The result of calling {@link SimpleStore#hashQuery} on\n * the `query` argument passed to {@link SimpleStore#findAll}.\n * @param {object} opts The `opts` argument passed to {@link SimpleStore#findAll}.\n * @since 3.0.0\n */\n cacheFindAll (name, data, hash, opts) {\n this._completedQueries[name][hash] = (name, hash, opts) => this.filter(name, utils.fromJson(hash))\n },\n\n /**\n * Remove __all__ records from the in-memory store and reset\n * {@link SimpleStore#_completedQueries}.\n *\n * @method SimpleStore#clear\n * @returns {Object} Object containing all records that were in the store.\n * @see SimpleStore#remove\n * @see SimpleStore#removeAll\n * @since 3.0.0\n */\n clear () {\n const removed = {}\n utils.forOwn(this._collections, (collection, name) => {\n removed[name] = collection.removeAll()\n this._completedQueries[name] = {}\n })\n return removed\n },\n\n /**\n * Fired during {@link SimpleStore#create}. See\n * {@link SimpleStore~beforeCreateListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeCreate\n * @see SimpleStore~beforeCreateListener\n * @see SimpleStore#create\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeCreate} event.\n *\n * @example\n * function onBeforeCreate (mapperName, props, opts) {\n * // do something\n * }\n * store.on('beforeCreate', onBeforeCreate);\n *\n * @callback SimpleStore~beforeCreateListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeCreate}.\n * @param {object} props The `props` argument received by {@link Mapper#beforeCreate}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreate}.\n * @see SimpleStore#event:beforeCreate\n * @see SimpleStore#create\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#create}. See\n * {@link SimpleStore~afterCreateListener} for how to listen for this event.\n *\n * @event SimpleStore#afterCreate\n * @see SimpleStore~afterCreateListener\n * @see SimpleStore#create\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterCreate} event.\n *\n * @example\n * function onAfterCreate (mapperName, props, opts, result) {\n * // do something\n * }\n * store.on('afterCreate', onAfterCreate);\n *\n * @callback SimpleStore~afterCreateListener\n * @param {string} name The `name` argument received by {@link Mapper#afterCreate}.\n * @param {object} props The `props` argument received by {@link Mapper#afterCreate}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterCreate}.\n * @param {object} result The `result` argument received by {@link Mapper#afterCreate}.\n * @see SimpleStore#event:afterCreate\n * @see SimpleStore#create\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#create}. Adds the created record to the store.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('book');\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // POST /book {\"author_id\":1234,...}\n * store.create('book', {\n * author_id: 1234,\n * edition: 'First Edition',\n * title: 'Respect your Data'\n * }).then((book) => {\n * console.log(book.id); // 120392\n * console.log(book.title); // \"Respect your Data\"\n * });\n *\n * @fires SimpleStore#beforeCreate\n * @fires SimpleStore#afterCreate\n * @fires SimpleStore#add\n * @method SimpleStore#create\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} record Passed to {@link Mapper#create}.\n * @param {object} [opts] Passed to {@link Mapper#create}. See\n * {@link Mapper#create} for more configuration options.\n * @returns {Promise} Resolves with the result of the create.\n * @since 3.0.0\n */\n create (name, record, opts) {\n opts || (opts = {})\n return Container.prototype.create.call(this, name, record, opts)\n .then((result) => this._end(name, result, opts))\n },\n\n /**\n * Fired during {@link SimpleStore#createMany}. See\n * {@link SimpleStore~beforeCreateManyListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeCreateMany\n * @see SimpleStore~beforeCreateManyListener\n * @see SimpleStore#createMany\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeCreateMany} event.\n *\n * @example\n * function onBeforeCreateMany (mapperName, records, opts) {\n * // do something\n * }\n * store.on('beforeCreateMany', onBeforeCreateMany);\n *\n * @callback SimpleStore~beforeCreateManyListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeCreateMany}.\n * @param {object} records The `records` argument received by {@link Mapper#beforeCreateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreateMany}.\n * @see SimpleStore#event:beforeCreateMany\n * @see SimpleStore#createMany\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#createMany}. See\n * {@link SimpleStore~afterCreateManyListener} for how to listen for this event.\n *\n * @event SimpleStore#afterCreateMany\n * @see SimpleStore~afterCreateManyListener\n * @see SimpleStore#createMany\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterCreateMany} event.\n *\n * @example\n * function onAfterCreateMany (mapperName, records, opts, result) {\n * // do something\n * }\n * store.on('afterCreateMany', onAfterCreateMany);\n *\n * @callback SimpleStore~afterCreateManyListener\n * @param {string} name The `name` argument received by {@link Mapper#afterCreateMany}.\n * @param {object} records The `records` argument received by {@link Mapper#afterCreateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterCreateMany}.\n * @param {object} result The `result` argument received by {@link Mapper#afterCreateMany}.\n * @see SimpleStore#event:afterCreateMany\n * @see SimpleStore#createMany\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#createMany}. Adds the created records to the\n * store.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('book');\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // POST /book [{\"author_id\":1234,...},{...}]\n * store.createMany('book', [{\n * author_id: 1234,\n * edition: 'First Edition',\n * title: 'Respect your Data'\n * }, {\n * author_id: 1234,\n * edition: 'Second Edition',\n * title: 'Respect your Data'\n * }]).then((books) => {\n * console.log(books[0].id); // 142394\n * console.log(books[0].title); // \"Respect your Data\"\n * });\n *\n * @fires SimpleStore#beforeCreateMany\n * @fires SimpleStore#afterCreateMany\n * @fires SimpleStore#add\n * @method SimpleStore#createMany\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {array} records Passed to {@link Mapper#createMany}.\n * @param {object} [opts] Passed to {@link Mapper#createMany}. See\n * {@link Mapper#createMany} for more configuration options.\n * @returns {Promise} Resolves with the result of the create.\n * @since 3.0.0\n */\n createMany (name, records, opts) {\n opts || (opts = {})\n return Container.prototype.createMany.call(this, name, records, opts)\n .then((result) => this._end(name, result, opts))\n },\n\n defineMapper (name, opts) {\n const self = this\n const mapper = Container.prototype.defineMapper.call(self, name, opts)\n self._pendingQueries[name] = {}\n self._completedQueries[name] = {}\n mapper.relationList || Object.defineProperty(mapper, 'relationList', { value: [] })\n\n let collectionOpts = {\n // Make sure the collection has somewhere to store \"added\" timestamps\n _added: {},\n // Give the collection a reference to this SimpleStore\n datastore: self,\n // The mapper tied to the collection\n mapper\n }\n\n if (opts && ('onConflict' in opts)) {\n collectionOpts.onConflict = opts.onConflict\n }\n\n // The SimpleStore uses a subclass of Collection that is \"SimpleStore-aware\"\n const collection = self._collections[name] = new self.collectionClass(null, collectionOpts) // eslint-disable-line\n\n const schema = mapper.schema || {}\n const properties = schema.properties || {}\n // TODO: Make it possible index nested properties?\n utils.forOwn(properties, function (opts, prop) {\n if (opts.indexed) {\n collection.createIndex(prop)\n }\n })\n\n // Create a secondary index on the \"added\" timestamps of records in the\n // collection\n collection.createIndex('addedTimestamps', ['$'], {\n fieldGetter (obj) {\n return collection._added[collection.recordId(obj)]\n }\n })\n\n collection.on('all', function (...args) {\n self._onCollectionEvent(name, ...args)\n })\n\n return mapper\n },\n\n /**\n * Fired during {@link SimpleStore#destroy}. See\n * {@link SimpleStore~beforeDestroyListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeDestroy\n * @see SimpleStore~beforeDestroyListener\n * @see SimpleStore#destroy\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeDestroy} event.\n *\n * @example\n * function onBeforeDestroy (mapperName, id, opts) {\n * // do something\n * }\n * store.on('beforeDestroy', onBeforeDestroy);\n *\n * @callback SimpleStore~beforeDestroyListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeDestroy}.\n * @param {string|number} id The `id` argument received by {@link Mapper#beforeDestroy}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroy}.\n * @see SimpleStore#event:beforeDestroy\n * @see SimpleStore#destroy\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#destroy}. See\n * {@link SimpleStore~afterDestroyListener} for how to listen for this event.\n *\n * @event SimpleStore#afterDestroy\n * @see SimpleStore~afterDestroyListener\n * @see SimpleStore#destroy\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterDestroy} event.\n *\n * @example\n * function onAfterDestroy (mapperName, id, opts, result) {\n * // do something\n * }\n * store.on('afterDestroy', onAfterDestroy);\n *\n * @callback SimpleStore~afterDestroyListener\n * @param {string} name The `name` argument received by {@link Mapper#afterDestroy}.\n * @param {string|number} id The `id` argument received by {@link Mapper#afterDestroy}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterDestroy}.\n * @param {object} result The `result` argument received by {@link Mapper#afterDestroy}.\n * @see SimpleStore#event:afterDestroy\n * @see SimpleStore#destroy\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#destroy}. Removes any destroyed record from the\n * in-memory store. Clears out any {@link SimpleStore#_completedQueries} entries\n * associated with the provided `id`.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('book');\n *\n * store.add('book', { id: 1234, title: 'Data Management is Hard' });\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // DELETE /book/1234\n * store.destroy('book', 1234).then(() => {\n * // The book record is no longer in the in-memory store\n * console.log(store.get('book', 1234)); // undefined\n *\n * return store.find('book', 1234);\n * }).then((book) {\n * // The book was deleted from the database too\n * console.log(book); // undefined\n * });\n *\n * @fires SimpleStore#beforeDestroy\n * @fires SimpleStore#afterDestroy\n * @fires SimpleStore#remove\n * @method SimpleStore#destroy\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(string|number)} id Passed to {@link Mapper#destroy}.\n * @param {object} [opts] Passed to {@link Mapper#destroy}. See\n * {@link Mapper#destroy} for more configuration options.\n * @returns {Promise} Resolves when the destroy operation completes.\n * @since 3.0.0\n */\n destroy (name, id, opts) {\n opts || (opts = {})\n return Container.prototype.destroy.call(this, name, id, opts).then((result) => {\n const record = this.getCollection(name).remove(id, opts)\n\n if (opts.raw) {\n result.data = record\n } else {\n result = record\n }\n delete this._pendingQueries[name][id]\n delete this._completedQueries[name][id]\n return result\n })\n },\n\n /**\n * Fired during {@link SimpleStore#destroyAll}. See\n * {@link SimpleStore~beforeDestroyAllListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeDestroyAll\n * @see SimpleStore~beforeDestroyAllListener\n * @see SimpleStore#destroyAll\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeDestroyAll} event.\n *\n * @example\n * function onBeforeDestroyAll (mapperName, query, opts) {\n * // do something\n * }\n * store.on('beforeDestroyAll', onBeforeDestroyAll);\n *\n * @callback SimpleStore~beforeDestroyAllListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeDestroyAll}.\n * @param {object} query The `query` argument received by {@link Mapper#beforeDestroyAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroyAll}.\n * @see SimpleStore#event:beforeDestroyAll\n * @see SimpleStore#destroyAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#destroyAll}. See\n * {@link SimpleStore~afterDestroyAllListener} for how to listen for this event.\n *\n * @event SimpleStore#afterDestroyAll\n * @see SimpleStore~afterDestroyAllListener\n * @see SimpleStore#destroyAll\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterDestroyAll} event.\n *\n * @example\n * function onAfterDestroyAll (mapperName, query, opts, result) {\n * // do something\n * }\n * store.on('afterDestroyAll', onAfterDestroyAll);\n *\n * @callback SimpleStore~afterDestroyAllListener\n * @param {string} name The `name` argument received by {@link Mapper#afterDestroyAll}.\n * @param {object} query The `query` argument received by {@link Mapper#afterDestroyAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterDestroyAll}.\n * @param {object} result The `result` argument received by {@link Mapper#afterDestroyAll}.\n * @see SimpleStore#event:afterDestroyAll\n * @see SimpleStore#destroyAll\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#destroyAll}. Removes any destroyed records from\n * the in-memory store.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('book');\n *\n * store.add('book', { id: 1234, title: 'Data Management is Hard' });\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // DELETE /book/1234\n * store.destroy('book', 1234).then(() => {\n * // The book record is gone from the in-memory store\n * console.log(store.get('book', 1234)); // undefined\n * return store.find('book', 1234);\n * }).then((book) {\n * // The book was deleted from the database too\n * console.log(book); // undefined\n * });\n *\n * @fires SimpleStore#beforeDestroyAll\n * @fires SimpleStore#afterDestroyAll\n * @fires SimpleStore#remove\n * @method SimpleStore#destroyAll\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} [query] Passed to {@link Mapper#destroyAll}.\n * @param {object} [opts] Passed to {@link Mapper#destroyAll}. See\n * {@link Mapper#destroyAll} for more configuration options.\n * @returns {Promise} Resolves when the delete completes.\n * @since 3.0.0\n */\n destroyAll (name, query, opts) {\n opts || (opts = {})\n return Container.prototype.destroyAll.call(this, name, query, opts).then((result) => {\n const records = this.getCollection(name).removeAll(query, opts)\n\n if (opts.raw) {\n result.data = records\n } else {\n result = records\n }\n const hash = this.hashQuery(name, query, opts)\n delete this._pendingQueries[name][hash]\n delete this._completedQueries[name][hash]\n return result\n })\n },\n\n eject (name, id, opts) {\n console.warn('DEPRECATED: \"eject\" is deprecated, use \"remove\" instead')\n return this.remove(name, id, opts)\n },\n\n ejectAll (name, query, opts) {\n console.warn('DEPRECATED: \"ejectAll\" is deprecated, use \"removeAll\" instead')\n return this.removeAll(name, query, opts)\n },\n\n /**\n * Fired during {@link SimpleStore#find}. See\n * {@link SimpleStore~beforeFindListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeFind\n * @see SimpleStore~beforeFindListener\n * @see SimpleStore#find\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeFind} event.\n *\n * @example\n * function onBeforeFind (mapperName, id, opts) {\n * // do something\n * }\n * store.on('beforeFind', onBeforeFind);\n *\n * @callback SimpleStore~beforeFindListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeFind}.\n * @param {string|number} id The `id` argument received by {@link Mapper#beforeFind}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeFind}.\n * @see SimpleStore#event:beforeFind\n * @see SimpleStore#find\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#find}. See\n * {@link SimpleStore~afterFindListener} for how to listen for this event.\n *\n * @event SimpleStore#afterFind\n * @see SimpleStore~afterFindListener\n * @see SimpleStore#find\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterFind} event.\n *\n * @example\n * function onAfterFind (mapperName, id, opts, result) {\n * // do something\n * }\n * store.on('afterFind', onAfterFind);\n *\n * @callback SimpleStore~afterFindListener\n * @param {string} name The `name` argument received by {@link Mapper#afterFind}.\n * @param {string|number} id The `id` argument received by {@link Mapper#afterFind}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterFind}.\n * @param {object} result The `result` argument received by {@link Mapper#afterFind}.\n * @see SimpleStore#event:afterFind\n * @see SimpleStore#find\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#find}. Adds any found record to the store.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('book');\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // GET /book/1234\n * store.find('book', 1234).then((book) => {\n * // The book record is now in the in-memory store\n * console.log(store.get('book', 1234) === book); // true\n * });\n *\n * @fires SimpleStore#beforeFind\n * @fires SimpleStore#afterFind\n * @fires SimpleStore#add\n * @method SimpleStore#find\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(string|number)} id Passed to {@link Mapper#find}.\n * @param {object} [opts] Passed to {@link Mapper#find}.\n * @param {boolean} [opts.force] Bypass cacheFind\n * @param {boolean|Function} [opts.usePendingFind] See {@link SimpleStore#usePendingFind}\n * @returns {Promise} Resolves with the result, if any.\n * @since 3.0.0\n */\n find (name, id, opts) {\n opts || (opts = {})\n const mapper = this.getMapper(name)\n const pendingQuery = this._pendingQueries[name][id]\n const usePendingFind = opts.usePendingFind === undefined ? this.usePendingFind : opts.usePendingFind\n utils._(opts, mapper)\n\n if (pendingQuery && (utils.isFunction(usePendingFind) ? usePendingFind.call(this, name, id, opts) : usePendingFind)) {\n return pendingQuery\n }\n const item = this.cachedFind(name, id, opts)\n\n if (opts.force || !item) {\n const promise = this._pendingQueries[name][id] = Container.prototype.find.call(this, name, id, opts)\n return promise\n .then((result) => {\n delete this._pendingQueries[name][id]\n result = this._end(name, result, opts)\n this.cacheFind(name, result, id, opts)\n return result\n }, (err) => {\n delete this._pendingQueries[name][id]\n return utils.reject(err)\n })\n }\n\n return utils.resolve(item)\n },\n\n /**\n * Fired during {@link SimpleStore#findAll}. See\n * {@link SimpleStore~beforeFindAllListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeFindAll\n * @see SimpleStore~beforeFindAllListener\n * @see SimpleStore#findAll\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeFindAll} event.\n *\n * @example\n * function onBeforeFindAll (mapperName, query, opts) {\n * // do something\n * }\n * store.on('beforeFindAll', onBeforeFindAll);\n *\n * @callback SimpleStore~beforeFindAllListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeFindAll}.\n * @param {object} query The `query` argument received by {@link Mapper#beforeFindAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeFindAll}.\n * @see SimpleStore#event:beforeFindAll\n * @see SimpleStore#findAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#findAll}. See\n * {@link SimpleStore~afterFindAllListener} for how to listen for this event.\n *\n * @event SimpleStore#afterFindAll\n * @see SimpleStore~afterFindAllListener\n * @see SimpleStore#findAll\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterFindAll} event.\n *\n * @example\n * function onAfterFindAll (mapperName, query, opts, result) {\n * // do something\n * }\n * store.on('afterFindAll', onAfterFindAll);\n *\n * @callback SimpleStore~afterFindAllListener\n * @param {string} name The `name` argument received by {@link Mapper#afterFindAll}.\n * @param {object} query The `query` argument received by {@link Mapper#afterFindAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterFindAll}.\n * @param {object} result The `result` argument received by {@link Mapper#afterFindAll}.\n * @see SimpleStore#event:afterFindAll\n * @see SimpleStore#findAll\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#findAll}. Adds any found records to the store.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('movie');\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // GET /movie?rating=PG\n * store.find('movie', { rating: 'PG' }).then((movies) => {\n * // The movie records are now in the in-memory store\n * console.log(store.filter('movie'));\n * });\n *\n * @fires SimpleStore#beforeFindAll\n * @fires SimpleStore#afterFindAll\n * @fires SimpleStore#add\n * @method SimpleStore#findAll\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} [query] Passed to {@link Mapper.findAll}.\n * @param {object} [opts] Passed to {@link Mapper.findAll}.\n * @param {boolean} [opts.force] Bypass cacheFindAll\n * @param {boolean|Function} [opts.usePendingFindAll] See {@link SimpleStore#usePendingFindAll}\n * @returns {Promise} Resolves with the result, if any.\n * @since 3.0.0\n */\n findAll (name, query, opts) {\n opts || (opts = {})\n const mapper = this.getMapper(name)\n const hash = this.hashQuery(name, query, opts)\n const pendingQuery = this._pendingQueries[name][hash]\n const usePendingFindAll = opts.usePendingFindAll === undefined ? this.usePendingFindAll : opts.usePendingFindAll\n utils._(opts, mapper)\n\n if (pendingQuery && (utils.isFunction(usePendingFindAll) ? usePendingFindAll.call(this, name, query, opts) : usePendingFindAll)) {\n return pendingQuery\n }\n\n const items = this.cachedFindAll(name, hash, opts)\n\n if (opts.force || !items) {\n const promise = this._pendingQueries[name][hash] = Container.prototype.findAll.call(this, name, query, opts)\n return promise\n .then((result) => {\n delete this._pendingQueries[name][hash]\n result = this._end(name, result, opts)\n this.cacheFindAll(name, result, hash, opts)\n return result\n }, (err) => {\n delete this._pendingQueries[name][hash]\n return utils.reject(err)\n })\n }\n\n return utils.resolve(items)\n },\n\n /**\n * Return the {@link Collection} with the given name, if for some\n * reason you need a direct reference to the collection.\n *\n * @method SimpleStore#getCollection\n * @param {string} name Name of the {@link Collection} to retrieve.\n * @returns {Collection}\n * @since 3.0.0\n * @throws {Error} Thrown if the specified {@link Collection} does not\n * exist.\n */\n getCollection (name) {\n const collection = this._collections[name]\n if (!collection) {\n throw utils.err(`${DOMAIN}#getCollection`, name)(404, 'collection')\n }\n return collection\n },\n\n /**\n * Hashing function used to cache {@link SimpleStore#find} and\n * {@link SimpleStore#findAll} requests. This method simply JSONifies the\n * `query` argument passed to {@link SimpleStore#find} or\n * {@link SimpleStore#findAll}.\n *\n * Override this method for custom hashing behavior.\n * @method SimpleStore#hashQuery\n * @param {string} name The `name` argument passed to {@link SimpleStore#find}\n * or {@link SimpleStore#findAll}.\n * @param {object} query The `query` argument passed to {@link SimpleStore#find}\n * or {@link SimpleStore#findAll}.\n * @returns {string} The JSONified `query`.\n * @since 3.0.0\n */\n hashQuery (name, query, opts) {\n return utils.toJson(query || {})\n },\n\n inject (name, records, opts) {\n console.warn('DEPRECATED: \"inject\" is deprecated, use \"add\" instead')\n return this.add(name, records, opts)\n },\n\n /**\n * Wrapper for {@link Collection#remove}. Removes the specified\n * {@link Record} from the store.\n *\n * @example SimpleStore#remove\n * const JSData = require('js-data');\n * const { SimpleStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new SimpleStore();\n * store.defineMapper('book');\n * console.log(store.getAll('book').length);\n * store.add('book', { id: 1234 });\n * console.log(store.getAll('book').length);\n * store.remove('book', 1234);\n * console.log(store.getAll('book').length);\n *\n * @fires SimpleStore#remove\n * @method SimpleStore#remove\n * @param {string} name The name of the {@link Collection} to target.\n * @param {string|number} id The primary key of the {@link Record} to remove.\n * @param {object} [opts] Configuration options.\n * @param {string[]} [opts.with] Relations of the {@link Record} to also\n * remove from the store.\n * @returns {Record} The removed {@link Record}, if any.\n * @see Collection#add\n * @see Collection#add\n * @since 3.0.0\n */\n remove (name, id, opts) {\n const record = this.getCollection(name).remove(id, opts)\n if (record) {\n this.removeRelated(name, [record], opts)\n }\n return record\n },\n\n /**\n * Wrapper for {@link Collection#removeAll}. Removes the selected\n * {@link Record}s from the store.\n *\n * @example SimpleStore#removeAll\n * const JSData = require('js-data');\n * const { SimpleStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new SimpleStore();\n * store.defineMapper('movie');\n * console.log(store.getAll('movie').length);\n * store.add('movie', [{ id: 3, rating: 'R' }, { id: 4, rating: 'PG-13' });\n * console.log(store.getAll('movie').length);\n * store.removeAll('movie', { rating: 'R' });\n * console.log(store.getAll('movie').length);\n *\n * @fires SimpleStore#remove\n * @method SimpleStore#removeAll\n * @param {string} name The name of the {@link Collection} to target.\n * @param {object} [query={}] Selection query. See {@link query}.\n * @param {object} [query.where] See {@link query.where}.\n * @param {number} [query.offset] See {@link query.offset}.\n * @param {number} [query.limit] See {@link query.limit}.\n * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}.\n * @param {object} [opts] Configuration options.\n * @param {string[]} [opts.with] Relations of the {@link Record} to also\n * remove from the store.\n * @returns {Record} The removed {@link Record}s, if any.\n * @see Collection#add\n * @see Collection#add\n * @since 3.0.0\n */\n removeAll (name, query, opts) {\n if (!query || !Object.keys(query).length) {\n this._completedQueries[name] = {}\n } else {\n this._completedQueries[name][this.hashQuery(name, query, opts)] = undefined\n }\n const records = this.getCollection(name).removeAll(query, opts)\n if (records.length) {\n this.removeRelated(name, records, opts)\n }\n return records\n },\n\n /**\n * Remove from the store {@link Record}s that are related to the provided\n * {@link Record}(s).\n *\n * @fires SimpleStore#remove\n * @method SimpleStore#removeRelated\n * @param {string} name The name of the {@link Collection} to target.\n * @param {Record|Record[]} records {@link Record}s whose relations are to be\n * removed.\n * @param {object} [opts] Configuration options.\n * @param {string[]} [opts.with] Relations of the {@link Record}(s) to remove\n * from the store.\n * @since 3.0.0\n */\n removeRelated (name, records, opts) {\n if (!utils.isArray(records)) {\n records = [records]\n }\n utils.forEachRelation(this.getMapper(name), opts, (def, optsCopy) => {\n records.forEach((record) => {\n let relatedData\n let query\n if (def.foreignKey && (def.type === hasOneType || def.type === hasManyType)) {\n query = { [def.foreignKey]: def.getForeignKey(record) }\n } else if (def.type === hasManyType && def.localKeys) {\n query = {\n where: {\n [def.getRelation().idAttribute]: {\n 'in': utils.get(record, def.localKeys)\n }\n }\n }\n } else if (def.type === hasManyType && def.foreignKeys) {\n query = {\n where: {\n [def.foreignKeys]: {\n 'contains': def.getForeignKey(record)\n }\n }\n }\n } else if (def.type === belongsToType) {\n relatedData = this.remove(def.relation, def.getForeignKey(record), optsCopy)\n }\n if (query) {\n relatedData = this.removeAll(def.relation, query, optsCopy)\n }\n if (relatedData) {\n if (utils.isArray(relatedData) && !relatedData.length) {\n return\n }\n if (def.type === hasOneType) {\n relatedData = relatedData[0]\n }\n def.setLocalField(record, relatedData)\n }\n })\n })\n },\n\n /**\n * Fired during {@link SimpleStore#update}. See\n * {@link SimpleStore~beforeUpdateListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeUpdate\n * @see SimpleStore~beforeUpdateListener\n * @see SimpleStore#update\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeUpdate} event.\n *\n * @example\n * function onBeforeUpdate (mapperName, id, props, opts) {\n * // do something\n * }\n * store.on('beforeUpdate', onBeforeUpdate);\n *\n * @callback SimpleStore~beforeUpdateListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeUpdate}.\n * @param {string|number} id The `id` argument received by {@link Mapper#beforeUpdate}.\n * @param {object} props The `props` argument received by {@link Mapper#beforeUpdate}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdate}.\n * @see SimpleStore#event:beforeUpdate\n * @see SimpleStore#update\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#update}. See\n * {@link SimpleStore~afterUpdateListener} for how to listen for this event.\n *\n * @event SimpleStore#afterUpdate\n * @see SimpleStore~afterUpdateListener\n * @see SimpleStore#update\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterUpdate} event.\n *\n * @example\n * function onAfterUpdate (mapperName, id, props, opts, result) {\n * // do something\n * }\n * store.on('afterUpdate', onAfterUpdate);\n *\n * @callback SimpleStore~afterUpdateListener\n * @param {string} name The `name` argument received by {@link Mapper#afterUpdate}.\n * @param {string|number} id The `id` argument received by {@link Mapper#afterUpdate}.\n * @param {object} props The `props` argument received by {@link Mapper#afterUpdate}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdate}.\n * @param {object} result The `result` argument received by {@link Mapper#afterUpdate}.\n * @see SimpleStore#event:afterUpdate\n * @see SimpleStore#update\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#update}. Adds the updated {@link Record} to the\n * store.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('post');\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // PUT /post/1234 {\"status\":\"published\"}\n * store.update('post', 1, { status: 'published' }).then((post) => {\n * // The post record has also been updated in the in-memory store\n * console.log(store.get('post', 1234));\n * });\n *\n * @fires SimpleStore#beforeUpdate\n * @fires SimpleStore#afterUpdate\n * @fires SimpleStore#add\n * @method SimpleStore#update\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(string|number)} id Passed to {@link Mapper#update}.\n * @param {object} record Passed to {@link Mapper#update}.\n * @param {object} [opts] Passed to {@link Mapper#update}. See\n * {@link Mapper#update} for more configuration options.\n * @returns {Promise} Resolves with the result of the update.\n * @since 3.0.0\n */\n update (name, id, record, opts) {\n opts || (opts = {})\n return Container.prototype.update.call(this, name, id, record, opts)\n .then((result) => this._end(name, result, opts))\n },\n\n /**\n * Fired during {@link SimpleStore#updateAll}. See\n * {@link SimpleStore~beforeUpdateAllListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeUpdateAll\n * @see SimpleStore~beforeUpdateAllListener\n * @see SimpleStore#updateAll\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeUpdateAll} event.\n *\n * @example\n * function onBeforeUpdateAll (mapperName, props, query, opts) {\n * // do something\n * }\n * store.on('beforeUpdateAll', onBeforeUpdateAll);\n *\n * @callback SimpleStore~beforeUpdateAllListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeUpdateAll}.\n * @param {object} props The `props` argument received by {@link Mapper#beforeUpdateAll}.\n * @param {object} query The `query` argument received by {@link Mapper#beforeUpdateAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateAll}.\n * @see SimpleStore#event:beforeUpdateAll\n * @see SimpleStore#updateAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#updateAll}. See\n * {@link SimpleStore~afterUpdateAllListener} for how to listen for this event.\n *\n * @event SimpleStore#afterUpdateAll\n * @see SimpleStore~afterUpdateAllListener\n * @see SimpleStore#updateAll\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterUpdateAll} event.\n *\n * @example\n * function onAfterUpdateAll (mapperName, props, query, opts, result) {\n * // do something\n * }\n * store.on('afterUpdateAll', onAfterUpdateAll);\n *\n * @callback SimpleStore~afterUpdateAllListener\n * @param {string} name The `name` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} props The `props` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} query The `query` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} result The `result` argument received by {@link Mapper#afterUpdateAll}.\n * @see SimpleStore#event:afterUpdateAll\n * @see SimpleStore#updateAll\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#updateAll}. Adds the updated {@link Record}s to\n * the store.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('post');\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // PUT /post?author_id=1234 {\"status\":\"published\"}\n * store.updateAll('post', { author_id: 1234 }, { status: 'published' }).then((posts) => {\n * // The post records have also been updated in the in-memory store\n * console.log(store.filter('posts', { author_id: 1234 }));\n * });\n *\n * @fires SimpleStore#beforeUpdateAll\n * @fires SimpleStore#afterUpdateAll\n * @fires SimpleStore#add\n * @method SimpleStore#updateAll\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} props Passed to {@link Mapper#updateAll}.\n * @param {object} [query] Passed to {@link Mapper#updateAll}.\n * @param {object} [opts] Passed to {@link Mapper#updateAll}. See\n * {@link Mapper#updateAll} for more configuration options.\n * @returns {Promise} Resolves with the result of the update.\n * @since 3.0.0\n */\n updateAll (name, props, query, opts) {\n opts || (opts = {})\n return Container.prototype.updateAll.call(this, name, props, query, opts)\n .then((result) => this._end(name, result, opts))\n },\n\n /**\n * Fired during {@link SimpleStore#updateMany}. See\n * {@link SimpleStore~beforeUpdateManyListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeUpdateMany\n * @see SimpleStore~beforeUpdateManyListener\n * @see SimpleStore#updateMany\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeUpdateMany} event.\n *\n * @example\n * function onBeforeUpdateMany (mapperName, records, opts) {\n * // do something\n * }\n * store.on('beforeUpdateMany', onBeforeUpdateMany);\n *\n * @callback SimpleStore~beforeUpdateManyListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeUpdateMany}.\n * @param {object} records The `records` argument received by {@link Mapper#beforeUpdateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateMany}.\n * @see SimpleStore#event:beforeUpdateMany\n * @see SimpleStore#updateMany\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#updateMany}. See\n * {@link SimpleStore~afterUpdateManyListener} for how to listen for this event.\n *\n * @event SimpleStore#afterUpdateMany\n * @see SimpleStore~afterUpdateManyListener\n * @see SimpleStore#updateMany\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterUpdateMany} event.\n *\n * @example\n * function onAfterUpdateMany (mapperName, records, opts, result) {\n * // do something\n * }\n * store.on('afterUpdateMany', onAfterUpdateMany);\n *\n * @callback SimpleStore~afterUpdateManyListener\n * @param {string} name The `name` argument received by {@link Mapper#afterUpdateMany}.\n * @param {object} records The `records` argument received by {@link Mapper#afterUpdateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateMany}.\n * @param {object} result The `result` argument received by {@link Mapper#afterUpdateMany}.\n * @see SimpleStore#event:afterUpdateMany\n * @see SimpleStore#updateMany\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#updateMany}. Adds the updated {@link Record}s to\n * the store.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('post');\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // PUT /post [{\"id\":3,status\":\"published\"},{\"id\":4,status\":\"published\"}]\n * store.updateMany('post', [\n * { id: 3, status: 'published' },\n * { id: 4, status: 'published' }\n * ]).then((posts) => {\n * // The post records have also been updated in the in-memory store\n * console.log(store.getAll('post', 3, 4));\n * });\n *\n * @fires SimpleStore#beforeUpdateMany\n * @fires SimpleStore#afterUpdateMany\n * @fires SimpleStore#add\n * @method SimpleStore#updateMany\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(Object[]|Record[])} records Passed to {@link Mapper#updateMany}.\n * @param {object} [opts] Passed to {@link Mapper#updateMany}. See\n * {@link Mapper#updateMany} for more configuration options.\n * @returns {Promise} Resolves with the result of the update.\n * @since 3.0.0\n */\n updateMany (name, records, opts) {\n opts || (opts = {})\n return Container.prototype.updateMany.call(this, name, records, opts)\n .then((result) => this._end(name, result, opts))\n }\n}\n\nproxiedCollectionMethods.forEach(function (method) {\n props[method] = function (name, ...args) {\n return this.getCollection(name)[method](...args)\n }\n})\n\nexport default Container.extend(props)\n\n/**\n * Fired when a record changes. Only works for records that have tracked fields.\n * See {@link SimpleStore~changeListener} on how to listen for this event.\n *\n * @event SimpleStore#change\n * @see SimpleStore~changeListener\n */\n\n/**\n * Callback signature for the {@link SimpleStore#event:change} event.\n *\n * @example\n * function onChange (mapperName, record, changes) {\n * // do something\n * }\n * store.on('change', onChange);\n *\n * @callback SimpleStore~changeListener\n * @param {string} name The name of the associated {@link Mapper}.\n * @param {Record} record The Record that changed.\n * @param {object} changes The changes.\n * @see SimpleStore#event:change\n * @since 3.0.0\n */\n\n/**\n * Fired when one or more records are added to the in-memory store. See\n * {@link SimpleStore~addListener} on how to listen for this event.\n *\n * @event SimpleStore#add\n * @see SimpleStore~addListener\n * @see SimpleStore#event:add\n * @see SimpleStore#add\n * @see SimpleStore#create\n * @see SimpleStore#createMany\n * @see SimpleStore#find\n * @see SimpleStore#findAll\n * @see SimpleStore#update\n * @see SimpleStore#updateAll\n * @see SimpleStore#updateMany\n */\n\n/**\n * Callback signature for the {@link SimpleStore#event:add} event.\n *\n * @example\n * function onAdd (mapperName, recordOrRecords) {\n * // do something\n * }\n * store.on('add', onAdd);\n *\n * @callback SimpleStore~addListener\n * @param {string} name The name of the associated {@link Mapper}.\n * @param {Record|Record[]} The Record or Records that were added.\n * @see SimpleStore#event:add\n * @see SimpleStore#add\n * @see SimpleStore#create\n * @see SimpleStore#createMany\n * @see SimpleStore#find\n * @see SimpleStore#findAll\n * @see SimpleStore#update\n * @see SimpleStore#updateAll\n * @see SimpleStore#updateMany\n * @since 3.0.0\n */\n\n/**\n * Fired when one or more records are removed from the in-memory store. See\n * {@link SimpleStore~removeListener} for how to listen for this event.\n *\n * @event SimpleStore#remove\n * @see SimpleStore~removeListener\n * @see SimpleStore#event:remove\n * @see SimpleStore#clear\n * @see SimpleStore#destroy\n * @see SimpleStore#destroyAll\n * @see SimpleStore#remove\n * @see SimpleStore#removeAll\n */\n\n/**\n * Callback signature for the {@link SimpleStore#event:remove} event.\n *\n * @example\n * function onRemove (mapperName, recordsOrRecords) {\n * // do something\n * }\n * store.on('remove', onRemove);\n *\n * @callback SimpleStore~removeListener\n * @param {string} name The name of the associated {@link Mapper}.\n * @param {Record|Record[]} Record or Records that were removed.\n * @see SimpleStore#event:remove\n * @see SimpleStore#clear\n * @see SimpleStore#destroy\n * @see SimpleStore#destroyAll\n * @see SimpleStore#remove\n * @see SimpleStore#removeAll\n * @since 3.0.0\n */\n\n/**\n * Create a subclass of this SimpleStore:\n * @example SimpleStore.extend\n * const JSData = require('js-data');\n * const { SimpleStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomSimpleStoreClass extends SimpleStore {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customSimpleStore = new CustomSimpleStoreClass();\n * console.log(customSimpleStore.foo());\n * console.log(CustomSimpleStoreClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherSimpleStoreClass = SimpleStore.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * })\n * const otherSimpleStore = new OtherSimpleStoreClass();\n * console.log(otherSimpleStore.foo());\n * console.log(OtherSimpleStoreClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherSimpleStoreClass () {\n * SimpleStore.call(this)\n * this.created_at = new Date().getTime()\n * }\n * SimpleStore.extend({\n * constructor: AnotherSimpleStoreClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * })\n * const anotherSimpleStore = new AnotherSimpleStoreClass();\n * console.log(anotherSimpleStore.created_at);\n * console.log(anotherSimpleStore.foo());\n * console.log(AnotherSimpleStoreClass.beep());\n *\n * @method SimpleStore.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this SimpleStore class.\n * @since 3.0.0\n */\n","import utils from './utils'\nimport './decorators'\nimport Collection from './Collection'\n\nconst DOMAIN = 'LinkedCollection'\n\n/**\n * Extends {@link Collection}. Used by a {@link DataStore} to implement an\n * Identity Map.\n *\n * ```javascript\n * import {LinkedCollection} from 'js-data'\n * ```\n *\n * @class LinkedCollection\n * @extends Collection\n * @param {array} [records] Initial set of records to insert into the\n * collection. See {@link Collection}.\n * @param {object} [opts] Configuration options. See {@link Collection}.\n * @returns {Mapper}\n */\nfunction LinkedCollection (records, opts) {\n utils.classCallCheck(this, LinkedCollection)\n // Make sure this collection has somewhere to store \"added\" timestamps\n Object.defineProperties(this, {\n _added: {\n value: {}\n },\n datastore: {\n writable: true,\n value: undefined\n }\n })\n\n Collection.call(this, records, opts)\n\n // Make sure this collection has a reference to a datastore\n if (!this.datastore) {\n throw utils.err(`new ${DOMAIN}`, 'opts.datastore')(400, 'DataStore', this.datastore)\n }\n}\n\nexport default Collection.extend({\n constructor: LinkedCollection,\n\n _addMeta (record, timestamp) {\n // Track when this record was added\n this._added[this.recordId(record)] = timestamp\n\n if (utils.isFunction(record._set)) {\n record._set('$', timestamp)\n }\n },\n\n _clearMeta (record) {\n delete this._added[this.recordId(record)]\n if (utils.isFunction(record._set)) {\n record._set('$') // unset\n }\n },\n\n _onRecordEvent (...args) {\n Collection.prototype._onRecordEvent.apply(this, args)\n const event = args[0]\n // This is a very brute force method\n // Lots of room for optimization\n if (utils.isString(event) && event.indexOf('change') === 0) {\n this.updateIndexes(args[1])\n }\n },\n\n add (records, opts) {\n const mapper = this.mapper\n const timestamp = new Date().getTime()\n const singular = utils.isObject(records) && !utils.isArray(records)\n\n if (singular) {\n records = [records]\n }\n records = Collection.prototype.add.call(this, records, opts)\n\n if (mapper.relationList.length && records.length) {\n // Check the currently visited record for relations that need to be\n // inserted into their respective collections.\n mapper.relationList.forEach(function (def) {\n def.addLinkedRecords(records)\n })\n }\n\n records.forEach((record) => this._addMeta(record, timestamp))\n\n return singular ? records[0] : records\n },\n\n remove (idOrRecord, opts) {\n const mapper = this.mapper\n const record = Collection.prototype.remove.call(this, idOrRecord, opts)\n if (record) {\n this._clearMeta(record)\n }\n\n if (mapper.relationList.length && record) {\n mapper.relationList.forEach(function (def) {\n def.removeLinkedRecords(mapper, [record])\n })\n }\n\n return record\n },\n\n removeAll (query, opts) {\n const mapper = this.mapper\n const records = Collection.prototype.removeAll.call(this, query, opts)\n records.forEach(this._clearMeta, this)\n\n if (mapper.relationList.length && records.length) {\n mapper.relationList.forEach(function (def) {\n def.removeLinkedRecords(mapper, records)\n })\n }\n\n return records\n }\n})\n\n/**\n * Create a subclass of this LinkedCollection:\n *\n * @example LinkedCollection.extend\n * const JSData = require('js-data');\n * const { LinkedCollection } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomLinkedCollectionClass extends LinkedCollection {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customLinkedCollection = new CustomLinkedCollectionClass();\n * console.log(customLinkedCollection.foo());\n * console.log(CustomLinkedCollectionClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherLinkedCollectionClass = LinkedCollection.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherLinkedCollection = new OtherLinkedCollectionClass();\n * console.log(otherLinkedCollection.foo());\n * console.log(OtherLinkedCollectionClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherLinkedCollectionClass () {\n * LinkedCollection.call(this);\n * this.created_at = new Date().getTime();\n * }\n * LinkedCollection.extend({\n * constructor: AnotherLinkedCollectionClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const anotherLinkedCollection = new AnotherLinkedCollectionClass();\n * console.log(anotherLinkedCollection.created_at);\n * console.log(anotherLinkedCollection.foo());\n * console.log(AnotherLinkedCollectionClass.beep());\n *\n * @method LinkedCollection.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this LinkedCollection class.\n * @since 3.0.0\n */\n","import utils, { safeSetLink, safeSetProp } from './utils'\n\nimport {\n belongsToType,\n hasManyType,\n hasOneType\n} from './decorators'\nimport SimpleStore from './SimpleStore'\nimport LinkedCollection from './LinkedCollection'\n\nconst DATASTORE_DEFAULTS = {\n /**\n * Whether in-memory relations should be unlinked from records after they are\n * destroyed.\n *\n * @default true\n * @name DataStore#unlinkOnDestroy\n * @since 3.0.0\n * @type {boolean}\n */\n unlinkOnDestroy: true\n}\n\n/**\n * The `DataStore` class is an extension of {@link SimpleStore}. Not only does\n * `DataStore` manage mappers and store data in collections, it uses the\n * {@link LinkedCollection} class to link related records together in memory.\n *\n * ```javascript\n * import { DataStore } from 'js-data';\n * ```\n *\n * @example\n * import { DataStore } from 'js-data';\n * import HttpAdapter from 'js-data-http';\n * const store = new DataStore();\n *\n * // DataStore#defineMapper returns a direct reference to the newly created\n * // Mapper.\n * const UserMapper = store.defineMapper('user');\n *\n * // DataStore#as returns the store scoped to a particular Mapper.\n * const UserStore = store.as('user');\n *\n * // Call \"find\" on \"UserMapper\" (Stateless ORM)\n * UserMapper.find(1).then((user) => {\n * // retrieved a \"user\" record via the http adapter, but that's it\n *\n * // Call \"find\" on \"store\" targeting \"user\" (Stateful DataStore)\n * return store.find('user', 1); // same as \"UserStore.find(1)\"\n * }).then((user) => {\n * // not only was a \"user\" record retrieved, but it was added to the\n * // store's \"user\" collection\n * const cachedUser = store.getCollection('user').get(1);\n * console.log(user === cachedUser); // true\n * });\n *\n * @class DataStore\n * @extends SimpleStore\n * @param {object} [opts] Configuration options. See {@link SimpleStore}.\n * @param {boolean} [opts.collectionClass={@link LinkedCollection}] See {@link DataStore#collectionClass}.\n * @param {boolean} [opts.debug=false] See {@link Component#debug}.\n * @param {boolean} [opts.unlinkOnDestroy=true] See {@link DataStore#unlinkOnDestroy}.\n * @param {boolean|Function} [opts.usePendingFind=true] See {@link DataStore#usePendingFind}.\n * @param {boolean|Function} [opts.usePendingFindAll=true] See {@link DataStore#usePendingFindAll}.\n * @returns {DataStore}\n * @see SimpleStore\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#datastore\",\"Components of JSData: DataStore\"]\n * @tutorial [\"http://www.js-data.io/v3.0/docs/working-with-the-datastore\",\"Working with the DataStore\"]\n * @tutorial [\"http://www.js-data.io/v3.0/docs/jsdata-and-the-browser\",\"Notes on using JSData in the Browser\"]\n */\nfunction DataStore (opts) {\n utils.classCallCheck(this, DataStore)\n\n opts || (opts = {})\n // Fill in any missing options with the defaults\n utils.fillIn(opts, DATASTORE_DEFAULTS)\n opts.collectionClass || (opts.collectionClass = LinkedCollection)\n SimpleStore.call(this, opts)\n}\n\nconst props = {\n constructor: DataStore,\n\n defineMapper (name, opts) {\n // Complexity of this method is beyond simply using => functions to bind context\n const self = this\n const mapper = SimpleStore.prototype.defineMapper.call(self, name, opts)\n const idAttribute = mapper.idAttribute\n const collection = this.getCollection(name)\n\n mapper.relationList.forEach(function (def) {\n const relation = def.relation\n const localField = def.localField\n const path = `links.${localField}`\n const foreignKey = def.foreignKey\n const type = def.type\n const updateOpts = { index: foreignKey }\n let descriptor\n\n const getter = function () { return this._get(path) }\n\n if (type === belongsToType) {\n if (!collection.indexes[foreignKey]) {\n collection.createIndex(foreignKey)\n }\n\n descriptor = {\n get: getter,\n // e.g. profile.user = someUser\n // or comment.post = somePost\n set (record) {\n // e.g. const otherUser = profile.user\n const currentParent = this._get(path)\n // e.g. profile.user === someUser\n if (record === currentParent) {\n return currentParent\n }\n const id = utils.get(this, idAttribute)\n const inverseDef = def.getInverse(mapper)\n\n // e.g. profile.user !== someUser\n // or comment.post !== somePost\n if (currentParent && inverseDef) {\n this.removeInverseRelation(currentParent, id, inverseDef, idAttribute)\n }\n if (record) {\n // e.g. profile.user = someUser\n const relatedIdAttribute = def.getRelation().idAttribute\n const relatedId = utils.get(record, relatedIdAttribute)\n\n // Prefer store record\n if (relatedId !== undefined && this._get('$')) {\n record = self.get(relation, relatedId) || record\n }\n\n // Set locals\n // e.g. profile.user = someUser\n // or comment.post = somePost\n safeSetLink(this, localField, record)\n safeSetProp(this, foreignKey, relatedId)\n collection.updateIndex(this, updateOpts)\n\n if (inverseDef) {\n this.setupInverseRelation(record, id, inverseDef, idAttribute)\n }\n } else {\n // Unset in-memory link only\n // e.g. profile.user = undefined\n // or comment.post = undefined\n safeSetLink(this, localField, undefined)\n }\n return record\n }\n }\n\n let foreignKeyDescriptor = Object.getOwnPropertyDescriptor(mapper.recordClass.prototype, foreignKey)\n if (!foreignKeyDescriptor) {\n foreignKeyDescriptor = {\n enumerable: true\n }\n }\n const originalGet = foreignKeyDescriptor.get\n foreignKeyDescriptor.get = function () {\n if (originalGet) {\n return originalGet.call(this)\n }\n return this._get(`props.${foreignKey}`)\n }\n const originalSet = foreignKeyDescriptor.set\n foreignKeyDescriptor.set = function (value) {\n if (originalSet) {\n originalSet.call(this, value)\n }\n const currentParent = utils.get(this, localField)\n const id = utils.get(this, idAttribute)\n const inverseDef = def.getInverse(mapper)\n const currentParentId = currentParent ? utils.get(currentParent, def.getRelation().idAttribute) : undefined\n\n if (currentParent && currentParentId !== undefined && currentParentId !== value) {\n if (inverseDef.type === hasOneType) {\n safeSetLink(currentParent, inverseDef.localField, undefined)\n } else if (inverseDef.type === hasManyType) {\n const children = utils.get(currentParent, inverseDef.localField)\n if (id === undefined) {\n utils.remove(children, (child) => child === this)\n } else {\n utils.remove(children, (child) => child === this || id === utils.get(child, idAttribute))\n }\n }\n }\n\n safeSetProp(this, foreignKey, value)\n collection.updateIndex(this, updateOpts)\n\n if ((value === undefined || value === null)) {\n if (currentParentId !== undefined) {\n // Unset locals\n utils.set(this, localField, undefined)\n }\n } else if (this._get('$')) {\n const storeRecord = self.get(relation, value)\n if (storeRecord) {\n utils.set(this, localField, storeRecord)\n }\n }\n }\n Object.defineProperty(mapper.recordClass.prototype, foreignKey, foreignKeyDescriptor)\n } else if (type === hasManyType) {\n const localKeys = def.localKeys\n const foreignKeys = def.foreignKeys\n\n // TODO: Handle case when belongsTo relation isn't ever defined\n if (self._collections[relation] && foreignKey && !self.getCollection(relation).indexes[foreignKey]) {\n self.getCollection(relation).createIndex(foreignKey)\n }\n\n descriptor = {\n get () {\n let current = getter.call(this)\n if (!current) {\n this._set(path, [])\n }\n return getter.call(this)\n },\n // e.g. post.comments = someComments\n // or user.groups = someGroups\n // or group.users = someUsers\n set (records) {\n if (records && !utils.isArray(records)) {\n records = [records]\n }\n const id = utils.get(this, idAttribute)\n const relatedIdAttribute = def.getRelation().idAttribute\n const inverseDef = def.getInverse(mapper)\n const inverseLocalField = inverseDef.localField\n const current = this._get(path) || []\n const toLink = []\n const toLinkIds = {}\n\n if (records) {\n records.forEach((record) => {\n // e.g. comment.id\n const relatedId = utils.get(record, relatedIdAttribute)\n const currentParent = utils.get(record, inverseLocalField)\n if (currentParent && currentParent !== this) {\n const currentChildrenOfParent = utils.get(currentParent, localField)\n // e.g. somePost.comments.remove(comment)\n if (relatedId === undefined) {\n utils.remove(currentChildrenOfParent, (child) => child === record)\n } else {\n utils.remove(currentChildrenOfParent, (child) => child === record || relatedId === utils.get(child, relatedIdAttribute))\n }\n }\n if (relatedId !== undefined) {\n if (this._get('$')) {\n // Prefer store record\n record = self.get(relation, relatedId) || record\n }\n // e.g. toLinkIds[comment.id] = comment\n toLinkIds[relatedId] = record\n }\n toLink.push(record)\n })\n }\n\n // e.g. post.comments = someComments\n if (foreignKey) {\n current.forEach((record) => {\n // e.g. comment.id\n const relatedId = utils.get(record, relatedIdAttribute)\n if ((relatedId === undefined && toLink.indexOf(record) === -1) || (relatedId !== undefined && !(relatedId in toLinkIds))) {\n // Update (unset) inverse relation\n if (records) {\n // e.g. comment.post_id = undefined\n safeSetProp(record, foreignKey, undefined)\n // e.g. CommentCollection.updateIndex(comment, { index: 'post_id' })\n self.getCollection(relation).updateIndex(record, updateOpts)\n }\n // e.g. comment.post = undefined\n safeSetLink(record, inverseLocalField, undefined)\n }\n })\n toLink.forEach((record) => {\n // Update (set) inverse relation\n // e.g. comment.post_id = post.id\n safeSetProp(record, foreignKey, id)\n // e.g. CommentCollection.updateIndex(comment, { index: 'post_id' })\n self.getCollection(relation).updateIndex(record, updateOpts)\n // e.g. comment.post = post\n safeSetLink(record, inverseLocalField, this)\n })\n } else if (localKeys) {\n // Update locals\n // e.g. group.users = someUsers\n // Update (set) inverse relation\n const ids = toLink.map((child) => utils.get(child, relatedIdAttribute)).filter((id) => id !== undefined)\n // e.g. group.user_ids = [1,2,3,...]\n utils.set(this, localKeys, ids)\n // Update (unset) inverse relation\n if (inverseDef.foreignKeys) {\n current.forEach((child) => {\n const relatedId = utils.get(child, relatedIdAttribute)\n if ((relatedId === undefined && toLink.indexOf(child) === -1) || (relatedId !== undefined && !(relatedId in toLinkIds))) {\n // Update inverse relation\n // safeSetLink(child, inverseLocalField, undefined)\n const parents = utils.get(child, inverseLocalField) || []\n // e.g. someUser.groups.remove(group)\n if (id === undefined) {\n utils.remove(parents, (parent) => parent === this)\n } else {\n utils.remove(parents, (parent) => parent === this || id === utils.get(parent, idAttribute))\n }\n }\n })\n toLink.forEach((child) => {\n // Update (set) inverse relation\n const parents = utils.get(child, inverseLocalField)\n // e.g. someUser.groups.push(group)\n if (id === undefined) {\n utils.noDupeAdd(parents, this, (parent) => parent === this)\n } else {\n utils.noDupeAdd(parents, this, (parent) => parent === this || id === utils.get(parent, idAttribute))\n }\n })\n }\n } else if (foreignKeys) {\n // e.g. user.groups = someGroups\n // Update (unset) inverse relation\n current.forEach((parent) => {\n const ids = utils.get(parent, foreignKeys) || []\n // e.g. someGroup.user_ids.remove(user.id)\n utils.remove(ids, (_key) => id === _key)\n const children = utils.get(parent, inverseLocalField)\n // e.g. someGroup.users.remove(user)\n if (id === undefined) {\n utils.remove(children, (child) => child === this)\n } else {\n utils.remove(children, (child) => child === this || id === utils.get(child, idAttribute))\n }\n })\n // Update (set) inverse relation\n toLink.forEach((parent) => {\n const ids = utils.get(parent, foreignKeys) || []\n utils.noDupeAdd(ids, id, (_key) => id === _key)\n const children = utils.get(parent, inverseLocalField)\n if (id === undefined) {\n utils.noDupeAdd(children, this, (child) => child === this)\n } else {\n utils.noDupeAdd(children, this, (child) => child === this || id === utils.get(child, idAttribute))\n }\n })\n }\n\n this._set(path, toLink)\n return toLink\n }\n }\n } else if (type === hasOneType) {\n // TODO: Handle case when belongsTo relation isn't ever defined\n if (self._collections[relation] && foreignKey && !self.getCollection(relation).indexes[foreignKey]) {\n self.getCollection(relation).createIndex(foreignKey)\n }\n descriptor = {\n get: getter,\n // e.g. user.profile = someProfile\n set (record) {\n const current = this._get(path)\n if (record === current) {\n return current\n }\n const inverseLocalField = def.getInverse(mapper).localField\n // Update (unset) inverse relation\n if (current) {\n safeSetProp(current, foreignKey, undefined)\n self.getCollection(relation).updateIndex(current, updateOpts)\n safeSetLink(current, inverseLocalField, undefined)\n }\n if (record) {\n const relatedId = utils.get(record, def.getRelation().idAttribute)\n // Prefer store record\n if (relatedId !== undefined) {\n record = self.get(relation, relatedId) || record\n }\n\n // Set locals\n safeSetLink(this, localField, record)\n\n // Update (set) inverse relation\n safeSetProp(record, foreignKey, utils.get(this, idAttribute))\n self.getCollection(relation).updateIndex(record, updateOpts)\n safeSetLink(record, inverseLocalField, this)\n } else {\n // Unset locals\n safeSetLink(this, localField, undefined)\n }\n return record\n }\n }\n }\n\n if (descriptor) {\n descriptor.enumerable = def.enumerable === undefined ? false : def.enumerable\n if (def.get) {\n let origGet = descriptor.get\n descriptor.get = function () {\n return def.get(def, this, (...args) => origGet.apply(this, args))\n }\n }\n if (def.set) {\n let origSet = descriptor.set\n descriptor.set = function (related) {\n return def.set(def, this, related, (value) => origSet.call(this, value === undefined ? related : value))\n }\n }\n Object.defineProperty(mapper.recordClass.prototype, localField, descriptor)\n }\n })\n\n return mapper\n },\n\n destroy (name, id, opts) {\n opts || (opts = {})\n return SimpleStore.prototype.destroy.call(this, name, id, opts).then((result) => {\n let record\n if (opts.raw) {\n record = result.data\n } else {\n record = result\n }\n\n if (record && this.unlinkOnDestroy) {\n const _opts = utils.plainCopy(opts)\n _opts.withAll = true\n utils.forEachRelation(this.getMapper(name), _opts, (def) => {\n utils.set(record, def.localField, undefined)\n })\n }\n return result\n })\n },\n\n destroyAll (name, query, opts) {\n opts || (opts = {})\n return SimpleStore.prototype.destroyAll.call(this, name, query, opts).then((result) => {\n let records\n if (opts.raw) {\n records = result.data\n } else {\n records = result\n }\n\n if (records && records.length && this.unlinkOnDestroy) {\n const _opts = utils.plainCopy(opts)\n _opts.withAll = true\n utils.forEachRelation(this.getMapper(name), _opts, (def) => {\n records.forEach((record) => {\n utils.set(record, def.localField, undefined)\n })\n })\n }\n return result\n })\n }\n}\n\nexport default SimpleStore.extend(props)\n\n/**\n * Create a subclass of this DataStore:\n * @example DataStore.extend\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomDataStoreClass extends DataStore {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customDataStore = new CustomDataStoreClass();\n * console.log(customDataStore.foo());\n * console.log(CustomDataStoreClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherDataStoreClass = DataStore.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherDataStore = new OtherDataStoreClass();\n * console.log(otherDataStore.foo());\n * console.log(OtherDataStoreClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherDataStoreClass () {\n * DataStore.call(this);\n * this.created_at = new Date().getTime();\n * }\n * DataStore.extend({\n * constructor: AnotherDataStoreClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const anotherDataStore = new AnotherDataStoreClass();\n * console.log(anotherDataStore.created_at);\n * console.log(anotherDataStore.foo());\n * console.log(AnotherDataStoreClass.beep());\n *\n * @method DataStore.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this DataStore class.\n * @since 3.0.0\n */\n","/**\n * Registered as `js-data` in NPM and Bower.\n *\n * Also available from CDN.JS and JSDelivr.\n *\n * @module js-data\n *\n * @example Install from NPM\n * npm i --save js-data@beta\n * @example Install from Bower\n * bower i --save js-data@3.0.0-beta.1\n * @example Install from CDN.JS\n * \n * @example Install from JSDelivr\n * \n * @example Load into your app via script tag\n * \n * \n * @example Load into your app via CommonJS\n * var JSData = require('js-data');\n * @example Load into your app via ES2015 Modules\n * import * as JSData from 'js-data';\n * @example Load into your app via AMD\n * define('myApp', ['js-data'], function (JSData) { ... });\n */\n\n/**\n * JSData's utility methods.\n *\n * @example\n * import { utils } from 'js-data';\n * console.log(utils.isString('foo')); // true\n *\n * @name module:js-data.utils\n * @property {Function} Promise See {@link utils.Promise}.\n * @see utils\n * @since 3.0.0\n * @type {Object}\n */\nimport utils from './utils'\n\n/**\n * JSData's {@link Collection} class.\n *\n * @example\n * import { Collection } from 'js-data';\n * const collection = new Collection();\n *\n * @name module:js-data.Collection\n * @see Collection\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#collection\",\"Components of JSData: Collection\"]\n * @type {Constructor}\n */\nimport Collection from './Collection'\n\n/**\n * JSData's {@link Component} class. Most components in JSData extend this\n * class.\n *\n * @example\n * import { Component } from 'js-data';\n * // Make a custom component.\n * const MyComponent = Component.extend({\n * myMethod (someArg) { ... }\n * });\n *\n * @name module:js-data.Component\n * @see Component\n * @since 3.0.0\n * @type {Constructor}\n */\nimport Component from './Component'\n\n/**\n * JSData's {@link Container} class. Defines and manages {@link Mapper}s. Used\n * in Node.js and in the browser, though in the browser you may want to use\n * {@link DataStore} instead.\n *\n * @example\n * import { Container } from 'js-data';\n * const store = new Container();\n *\n * @name module:js-data.Container\n * @see Container\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#container\",\"Components of JSData: Container\"]\n * @type {Constructor}\n */\nimport {Container} from './Container'\n\n/**\n * JSData's {@link DataStore} class. Primarily for use in the browser. In\n * Node.js you probably want to use {@link Container} instead.\n *\n * @example\n * import { DataStore } from 'js-data';\n * const store = new DataStore();\n *\n * @name module:js-data.DataStore\n * @see DataStore\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#datastore\",\"Components of JSData: DataStore\"]\n * @type {Constructor}\n */\nimport DataStore from './DataStore'\n\n/**\n * JSData's {@link Index} class, based on [mindex]{@link https://github.com/internalfx/mindex}.\n *\n * @name module:js-data.Index\n * @see Index\n * @since 3.0.0\n * @type {Constructor}\n */\nimport Index from '../lib/mindex/index'\n\n/**\n * JSData's {@link LinkedCollection} class. Used by the {@link DataStore}\n * component. If you need to create a collection manually, you should probably\n * use the {@link Collection} class.\n *\n * @name module:js-data.LinkedCollection\n * @see DataStore\n * @see LinkedCollection\n * @since 3.0.0\n * @type {Constructor}\n */\nimport LinkedCollection from './LinkedCollection'\n\n/**\n * JSData's {@link Mapper} class. The core of the ORM.\n *\n * @example Recommended use\n * import { Container } from 'js-data';\n * const store = new Container();\n * store.defineMapper('user');\n *\n * @example Create Mapper manually\n * import { Mapper } from 'js-data';\n * const UserMapper = new Mapper({ name: 'user' });\n *\n * @name module:js-data.Mapper\n * @see Container\n * @see Mapper\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/modeling-your-data\",\"Modeling your data\"]\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#mapper\",\"Components of JSData: Mapper\"]\n * @type {Constructor}\n */\nimport Mapper from './Mapper'\n\n/**\n * JSData's {@link Query} class. Used by the {@link Collection} component.\n *\n * @name module:js-data.Query\n * @see Query\n * @since 3.0.0\n * @type {Constructor}\n */\nimport Query from './Query'\n\n/**\n * JSData's {@link Record} class.\n *\n * @example\n * import { Container } from 'js-data';\n * const store = new Container();\n * store.defineMapper('user');\n * const user = store.createRecord('user');\n *\n * @name module:js-data.Record\n * @see Record\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#record\",\"Components of JSData: Record\"]\n * @type {Constructor}\n */\nimport Record from './Record'\n\n/**\n * JSData's {@link Schema} class. Implements http://json-schema.org/draft-04.\n *\n * @example\n * import { Container, Schema } from 'js-data';\n * const userSchema = new Schema({\n * properties: {\n * id: { type: 'string' },\n * name: { type: 'string' }\n * }\n * });\n * const store = new Container();\n * store.defineMapper('user', {\n * schema: userSchema\n * });\n *\n * @name module:js-data.Schema\n * @see Schema\n * @see http://json-schema.org/\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#schema\",\"Components of JSData: schema\"]\n * @tutorial [\"http://www.js-data.io/v3.0/docs/schemas\",\"JSData's Schema Syntax\"]\n * @type {Constructor}\n */\nimport Schema from './Schema'\n\n/**\n * JSData's {@link Settable} class.\n *\n * @example\n * import { Settable } from 'js-data';\n * const obj = new Settable();\n * obj.set('secret', 'value');\n * console.log(JSON.stringify(obj)); // {}\n *\n * @name module:js-data.Settable\n * @see Settable\n * @since 3.0.0\n * @type {Constructor}\n */\nimport Settable from './Settable'\n\n/**\n * JSData's {@link SimpleStore} class. Primarily for use in the browser. In\n * Node.js you probably want to use {@link Container} instead.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * const store = new SimpleStore();\n *\n * @name module:js-data.SimpleStore\n * @see SimpleStore\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#SimpleStore\",\"Components of JSData: SimpleStore\"]\n * @type {Constructor}\n */\nimport SimpleStore from './SimpleStore'\n\n/**\n * Describes the version of this `JSData` object.\n *\n * @example\n * console.log(JSData.version.full); // \"3.0.0-beta.1\"\n *\n * @name version\n * @memberof module:js-data\n * @property {string} full The full semver value.\n * @property {number} major The major version number.\n * @property {number} minor The minor version number.\n * @property {number} patch The patch version number.\n * @property {(string|boolean)} alpha The alpha version value, otherwise `false`\n * if the current version is not alpha.\n * @property {(string|boolean)} beta The beta version value, otherwise `false`\n * if the current version is not beta.\n * @since 2.0.0\n * @type {Object}\n */\nexport const version = '<%= version %>'\n\nexport * from './decorators'\n\nexport {\n Collection,\n Component,\n Container,\n DataStore,\n Index,\n LinkedCollection,\n Mapper,\n Query,\n Record,\n Schema,\n Settable,\n SimpleStore,\n utils\n}\n"],"names":["DOMAIN","INFINITY","MAX_INTEGER","BOOL_TAG","DATE_TAG","FUNC_TAG","NUMBER_TAG","OBJECT_TAG","REGEXP_TAG","STRING_TAG","objToString","Object","prototype","toString","PATH","ERRORS","arguments","toInteger","value","sign","remainder","toStr","call","isPlainObject","constructor","mkdirP","object","path","parts","split","forEach","key","utils","Promise","dest","src","forOwn","undefined","isFunction","indexOf","opts","def","fn","thisArg","relationName","relation","containedName","index","with","_getIndex","localField","withAll","optsCopy","fillIn","getRelation","slice","_activeWith","splice","i","length","substr","list","_relation","isObject","target","props","map","keys","propName","descriptor","getOwnPropertyDescriptor","enumerable","defineProperties","newObject","oldObject","diff","diffObjects","diffCount","added","removed","changed","instance","ctor","err","name","from","to","stackFrom","stackTo","blacklist","plain","isArray","copy","isDate","Date","getTime","isRegExp","RegExp","source","match","lastIndex","create","getPrototypeOf","push","result","hasOwnProperty","isBlacklisted","existing","deepFillIn","deepMixIn","equalsFn","ignore","deepEqual","newKeys","filter","oldKeys","oldValue","newValue","a","b","domain","code","prefix","message","apply","Array","Error","getter","setter","_events","events","args","type","shift","listeners","f","c","all","unshift","func","classProps","superClass","subClass","classCallCheck","obj","setPrototypeOf","strictEs6Class","__proto__","defineProperty","addHiddenPropsToTarget","array","record","mapper","relationList","_forRelation","len","json","isString","JSON","parse","prop","last","pop","isCtor","__super__","array1","array2","item","matches","test","isNumber","log","level","debug","toUpperCase","console","findIndex","_props","reduce","reject","resolve","_path","set","exec","_equal","stringify","safeSetProp","field","_set","safeSetLink","Settable","get","unset","extend","Component","writable","logify","eventify","_listeners","INDEX_ERR","reserved","escapeRegExp","percentRegExp","underscoreRegExp","escape","pattern","replace","Query","collection","data","where","fields","ops","predicates","clause","expr","op","groups","_where","prev","parser","_applyWhereFromArray","_applyWhereFromObject","group","isOr","keep","first","charAt","evaluate","_testArrayGroup","_testObjectGroup","leftKeys","rightKeys","getIndex","between","orderBy","cA","cB","temp","compare","predicate","like","query","getData","sort","skip","offset","limit","forEachFn","keyList","concat","getAll","flags","num","Math","min","mapFn","funcName","intersection","belongsToType","hasManyType","hasOneType","Relation","relatedMapper","options","TYPE_NAME","validateOptions","canAutoAddLinks","add","relatedCollection","datastore","getCollection","related","DOMAIN_ERR","foreignKey","localKey","relationFields","idAttribute","relatedRecord","_setForeignKey","relatedRecords","relatedData","inverse","findInverseRelation","isInversedTo","records","getLocalField","linkRecord","isEmptyLinks","canFindLinkFor","findExistingLinksFor","setLocalField","relatedId","unsaved","setForeignKey","id","relationData","is","createRecord","createLinked","then","BelongsToRelation","HasManyRelation","localKeys","foreignKeys","hasForeignKeys","recordId","ids","findExistingLinksByForeignKey","findExistingLinksByLocalKeys","findExistingLinksByForeignKeys","foreignIdField","createMany","HasOneRelation","RelationType","belongsTo","assignTo","hasMany","hasOne","superMethod","store","bind","creatingPath","noValidatePath","keepChangeHistoryPath","previousPath","Record","noValidate","keepChangeHistory","validateOnSet","toJSON","plainCopy","_get","_mapper","quickHasChanges","areDifferent","validate","currentParent","inverseDef","children","remove","child","noDupeAdd","relations","_","adapter","getAdapterName","dbg","tasks","task","forEachRelation","raw","load","isSorN","previous","preserve","commit","postProcess","changesOnly","changes","silent","hashCode","insertAt","removeAt","binarySearch","lo","hi","compared","mid","Index","fieldList","fieldGetter","isIndex","values","pos","found","dataLocation","newIndex","results","order","cb","visitAll","_between","leftKey","rightKey","leftInclusive","rightInclusive","currKey","peek","isUnique","removeRecord","j","insertRecord","COLLECTION_DEFAULTS","Collection","queryClass","emitRecordEvents","emit","beforeAdd","singular","onConflict","existingNoValidate","commitOnMerge","updateIndexes","indexes","on","_onRecordEvent","afterAdd","run","instances","removeAll","Ctor","initialValue","idOrRecord","beforeRemove","off","afterRemove","queryOrRecords","beforeRemoveAll","afterRemoveAll","mapCall","updateRecord","types","isBoolean","isInteger","isNull","segmentToString","segment","str","makePath","segments","makeError","actual","expected","addError","errors","maxLengthCommon","keyword","schema","max","minLengthCommon","validationKeywords","allErrors","allOf","_schema","validated","anyOf","possibleValues","join","items","checkingTuple","maximum","exclusiveMaximum","maxProperties","minimum","exclusiveMinimum","minProperties","multipleOf","not","oneOf","additionalProperties","properties","patternProperties","toValidate","omit","undef","origProp","required","existingOnly","prevProp","validType","_type","validator","typeGroupValidators","uniqueItems","runOps","ANY_OPS","ARRAY_OPS","NUMERIC_OPS","OBJECT_OPS","STRING_OPS","validateAny","ctx","shouldPop","changingPath","changedPath","changeHistoryPath","eventIdPath","silentPath","validationFailureMsg","numeric","Schema","definition","_definition","extends","validationKeyword","unsetter","track","makeDescriptor","hasSet","orig","applyDefaults","keyPath","originalGet","_unset","error","current","changing","setTimeout","changeRecord","timestamp","changeHistory","originalSet","pick","_copy","applyDefaultsHooks","validatingHooks","makeNotify","getSchema","toProcess","originalExistingOnly","notify","notify2","LIFECYCLE_METHODS","MAPPER_DEFAULTS","Mapper","recordClass","methods","isPrototypeOf","applySchema","_data","wrap","crud","originalRecord","parentRelationMap","adapterResponse","_runHook","_createParentRecordIfRequired","relationMap","_invokeAdapterMethod","createdProps","_createOrAssignChildRecordIfRequired","_commitChanges","_end","recordOrRecords","newValues","isRequiresParentId","createParentRecord","context","originalProps","isRequiresChildId","createChildRecord","parent","originalRecords","belongsToRelationData","Boolean","createdRecordsData","belongsToData","createdRecordData","ensureLinkedDataHasProperType","RecordCtor","method","config","lifecycleMethods","upper","before","after","defaults","_value","beforeAssign","adapterArgs","getAdapter","_result","getAdapters","defaultAdapter","_adapters","default","hookName","hookArgs","defaultValueIndex","overridenResult","propsOrRecords","conversionOptions","pass","_opts","_record","some","_name","getMapperByName","getMapper","proxiedMapperMethods","Container","mapperDefaults","mapperClass","original","_mappers","_onMapperEvent","defineRelations","warn","defineMapper","proxiedCollectionMethods","ownMethodsForScoping","cachedFn","hashOrId","cached","_completedQueries","SIMPLESTORE_DEFAULTS","SimpleStore","collectionClass","_collections","_pendingQueries","addToCache","hash","fromJson","self","collectionOpts","indexed","createIndex","_added","_onCollectionEvent","destroy","destroyAll","hashQuery","pendingQuery","usePendingFind","cachedFind","force","promise","find","cacheFind","usePendingFindAll","cachedFindAll","findAll","cacheFindAll","toJson","removeRelated","getForeignKey","update","updateAll","updateMany","LinkedCollection","event","addLinkedRecords","_addMeta","_clearMeta","removeLinkedRecords","DATASTORE_DEFAULTS","DataStore","updateOpts","getInverse","removeInverseRelation","relatedIdAttribute","updateIndex","setupInverseRelation","foreignKeyDescriptor","currentParentId","storeRecord","inverseLocalField","toLink","toLinkIds","currentChildrenOfParent","parents","_key","origGet","origSet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@@ +/*! +* js-data +* @version 3.0.2 - Homepage +* @author js-data project authors +* @copyright (c) 2014-2016 js-data project authors +* @license MIT +* +* @overview js-data is a framework-agnostic, datastore-agnostic ORM/ODM for Node.js and the Browser. +*/ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define('js-data', ['exports'], factory) : + (factory((global.JSData = {}))); +}(this, (function (exports) { 'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; +} : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; +}; + + + + + + + + + + + + + + + + + + + +var defineProperty = function (obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +}; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +var toConsumableArray = function (arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } else { + return Array.from(arr); + } +}; + +/** + * Utility methods used by JSData. + * + * @example + * import { utils } from 'js-data'; + * console.log(utils.isString('foo')); // true + * + * @namespace utils + * @type {Object} + */ + +var DOMAIN = 'utils'; + +var INFINITY = 1 / 0; +var MAX_INTEGER = 1.7976931348623157e+308; +var BOOL_TAG = '[object Boolean]'; +var DATE_TAG = '[object Date]'; +var FUNC_TAG = '[object Function]'; +var NUMBER_TAG = '[object Number]'; +var OBJECT_TAG = '[object Object]'; +var REGEXP_TAG = '[object RegExp]'; +var STRING_TAG = '[object String]'; +var objToString = Object.prototype.toString; +var PATH = /^(.+)\.(.+)$/; + +var ERRORS = { + '400': function _() { + return 'expected: ' + arguments[0] + ', found: ' + (arguments[2] ? arguments[1] : _typeof(arguments[1])); + }, + '404': function _() { + return arguments[0] + ' not found'; + } +}; + +var toInteger = function toInteger(value) { + if (!value) { + return 0; + } + // Coerce to number + value = +value; + if (value === INFINITY || value === -INFINITY) { + var sign = value < 0 ? -1 : 1; + return sign * MAX_INTEGER; + } + var remainder = value % 1; + return value === value ? remainder ? value - remainder : value : 0; // eslint-disable-line +}; + +var toStr = function toStr(value) { + return objToString.call(value); +}; + +var isPlainObject = function isPlainObject(value) { + return !!value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value.constructor === Object; +}; + +var mkdirP = function mkdirP(object, path) { + if (!path) { + return object; + } + var parts = path.split('.'); + parts.forEach(function (key) { + if (!object[key]) { + object[key] = {}; + } + object = object[key]; + }); + return object; +}; + +var utils = { + /** + * Reference to the Promise constructor used by JSData. Defaults to + * `window.Promise` or `global.Promise`. + * + * @example Make JSData use a different `Promise` constructor + * import Promise from 'bluebird'; + * import { utils } from 'js-data'; + * utils.Promise = Promise; + * + * @name utils.Promise + * @since 3.0.0 + * @type {Function} + */ + Promise: Promise, + + /** + * Shallow copy properties that meet the following criteria from `src` to + * `dest`: + * + * - own enumerable + * - not a function + * - does not start with "_" + * + * @method utils._ + * @param {object} dest Destination object. + * @param {object} src Source object. + * @private + * @since 3.0.0 + */ + _: function _(dest, src) { + utils.forOwn(src, function (value, key) { + if (key && dest[key] === undefined && !utils.isFunction(value) && key.indexOf('_') !== 0) { + dest[key] = value; + } + }); + }, + + + /** + * Recursively iterates over relations found in `opts.with`. + * + * @method utils._forRelation + * @param {object} opts Configuration options. + * @param {Relation} def Relation definition. + * @param {Function} fn Callback function. + * @param {*} [thisArg] Execution context for the callback function. + * @private + * @since 3.0.0 + */ + _forRelation: function _forRelation(opts, def, fn, thisArg) { + var relationName = def.relation; + var containedName = null; + var index = void 0; + opts || (opts = {}); + opts.with || (opts.with = []); + + if ((index = utils._getIndex(opts.with, relationName)) >= 0) { + containedName = relationName; + } else if ((index = utils._getIndex(opts.with, def.localField)) >= 0) { + containedName = def.localField; + } + + if (opts.withAll) { + fn.call(thisArg, def, {}); + return; + } else if (!containedName) { + return; + } + var optsCopy = {}; + utils.fillIn(optsCopy, def.getRelation()); + utils.fillIn(optsCopy, opts); + optsCopy.with = opts.with.slice(); + optsCopy._activeWith = optsCopy.with.splice(index, 1)[0]; + optsCopy.with.forEach(function (relation, i) { + if (relation && relation.indexOf(containedName) === 0 && relation.length >= containedName.length && relation[containedName.length] === '.') { + optsCopy.with[i] = relation.substr(containedName.length + 1); + } else { + optsCopy.with[i] = ''; + } + }); + fn.call(thisArg, def, optsCopy); + }, + + + /** + * Find the index of a relation in the given list + * + * @method utils._getIndex + * @param {string[]} list List to search. + * @param {string} relation Relation to find. + * @private + * @returns {number} + */ + _getIndex: function _getIndex(list, relation) { + var index = -1; + list.forEach(function (_relation, i) { + if (_relation === relation) { + index = i; + return false; + } else if (utils.isObject(_relation)) { + if (_relation.relation === relation) { + index = i; + return false; + } + } + }); + return index; + }, + + + /** + * Define hidden (non-enumerable), writable properties on `target` from the + * provided `props`. + * + * @example + * import { utils } from 'js-data'; + * function Cat () {} + * utils.addHiddenPropsToTarget(Cat.prototype, { + * say () { + * console.log('meow'); + * } + * }); + * const cat = new Cat(); + * cat.say(); // "meow" + * + * @method utils.addHiddenPropsToTarget + * @param {object} target That to which `props` should be added. + * @param {object} props Properties to be added to `target`. + * @since 3.0.0 + */ + addHiddenPropsToTarget: function addHiddenPropsToTarget(target, props) { + var map = {}; + Object.keys(props).forEach(function (propName) { + var descriptor = Object.getOwnPropertyDescriptor(props, propName); + + descriptor.enumerable = false; + map[propName] = descriptor; + }); + Object.defineProperties(target, map); + }, + + + /** + * Return whether the two objects are deeply different. + * + * @example + * import { utils } from 'js-data'; + * utils.areDifferent({}, {}); // false + * utils.areDifferent({ a: 1 }, { a: 1 }); // false + * utils.areDifferent({ foo: 'bar' }, {}); // true + * + * @method utils.areDifferent + * @param {object} a Base object. + * @param {object} b Comparison object. + * @param {object} [opts] Configuration options. + * @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function. + * @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore. + * @returns {boolean} Whether the two objects are deeply different. + * @see utils.diffObjects + * @since 3.0.0 + */ + areDifferent: function areDifferent(newObject, oldObject, opts) { + opts || (opts = {}); + var diff = utils.diffObjects(newObject, oldObject, opts); + var diffCount = Object.keys(diff.added).length + Object.keys(diff.removed).length + Object.keys(diff.changed).length; + return diffCount > 0; + }, + + + /** + * Verified that the given constructor is being invoked via `new`, as opposed + * to just being called like a normal function. + * + * @example + * import { utils } from 'js-data'; + * function Cat () { + * utils.classCallCheck(this, Cat); + * } + * const cat = new Cat(); // this is ok + * Cat(); // this throws an error + * + * @method utils.classCallCheck + * @param {*} instance Instance that is being constructed. + * @param {Constructor} ctor Constructor function used to construct the + * instance. + * @since 3.0.0 + * @throws {Error} Throws an error if the constructor is being improperly + * invoked. + */ + classCallCheck: function classCallCheck$$1(instance, ctor) { + if (!(instance instanceof ctor)) { + throw utils.err('' + ctor.name)(500, 'Cannot call a class as a function'); + } + }, + + + /** + * Deep copy a value. + * + * @example + * import { utils } from 'js-data'; + * const a = { foo: { bar: 'baz' } }; + * const b = utils.copy(a); + * a === b; // false + * utils.areDifferent(a, b); // false + * + * @param {*} from Value to deep copy. + * @param {*} [to] Destination object for the copy operation. + * @param {*} [stackFrom] For internal use. + * @param {*} [stackTo] For internal use. + * @param {string[]|RegExp[]} [blacklist] List of strings or RegExp of + * properties to skip. + * @param {boolean} [plain] Whether to make a plain copy (don't try to use + * original prototype). + * @returns {*} Deep copy of `from`. + * @since 3.0.0 + */ + copy: function copy(from, to, stackFrom, stackTo, blacklist, plain) { + if (!to) { + to = from; + if (from) { + if (utils.isArray(from)) { + to = utils.copy(from, [], stackFrom, stackTo, blacklist, plain); + } else if (utils.isDate(from)) { + to = new Date(from.getTime()); + } else if (utils.isRegExp(from)) { + to = new RegExp(from.source, from.toString().match(/[^/]*$/)[0]); + to.lastIndex = from.lastIndex; + } else if (utils.isObject(from)) { + if (plain) { + to = utils.copy(from, {}, stackFrom, stackTo, blacklist, plain); + } else { + to = utils.copy(from, Object.create(Object.getPrototypeOf(from)), stackFrom, stackTo, blacklist, plain); + } + } + } + } else { + if (from === to) { + throw utils.err(DOMAIN + '.copy')(500, 'Cannot copy! Source and destination are identical.'); + } + + stackFrom = stackFrom || []; + stackTo = stackTo || []; + + if (utils.isObject(from)) { + var index = stackFrom.indexOf(from); + if (index !== -1) { + return stackTo[index]; + } + + stackFrom.push(from); + stackTo.push(to); + } + + var result = void 0; + if (utils.isArray(from)) { + var i = void 0; + to.length = 0; + for (i = 0; i < from.length; i++) { + result = utils.copy(from[i], null, stackFrom, stackTo, blacklist, plain); + if (utils.isObject(from[i])) { + stackFrom.push(from[i]); + stackTo.push(result); + } + to.push(result); + } + } else { + if (utils.isArray(to)) { + to.length = 0; + } else { + utils.forOwn(to, function (value, key) { + delete to[key]; + }); + } + for (var key in from) { + if (from.hasOwnProperty(key)) { + if (utils.isBlacklisted(key, blacklist)) { + continue; + } + result = utils.copy(from[key], null, stackFrom, stackTo, blacklist, plain); + if (utils.isObject(from[key])) { + stackFrom.push(from[key]); + stackTo.push(result); + } + to[key] = result; + } + } + } + } + return to; + }, + + + /** + * Recursively shallow fill in own enumerable properties from `source` to + * `dest`. + * + * @example + * import { utils } from 'js-data'; + * const a = { foo: { bar: 'baz' }, beep: 'boop' }; + * const b = { beep: 'bip' }; + * utils.deepFillIn(b, a); + * console.log(b); // {"foo":{"bar":"baz"},"beep":"bip"} + * + * @method utils.deepFillIn + * @param {object} dest The destination object. + * @param {object} source The source object. + * @see utils.fillIn + * @see utils.deepMixIn + * @since 3.0.0 + */ + deepFillIn: function deepFillIn(dest, source) { + if (source) { + utils.forOwn(source, function (value, key) { + var existing = dest[key]; + if (isPlainObject(value) && isPlainObject(existing)) { + utils.deepFillIn(existing, value); + } else if (!dest.hasOwnProperty(key) || dest[key] === undefined) { + dest[key] = value; + } + }); + } + return dest; + }, + + + /** + * Recursively shallow copy enumerable properties from `source` to `dest`. + * + * @example + * import { utils } from 'js-data'; + * const a = { foo: { bar: 'baz' }, beep: 'boop' }; + * const b = { beep: 'bip' }; + * utils.deepFillIn(b, a); + * console.log(b); // {"foo":{"bar":"baz"},"beep":"boop"} + * + * @method utils.deepMixIn + * @param {object} dest The destination object. + * @param {object} source The source object. + * @see utils.fillIn + * @see utils.deepFillIn + * @since 3.0.0 + */ + deepMixIn: function deepMixIn(dest, source) { + if (source) { + for (var key in source) { + var value = source[key]; + var existing = dest[key]; + if (isPlainObject(value) && isPlainObject(existing)) { + utils.deepMixIn(existing, value); + } else { + dest[key] = value; + } + } + } + return dest; + }, + + + /** + * Return a diff of the base object to the comparison object. + * + * @example + * import { utils } from 'js-data'; + * const oldObject = { foo: 'bar', a: 1234 }; + * const newObject = { beep: 'boop', a: 5678 }; + * const diff = utils.diffObjects(oldObject, newObject); + * console.log(diff.added); // {"beep":"boop"} + * console.log(diff.changed); // {"a":5678} + * console.log(diff.removed); // {"foo":undefined} + * + * @method utils.diffObjects + * @param {object} newObject Comparison object. + * @param {object} oldObject Base object. + * @param {object} [opts] Configuration options. + * @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function. + * @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore. + * @returns {Object} The diff from the base object to the comparison object. + * @see utils.areDifferent + * @since 3.0.0 + */ + diffObjects: function diffObjects(newObject, oldObject, opts) { + opts || (opts = {}); + var equalsFn = opts.equalsFn; + var blacklist = opts.ignore; + var diff = { + added: {}, + changed: {}, + removed: {} + }; + if (!utils.isFunction(equalsFn)) { + equalsFn = utils.deepEqual; + } + + var newKeys = Object.keys(newObject).filter(function (key) { + return !utils.isBlacklisted(key, blacklist); + }); + var oldKeys = Object.keys(oldObject).filter(function (key) { + return !utils.isBlacklisted(key, blacklist); + }); + + // Check for properties that were added or changed + newKeys.forEach(function (key) { + var oldValue = oldObject[key]; + var newValue = newObject[key]; + if (equalsFn(oldValue, newValue)) { + return; + } + if (oldValue === undefined) { + diff.added[key] = newValue; + } else { + diff.changed[key] = newValue; + } + }); + + // Check for properties that were removed + oldKeys.forEach(function (key) { + var oldValue = oldObject[key]; + var newValue = newObject[key]; + if (newValue === undefined && oldValue !== undefined) { + diff.removed[key] = undefined; + } + }); + + return diff; + }, + + + /** + * Return whether the two values are equal according to the `==` operator. + * + * @example + * import { utils } from 'js-data'; + * console.log(utils.equal(1,1)); // true + * console.log(utils.equal(1,'1')); // true + * console.log(utils.equal(93, 66)); // false + * + * @method utils.equal + * @param {*} a First value in the comparison. + * @param {*} b Second value in the comparison. + * @returns {boolean} Whether the two values are equal according to `==`. + * @since 3.0.0 + */ + equal: function equal(a, b) { + return a == b; // eslint-disable-line + }, + + + /** + * Produce a factory function for making Error objects with the provided + * metadata. Used throughout the various js-data components. + * + * @example + * import { utils } from 'js-data'; + * const errorFactory = utils.err('domain', 'target'); + * const error400 = errorFactory(400, 'expected type', 'actual type'); + * console.log(error400); // [Error: [domain:target] expected: expected type, found: string + http://www.js-data.io/v3.0/docs/errors#400] + * @method utils.err + * @param {string} domain Namespace. + * @param {string} target Target. + * @returns {Function} Factory function. + * @since 3.0.0 + */ + err: function err(domain, target) { + return function (code) { + var prefix = '[' + domain + ':' + target + '] '; + var message = ERRORS[code].apply(null, Array.prototype.slice.call(arguments, 1)); + message = '' + prefix + message + '\nhttp://www.js-data.io/v3.0/docs/errors#' + code; + return new Error(message); + }; + }, + + + /** + * Add eventing capabilities into the target object. + * + * @example + * import { utils } from 'js-data'; + * const user = { name: 'John' }; + * utils.eventify(user); + * user.on('foo', () => console.log(arguments)); + * user.emit('foo', 1, 'bar'); // should log to console values (1, "bar") + * + * @method utils.eventify + * @param {object} target Target object. + * @param {Function} [getter] Custom getter for retrieving the object's event + * listeners. + * @param {Function} [setter] Custom setter for setting the object's event + * listeners. + * @since 3.0.0 + */ + eventify: function eventify(target, getter, setter) { + target = target || this; + var _events = {}; + if (!getter && !setter) { + getter = function getter() { + return _events; + }; + setter = function setter(value) { + _events = value; + }; + } + Object.defineProperties(target, { + emit: { + value: function value() { + var events = getter.call(this) || {}; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var type = args.shift(); + var listeners = events[type] || []; + var i = void 0; + for (i = 0; i < listeners.length; i++) { + listeners[i].f.apply(listeners[i].c, args); + } + listeners = events.all || []; + args.unshift(type); + for (i = 0; i < listeners.length; i++) { + listeners[i].f.apply(listeners[i].c, args); + } + } + }, + off: { + value: function value(type, func) { + var events = getter.call(this); + var listeners = events[type]; + if (!listeners) { + setter.call(this, {}); + } else if (func) { + for (var i = 0; i < listeners.length; i++) { + if (listeners[i].f === func) { + listeners.splice(i, 1); + break; + } + } + } else { + listeners.splice(0, listeners.length); + } + } + }, + on: { + value: function value(type, func, thisArg) { + if (!getter.call(this)) { + setter.call(this, {}); + } + var events = getter.call(this); + events[type] = events[type] || []; + events[type].push({ + c: thisArg, + f: func + }); + } + } + }); + }, + + + /** + * Used for sublcassing. Invoke this method in the context of a superclass to + * to produce a subclass based on `props` and `classProps`. + * + * @example + * import { utils } from 'js-data'; + * function Animal () {} + * Animal.extend = utils.extend; + * const Cat = Animal.extend({ + * say () { + * console.log('meow'); + * } + * }); + * const cat = new Cat(); + * cat instanceof Animal; // true + * cat instanceof Cat; // true + * cat.say(); // "meow" + * + * @method utils.extend + * @param {object} props Instance properties for the subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to use as the subclass. + * @param {object} props Static properties for the subclass. + * @returns {Constructor} A new subclass. + * @since 3.0.0 + */ + extend: function extend(props, classProps) { + var superClass = this; + var _subClass = void 0; + + props || (props = {}); + classProps || (classProps = {}); + + if (props.hasOwnProperty('constructor')) { + _subClass = props.constructor; + delete props.constructor; + } else { + _subClass = function subClass() { + utils.classCallCheck(this, _subClass); + + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + superClass.apply(this, args); + }; + } + + // Setup inheritance of instance members + _subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + configurable: true, + enumerable: false, + value: _subClass, + writable: true + } + }); + + var obj = Object; + // Setup inheritance of static members + if (obj.setPrototypeOf) { + obj.setPrototypeOf(_subClass, superClass); + } else if (classProps.strictEs6Class) { + _subClass.__proto__ = superClass; // eslint-disable-line + } else { + utils.forOwn(superClass, function (value, key) { + _subClass[key] = value; + }); + } + if (!_subClass.hasOwnProperty('__super__')) { + Object.defineProperty(_subClass, '__super__', { + configurable: true, + value: superClass + }); + } + + utils.addHiddenPropsToTarget(_subClass.prototype, props); + utils.fillIn(_subClass, classProps); + + return _subClass; + }, + + + /** + * Shallow copy own enumerable properties from `src` to `dest` that are on + * `src` but are missing from `dest. + * + * @example + * import { utils } from 'js-data'; + * const a = { foo: 'bar', beep: 'boop' }; + * const b = { beep: 'bip' }; + * utils.fillIn(b, a); + * console.log(b); // {"foo":"bar","beep":"bip"} + * + * @method utils.fillIn + * @param {object} dest The destination object. + * @param {object} source The source object. + * @see utils.deepFillIn + * @see utils.deepMixIn + * @since 3.0.0 + */ + fillIn: function fillIn(dest, src) { + utils.forOwn(src, function (value, key) { + if (!dest.hasOwnProperty(key) || dest[key] === undefined) { + dest[key] = value; + } + }); + }, + + + /** + * Find the last index of an item in an array according to the given checker function. + * + * @example + * import { utils } from 'js-data'; + * + * const john = { name: 'John', age: 20 }; + * const sara = { name: 'Sara', age: 25 }; + * const dan = { name: 'Dan', age: 20 }; + * const users = [john, sara, dan]; + * + * console.log(utils.findIndex(users, (user) => user.age === 25)); // 1 + * console.log(utils.findIndex(users, (user) => user.age > 19)); // 2 + * console.log(utils.findIndex(users, (user) => user.name === 'John')); // 0 + * console.log(utils.findIndex(users, (user) => user.name === 'Jimmy')); // -1 + * + * @method utils.findIndex + * @param {array} array The array to search. + * @param {Function} fn Checker function. + * @returns {number} Index if found or -1 if not found. + * @since 3.0.0 + */ + findIndex: function findIndex(array, fn) { + var index = -1; + if (!array) { + return index; + } + array.forEach(function (record, i) { + if (fn(record)) { + index = i; + return false; + } + }); + return index; + }, + + + /** + * Recursively iterate over a {@link Mapper}'s relations according to + * `opts.with`. + * + * @method utils.forEachRelation + * @param {Mapper} mapper Mapper. + * @param {object} opts Configuration options. + * @param {Function} fn Callback function. + * @param {*} thisArg Execution context for the callback function. + * @since 3.0.0 + */ + forEachRelation: function forEachRelation(mapper, opts, fn, thisArg) { + var relationList = mapper.relationList || []; + if (!relationList.length) { + return; + } + relationList.forEach(function (def) { + utils._forRelation(opts, def, fn, thisArg); + }); + }, + + + /** + * Iterate over an object's own enumerable properties. + * + * @example + * import { utils } from 'js-data'; + * const a = { b: 1, c: 4 }; + * let sum = 0; + * utils.forOwn(a, function (value, key) { + * sum += value; + * }); + * console.log(sum); // 5 + * + * @method utils.forOwn + * @param {object} object The object whose properties are to be enumerated. + * @param {Function} fn Iteration function. + * @param {object} [thisArg] Content to which to bind `fn`. + * @since 3.0.0 + */ + forOwn: function forOwn(obj, fn, thisArg) { + var keys = Object.keys(obj); + var len = keys.length; + var i = void 0; + for (i = 0; i < len; i++) { + if (fn.call(thisArg, obj[keys[i]], keys[i], obj) === false) { + break; + } + } + }, + + + /** + * Proxy for `JSON.parse`. + * + * @example + * import { utils } from 'js-data'; + * + * const a = utils.fromJson('{"name" : "John"}'); + * console.log(a); // { name: 'John' } + * + * @method utils.fromJson + * @param {string} json JSON to parse. + * @returns {Object} Parsed object. + * @see utils.toJson + * @since 3.0.0 + */ + fromJson: function fromJson(json) { + return utils.isString(json) ? JSON.parse(json) : json; + }, + + + /** + * Retrieve the specified property from the given object. Supports retrieving + * nested properties. + * + * @example + * import { utils } from 'js-data'; + * const a = { foo: { bar: 'baz' }, beep: 'boop' }; + * console.log(utils.get(a, 'beep')); // "boop" + * console.log(utils.get(a, 'foo.bar')); // "baz" + * + * @method utils.get + * @param {object} object Object from which to retrieve a property's value. + * @param {string} prop Property to retrieve. + * @returns {*} Value of the specified property. + * @see utils.set + * @since 3.0.0 + */ + 'get': function get$$1(object, prop) { + if (!prop) { + return; + } + var parts = prop.split('.'); + var last = parts.pop(); + + while (prop = parts.shift()) { + // eslint-disable-line + object = object[prop]; + if (object == null) { + // eslint-disable-line + return; + } + } + + return object[last]; + }, + + /** + * Return the superclass for the given instance or subclass. If an instance is + * provided, then finds the parent class of the instance's constructor. + * + * @example + * import { utils } from 'js-data'; + * // using ES2015 classes + * class Foo {} + * class Bar extends Foo {} + * const barInstance = new Bar(); + * let baseType = utils.getSuper(barInstance); + * console.log(Foo === baseType); // true + * + * // using Function constructor with utils.extend + * function Foo () {} + * Foo.extend = utils.extend; + * const Bar = Foo.extend(); + * const barInstance = new Bar(); + * let baseType = utils.getSuper(barInstance); + * console.log(Foo === baseType); // true + * + * @method utils.getSuper + * @param {Object|Function} instance Instance or constructor. + * @param {boolean} [isCtor=false] Whether `instance` is a constructor. + * @returns {Constructor} The superclass (grandparent constructor). + * @since 3.0.0 + */ + getSuper: function getSuper(instance, isCtor) { + var ctor = isCtor ? instance : instance.constructor; + if (ctor.hasOwnProperty('__super__')) { + return ctor.__super__; + } + return Object.getPrototypeOf(ctor) || ctor.__proto__; // eslint-disable-line + }, + + + /** + * Return the intersection of two arrays. + * + * @example + * import { utils } from 'js-data'; + * const arrA = ['green', 'red', 'blue', 'red']; + * const arrB = ['green', 'yellow', 'red']; + * const intersected = utils.intersection(arrA, arrB); + * + * console.log(intersected); // ['green', 'red']) + * + * @method utils.intersection + * @param {array} array1 First array. + * @param {array} array2 Second array. + * @returns {Array} Array of elements common to both arrays. + * @since 3.0.0 + */ + intersection: function intersection(array1, array2) { + if (!array1 || !array2) { + return []; + } + var result = []; + var item = void 0; + var i = void 0; + var len = array1.length; + for (i = 0; i < len; i++) { + item = array1[i]; + if (result.indexOf(item) !== -1) { + continue; + } + if (array2.indexOf(item) !== -1) { + result.push(item); + } + } + return result; + }, + + + /** + * Proxy for `Array.isArray`. + * + * @example + * import { utils } from 'js-data'; + * const a = [1,2,3,4,5]; + * const b = { foo: "bar" }; + * console.log(utils.isArray(a)); // true + * console.log(utils.isArray(b)); // false + * + * @method utils.isArray + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is an array. + * @since 3.0.0 + */ + isArray: Array.isArray, + + /** + * Return whether `prop` is matched by any string or regular expression in + * `blacklist`. + * + * @example + * import { utils } from 'js-data'; + * const blacklist = [/^\$hashKey/g, /^_/g, 'id']; + * console.log(utils.isBlacklisted("$hashKey", blacklist)); // true + * console.log(utils.isBlacklisted("id", blacklist)); // true + * console.log(utils.isBlacklisted("_myProp", blacklist)); // true + * console.log(utils.isBlacklisted("my_id", blacklist)); // false + * + * @method utils.isBlacklisted + * @param {string} prop The name of a property to check. + * @param {array} blacklist Array of strings and regular expressions. + * @returns {boolean} Whether `prop` was matched. + * @since 3.0.0 + */ + isBlacklisted: function isBlacklisted(prop, blacklist) { + if (!blacklist || !blacklist.length) { + return false; + } + var matches = void 0; + for (var i = 0; i < blacklist.length; i++) { + if (toStr(blacklist[i]) === REGEXP_TAG && blacklist[i].test(prop) || blacklist[i] === prop) { + matches = prop; + return !!matches; + } + } + return !!matches; + }, + + + /** + * Return whether the provided value is a boolean. + * + * @example + * import { utils } from 'js-data'; + * const a = true; + * const b = { foo: "bar" }; + * console.log(utils.isBoolean(a)); // true + * console.log(utils.isBoolean(b)); // false + * + * @method utils.isBoolean + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is a boolean. + * @since 3.0.0 + */ + isBoolean: function isBoolean(value) { + return toStr(value) === BOOL_TAG; + }, + + + /** + * Return whether the provided value is a date. + * + * @example + * import { utils } from 'js-data'; + * const a = new Date(); + * const b = { foo: "bar" }; + * console.log(utils.isDate(a)); // true + * console.log(utils.isDate(b)); // false + * + * @method utils.isDate + * @param {*} value The value to test. + * @returns {Date} Whether the provided value is a date. + * @since 3.0.0 + */ + isDate: function isDate(value) { + return value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && toStr(value) === DATE_TAG; + }, + + + /** + * Return whether the provided value is a function. + * + * @example + * import { utils } from 'js-data'; + * const a = function () { console.log('foo bar'); }; + * const b = { foo: "bar" }; + * console.log(utils.isFunction(a)); // true + * console.log(utils.isFunction(b)); // false + * + * @method utils.isFunction + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is a function. + * @since 3.0.0 + */ + isFunction: function isFunction(value) { + return typeof value === 'function' || value && toStr(value) === FUNC_TAG; + }, + + + /** + * Return whether the provided value is an integer. + * + * @example + * import { utils } from 'js-data'; + * const a = 1; + * const b = 1.25; + * const c = '1'; + * console.log(utils.isInteger(a)); // true + * console.log(utils.isInteger(b)); // false + * console.log(utils.isInteger(c)); // false + * + * @method utils.isInteger + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is an integer. + * @since 3.0.0 + */ + isInteger: function isInteger(value) { + return toStr(value) === NUMBER_TAG && value == toInteger(value); // eslint-disable-line + }, + + + /** + * Return whether the provided value is `null`. + * + * @example + * import { utils } from 'js-data'; + * const a = null; + * const b = { foo: "bar" }; + * console.log(utils.isNull(a)); // true + * console.log(utils.isNull(b)); // false + * + * @method utils.isNull + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is `null`. + * @since 3.0.0 + */ + isNull: function isNull(value) { + return value === null; + }, + + + /** + * Return whether the provided value is a number. + * + * @example + * import { utils } from 'js-data'; + * const a = 1; + * const b = -1.25; + * const c = '1'; + * console.log(utils.isNumber(a)); // true + * console.log(utils.isNumber(b)); // true + * console.log(utils.isNumber(c)); // false + * + * @method utils.isNumber + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is a number. + * @since 3.0.0 + */ + isNumber: function isNumber(value) { + var type = typeof value === 'undefined' ? 'undefined' : _typeof(value); + return type === 'number' || value && type === 'object' && toStr(value) === NUMBER_TAG; + }, + + + /** + * Return whether the provided value is an object. + * + * @example + * import { utils } from 'js-data'; + * const a = { foo: "bar" }; + * const b = 'foo bar'; + * console.log(utils.isObject(a)); // true + * console.log(utils.isObject(b)); // false + * + * @method utils.isObject + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is an object. + * @since 3.0.0 + */ + isObject: function isObject(value) { + return toStr(value) === OBJECT_TAG; + }, + + + /** + * Return whether the provided value is a regular expression. + * + * @example + * import { utils } from 'js-data'; + * const a = /^\$.+$/ig; + * const b = new RegExp('^\$.+$', 'ig'); + * const c = { foo: "bar" }; + * console.log(utils.isRegExp(a)); // true + * console.log(utils.isRegExp(b)); // true + * console.log(utils.isRegExp(c)); // false + * + * @method utils.isRegExp + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is a regular expression. + * @since 3.0.0 + */ + isRegExp: function isRegExp(value) { + return toStr(value) === REGEXP_TAG; + }, + + + /** + * Return whether the provided value is a string or a number. + * + * @example + * import { utils } from 'js-data'; + * console.log(utils.isSorN('')); // true + * console.log(utils.isSorN(-1.65)); // true + * console.log(utils.isSorN('my string')); // true + * console.log(utils.isSorN({})); // false + * console.log(utils.isSorN([1,2,4])); // false + * + * @method utils.isSorN + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is a string or a number. + * @since 3.0.0 + */ + isSorN: function isSorN(value) { + return utils.isString(value) || utils.isNumber(value); + }, + + + /** + * Return whether the provided value is a string. + * + * @example + * import { utils } from 'js-data'; + * console.log(utils.isString('')); // true + * console.log(utils.isString('my string')); // true + * console.log(utils.isString(100)); // false + * console.log(utils.isString([1,2,4])); // false + * + * @method utils.isString + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is a string. + * @since 3.0.0 + */ + isString: function isString(value) { + return typeof value === 'string' || value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && toStr(value) === STRING_TAG; + }, + + + /** + * Return whether the provided value is a `undefined`. + * + * @example + * import { utils } from 'js-data'; + * const a = undefined; + * const b = { foo: "bar"}; + * console.log(utils.isUndefined(a)); // true + * console.log(utils.isUndefined(b.baz)); // true + * console.log(utils.isUndefined(b)); // false + * console.log(utils.isUndefined(b.foo)); // false + * + * @method utils.isUndefined + * @param {*} value The value to test. + * @returns {boolean} Whether the provided value is a `undefined`. + * @since 3.0.0 + */ + isUndefined: function isUndefined(value) { + return value === undefined; + }, + + + /** + * Mix in logging capabilities to the target. + * + * @example + * import { utils } from 'js-data'; + * const a = { foo: "bar"}; + * + * // Add standard logging to an object + * utils.logify(a); + * a.log('info', 'test log info'); // output 'test log info' to console. + * + * // Toggle debug output of an object + * a.dbg('test debug output'); // does not output because debug is off. + * a.debug = true; + * a.dbg('test debug output'); // output 'test debug output' to console. + * + * @method utils.logify + * @param {*} target The target. + * @since 3.0.0 + */ + logify: function logify(target) { + utils.addHiddenPropsToTarget(target, { + dbg: function dbg() { + if (utils.isFunction(this.log)) { + for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + this.log.apply(this, ['debug'].concat(args)); + } + }, + log: function log(level) { + for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + + if (level && !args.length) { + args.push(level); + level = 'debug'; + } + if (level === 'debug' && !this.debug) { + return; + } + var prefix = level.toUpperCase() + ': (' + (this.name || this.constructor.name) + ')'; + if (utils.isFunction(console[level])) { + var _console; + + (_console = console)[level].apply(_console, [prefix].concat(args)); + } else { + var _console2; + + (_console2 = console).log.apply(_console2, [prefix].concat(args)); + } + } + }); + }, + + + /** + * Adds the given record to the provided array only if it's not already in the + * array. + * + * @example + * import { utils } from 'js-data'; + * const colors = ['red', 'green', 'yellow']; + * + * console.log(colors.length); // 3 + * utils.noDupeAdd(colors, 'red'); + * console.log(colors.length); // 3, red already exists + * + * utils.noDupeAdd(colors, 'blue'); + * console.log(colors.length); // 4, blue was added + * + * @method utils.noDupeAdd + * @param {array} array The array. + * @param {*} record The value to add. + * @param {Function} fn Callback function passed to {@link utils.findIndex}. + * @since 3.0.0 + */ + noDupeAdd: function noDupeAdd(array, record, fn) { + if (!array) { + return; + } + var index = this.findIndex(array, fn); + if (index < 0) { + array.push(record); + } + }, + + + /** + * Return a shallow copy of the provided object, minus the properties + * specified in `keys`. + * + * @example + * import { utils } from 'js-data'; + * const a = { name: 'John', $hashKey: 1214910 }; + * + * let b = utils.omit(a, ['$hashKey']); + * console.log(b); // { name: 'John' } + * + * @method utils.omit + * @param {object} props The object to copy. + * @param {string[]} keys Array of strings, representing properties to skip. + * @returns {Object} Shallow copy of `props`, minus `keys`. + * @since 3.0.0 + */ + omit: function omit(props, keys) { + var _props = {}; + utils.forOwn(props, function (value, key) { + if (keys.indexOf(key) === -1) { + _props[key] = value; + } + }); + return _props; + }, + + + /** + * Return a shallow copy of the provided object, but only include the + * properties specified in `keys`. + * + * @example + * import { utils } from 'js-data'; + * const a = { name: 'John', $hashKey: 1214910 }; + * + * let b = utils.pick(a, ['$hashKey']); + * console.log(b); // { $hashKey: 1214910 } + * + * @method utils.pick + * @param {object} props The object to copy. + * @param {string[]} keys Array of strings, representing properties to keep. + * @returns {Object} Shallow copy of `props`, but only including `keys`. + * @since 3.0.0 + */ + pick: function pick(props, keys) { + return keys.reduce(function (map, key) { + map[key] = props[key]; + return map; + }, {}); + }, + + + /** + * Return a plain copy of the given value. + * + * @example + * import { utils } from 'js-data'; + * const a = { name: 'John' }; + * let b = utils.plainCopy(a); + * console.log(a === b); // false + * + * @method utils.plainCopy + * @param {*} value The value to copy. + * @returns {*} Plain copy of `value`. + * @see utils.copy + * @since 3.0.0 + */ + plainCopy: function plainCopy(value) { + return utils.copy(value, undefined, undefined, undefined, undefined, true); + }, + + + /** + * Shortcut for `utils.Promise.reject(value)`. + * + * @example + * import { utils } from 'js-data'; + * + * utils.reject("Testing static reject").then(function (data) { + * // not called + * }).catch(function (reason) { + * console.log(reason); // "Testing static reject" + * }); + * + * @method utils.reject + * @param {*} [value] Value with which to reject the Promise. + * @returns {Promise} Promise reject with `value`. + * @see utils.Promise + * @since 3.0.0 + */ + reject: function reject(value) { + return utils.Promise.reject(value); + }, + + + /** + * Remove the last item found in array according to the given checker function. + * + * @example + * import { utils } from 'js-data'; + * + * const colors = ['red', 'green', 'yellow', 'red']; + * utils.remove(colors, (color) => color === 'red'); + * console.log(colors); // ['red', 'green', 'yellow'] + * + * @method utils.remove + * @param {array} array The array to search. + * @param {Function} fn Checker function. + */ + remove: function remove(array, fn) { + if (!array || !array.length) { + return; + } + var index = this.findIndex(array, fn); + if (index >= 0) { + array.splice(index, 1); // todo should this be recursive? + } + }, + + + /** + * Shortcut for `utils.Promise.resolve(value)`. + * + * @example + * import { utils } from 'js-data'; + * + * utils.resolve("Testing static resolve").then(function (data) { + * console.log(data); // "Testing static resolve" + * }).catch(function (reason) { + * // not called + * }); + * + * @param {*} [value] Value with which to resolve the Promise. + * @returns {Promise} Promise resolved with `value`. + * @see utils.Promise + * @since 3.0.0 + */ + resolve: function resolve(value) { + return utils.Promise.resolve(value); + }, + + + /** + * Set the value at the provided key or path. + * + * @example + * import { utils } from 'js-data'; + * + * const john = { + * name: 'John', + * age: 25, + * parent: { + * name: 'John's Mom', + * age: 50 + * } + * }; + * // set value by key + * utils.set(john, 'id', 98); + * console.log(john.id); // 98 + * + * // set value by path + * utils.set(john, 'parent.id', 20); + * console.log(john.parent.id); // 20 + * + * // set value by path/value map + * utils.set(john, { + * 'id': 1098, + * 'parent': { id: 1020 }, + * 'parent.age': '55' + * }); + * console.log(john.id); // 1098 + * console.log(john.parent.id); // 1020 + * console.log(john.parent.age); // 55 + * + * @method utils.set + * @param {object} object The object on which to set a property. + * @param {(string|Object)} path The key or path to the property. Can also + * pass in an object of path/value pairs, which will all be set on the target + * object. + * @param {*} [value] The value to set. + */ + set: function set$$1(object, path, value) { + if (utils.isObject(path)) { + utils.forOwn(path, function (value, _path) { + utils.set(object, _path, value); + }); + } else { + var parts = PATH.exec(path); + if (parts) { + mkdirP(object, parts[1])[parts[2]] = value; + } else { + object[path] = value; + } + } + }, + + /** + * Check whether the two provided objects are deeply equal. + * + * @example + * import { utils } from 'js-data'; + * + * const objA = { + * name: 'John', + * id: 27, + * nested: { + * item: 'item 1', + * colors: ['red', 'green', 'blue'] + * } + * }; + * + * const objB = { + * name: 'John', + * id: 27, + * nested: { + * item: 'item 1', + * colors: ['red', 'green', 'blue'] + * } + * }; + * + * console.log(utils.deepEqual(a,b)); // true + * objB.nested.colors.add('yellow'); // make a change to a nested object's array + * console.log(utils.deepEqual(a,b)); // false + * + * @method utils.deepEqual + * @param {object} a First object in the comparison. + * @param {object} b Second object in the comparison. + * @returns {boolean} Whether the two provided objects are deeply equal. + * @see utils.equal + * @since 3.0.0 + */ + deepEqual: function deepEqual(a, b) { + if (a === b) { + return true; + } + var _equal = true; + if (utils.isArray(a) && utils.isArray(b)) { + if (a.length !== b.length) { + return false; + } + for (var i = a.length; i--;) { + if (!utils.deepEqual(a[i], b[i])) { + // Exit loop early + return false; + } + } + } else if (utils.isObject(a) && utils.isObject(b)) { + utils.forOwn(a, function (value, key) { + if (!(_equal = utils.deepEqual(value, b[key]))) { + // Exit loop early + return false; + } + }); + if (_equal) { + utils.forOwn(b, function (value, key) { + if (!(_equal = utils.deepEqual(value, a[key]))) { + // Exit loop early + return false; + } + }); + } + } else { + return false; + } + return _equal; + }, + + + /** + * Proxy for `JSON.stringify`. + * + * @example + * import { utils } from 'js-data'; + * + * const a = { name: 'John' }; + * let jsonVal = utils.toJson(a); + * console.log(jsonVal); // '{"name" : "John"}' + * + * @method utils.toJson + * @param {*} value Value to serialize to JSON. + * @returns {string} JSON string. + * @see utils.fromJson + * @since 3.0.0 + */ + toJson: JSON.stringify, + + /** + * Unset the value at the provided key or path. + * + * @example + * import { utils } from 'js-data'; + * + * const john = { + * name: 'John', + * age: 25, + * parent: { + * name: 'John's Mom', + * age: 50 + * } + * }; + * + * utils.unset(john, age); + * utils.unset(john, parent.age); + * + * console.log(john.age); // null + * console.log(john.parent.age); // null + * + * @method utils.unset + * @param {object} object The object from which to delete the property. + * @param {string} path The key or path to the property. + * @see utils.set + * @since 3.0.0 + */ + unset: function unset(object, path) { + var parts = path.split('.'); + var last = parts.pop(); + + while (path = parts.shift()) { + // eslint-disable-line + object = object[path]; + if (object == null) { + // eslint-disable-line + return; + } + } + + object[last] = undefined; + } +}; + +var safeSetProp = function safeSetProp(record, field, value) { + if (record && record._set) { + record._set('props.' + field, value); + } else { + utils.set(record, field, value); + } +}; + +var safeSetLink = function safeSetLink(record, field, value) { + if (record && record._set) { + record._set('links.' + field, value); + } else { + utils.set(record, field, value); + } +}; + +/** + * A base class which gives instances private properties. + * + * Typically you won't instantiate this class directly, but you may find it + * useful as an abstract class for your own components. + * + * See {@link Settable.extend} for an example of using {@link Settable} as a + * base class. + * + *```javascript + * import {Settable} from 'js-data' + * ``` + * + * @class Settable + * @returns {Settable} A new {@link Settable} instance. + * @since 3.0.0 + */ +function Settable() { + var _props = {}; + Object.defineProperties(this, { + /** + * Get a private property of this instance. + * + * __Don't use the method unless you know what you're doing.__ + * + * @method Settable#_get + * @param {string} key The property to retrieve. + * @returns {*} The value of the property. + * @since 3.0.0 + */ + _get: { + value: function value(key) { + return utils.get(_props, key); + } + }, + + /** + * Set a private property of this instance. + * + * __Don't use the method unless you know what you're doing.__ + * + * @method __Don't use the method unless you know what you're doing.__#_set + * @param {(string|Object)} key The key or path to the property. Can also + * pass in an object of key/value pairs, which will all be set on the instance. + * @param {*} [value] The value to set. + * @since 3.0.0 + */ + _set: { + value: function value(key, _value) { + return utils.set(_props, key, _value); + } + }, + + /** + * Unset a private property of this instance. + * + * __Don't use the method unless you know what you're doing.__ + * + * @method __Don't use the method unless you know what you're doing.__#_unset + * @param {string} key The property to unset. + * @since 3.0.0 + */ + _unset: { + value: function value(key) { + return utils.unset(_props, key); + } + } + }); +} + +/** + * Create a subclass of this Settable: + * + * @example Settable.extend + * const JSData = require('js-data'); + * const { Settable } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomSettableClass extends Settable { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customSettable = new CustomSettableClass(); + * console.log(customSettable.foo()); + * console.log(CustomSettableClass.beep()); + * + * // Extend the class using alternate method. + * const OtherSettableClass = Settable.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherSettable = new OtherSettableClass(); + * console.log(otherSettable.foo()); + * console.log(OtherSettableClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherSettableClass () { + * Settable.call(this); + * this.created_at = new Date().getTime(); + * } + * Settable.extend({ + * constructor: AnotherSettableClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }) + * const anotherSettable = new AnotherSettableClass(); + * console.log(anotherSettable.created_at); + * console.log(anotherSettable.foo()); + * console.log(AnotherSettableClass.beep()); + * + * @method Settable.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this Settable class. + * @since 3.0.0 + */ +Settable.extend = utils.extend; + +/** + * The base class from which all JSData components inherit some basic + * functionality. + * + * Typically you won't instantiate this class directly, but you may find it + * useful as an abstract class for your own components. + * + * See {@link Component.extend} for an example of using {@link Component} as a + * base class. + * + *```javascript + * import {Component} from 'js-data' + * ``` + * + * @class Component + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.debug=false] See {@link Component#debug}. + * @returns {Component} A new {@link Component} instance. + * @since 3.0.0 + */ +function Component(opts) { + Settable.call(this); + opts || (opts = {}); + + /** + * Whether to enable debug-level logs for this component. Anything that + * extends `Component` inherits this option and the corresponding logging + * functionality. + * + * @example Component#debug + * const JSData = require('js-data'); + * const { Component } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const component = new Component(); + * component.log('debug', 'some message'); // nothing gets logged + * // Display debug logs: + * component.debug = true; + * component.log('debug', 'other message'); // this DOES get logged + * + * @default false + * @name Component#debug + * @since 3.0.0 + * @type {boolean} + */ + this.debug = opts.hasOwnProperty('debug') ? !!opts.debug : false; + + /** + * Event listeners attached to this Component. __Do not modify.__ Use + * {@link Component#on} and {@link Component#off} instead. + * + * @name Component#_listeners + * @private + * @instance + * @since 3.0.0 + * @type {Object} + */ + Object.defineProperty(this, '_listeners', { value: {}, writable: true }); +} + +var Component$1 = Settable.extend({ + constructor: Component +}); + +/** + * Create a subclass of this Component: + * + * @example Component.extend + * const JSData = require('js-data'); + * const { Component } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomComponentClass extends Component { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customComponent = new CustomComponentClass(); + * console.log(customComponent.foo()); + * console.log(CustomComponentClass.beep()); + * + * // Extend the class using alternate method. + * const OtherComponentClass = Component.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherComponent = new OtherComponentClass(); + * console.log(otherComponent.foo()); + * console.log(OtherComponentClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherComponentClass () { + * Component.call(this); + * this.created_at = new Date().getTime(); + * } + * Component.extend({ + * constructor: AnotherComponentClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }) + * const anotherComponent = new AnotherComponentClass(); + * console.log(anotherComponent.created_at); + * console.log(anotherComponent.foo()); + * console.log(AnotherComponentClass.beep()); + * + * @method Component.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this Component class. + * @since 3.0.0 + */ +Component.extend = utils.extend; + +/** + * Log the provided values at the "debug" level. Debug-level logs are only + * logged if {@link Component#debug} is `true`. + * + * `.dbg(...)` is shorthand for `.log('debug', ...)`. + * + * @method Component#dbg + * @param {...*} [args] Values to log. + * @since 3.0.0 + */ +/** + * Log the provided values. By default sends values to `console[level]`. + * Debug-level logs are only logged if {@link Component#debug} is `true`. + * + * Will attempt to use appropriate `console` methods if they are available. + * + * @method Component#log + * @param {string} level Log level. + * @param {...*} [args] Values to log. + * @since 3.0.0 + */ +utils.logify(Component.prototype); + +/** + * Register a new event listener on this Component. + * + * @example + * // Listen for all "afterCreate" events in a DataStore + * store.on('afterCreate', (mapperName, props, opts, result) => { + * console.log(mapperName); // "post" + * console.log(props.id); // undefined + * console.log(result.id); // 1234 + * }); + * store.create('post', { title: 'Modeling your data' }).then((post) => { + * console.log(post.id); // 1234 + * }); + * + * @example + * // Listen for the "add" event on a collection + * collection.on('add', (records) => { + * console.log(records); // [...] + * }); + * + * @example + * // Listen for "change" events on a record + * post.on('change', (record, changes) => { + * console.log(changes); // { changed: { title: 'Modeling your data' } } + * }); + * post.title = 'Modeling your data'; + * + * @method Component#on + * @param {string} event Name of event to subsribe to. + * @param {Function} listener Listener function to handle the event. + * @param {*} [ctx] Optional content in which to invoke the listener. + * @since 3.0.0 + */ +/** + * Remove an event listener from this Component. If no listener is provided, + * then all listeners for the specified event will be removed. If no event is + * specified then all listeners for all events will be removed. + * + * @example + * // Remove a particular listener for a particular event + * collection.off('add', handler); + * + * @example + * // Remove all listeners for a particular event + * record.off('change'); + * + * @example + * // Remove all listeners to all events + * store.off(); + * + * @method Component#off + * @param {string} [event] Name of event to unsubsribe to. + * @param {Function} [listener] Listener to remove. + * @since 3.0.0 + */ +/** + * Trigger an event on this Component. + * + * @example Component#emit + * // import { Collection, DataStore } from 'js-data'; + * const JSData = require('js-data'); + * const { Collection, DataStore } = JSData; + * + * const collection = new Collection(); + * collection.on('foo', function (msg) { + * console.log(msg); + * }); + * collection.emit('foo', 'bar'); + * + * const store = new DataStore(); + * store.on('beep', function (msg) { + * console.log(msg); + * }); + * store.emit('beep', 'boop'); + * + * @method Component#emit + * @param {string} event Name of event to emit. + * @param {...*} [args] Arguments to pass to any listeners. + * @since 3.0.0 + */ +utils.eventify(Component.prototype, function () { + return this._listeners; +}, function (value) { + this._listeners = value; +}); + +var DOMAIN$2 = 'Query'; +var INDEX_ERR = 'Index inaccessible after first operation'; + +// Reserved words used by JSData's Query Syntax +var reserved = { + limit: '', + offset: '', + orderBy: '', + skip: '', + sort: '', + where: '' + + // Used by our JavaScript implementation of the LIKE operator +};var escapeRegExp = /([.*+?^=!:${}()|[\]/\\])/g; +var percentRegExp = /%/g; +var underscoreRegExp = /_/g; +var escape = function escape(pattern) { + return pattern.replace(escapeRegExp, '\\$1'); +}; + +/** + * A class used by the {@link Collection} class to build queries to be executed + * against the collection's data. An instance of `Query` is returned by + * {@link Collection#query}. Query instances are typically short-lived, and you + * shouldn't have to create them yourself. Just use {@link Collection#query}. + * + * ```javascript + * import { Query } from 'js-data'; + * ``` + * + * @example Query intro + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'draft', id: 2 }, + * { author: 'Mike', age: 32, status: 'draft', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'draft', id: 5 } + * ] + * store.add('post', posts); + * const drafts = store.query('post').filter({ status: 'draft' }).limit(2).run(); + * console.log(drafts); + * + * @class Query + * @extends Component + * @param {Collection} collection The collection on which this query operates. + * @since 3.0.0 + */ +function Query(collection) { + utils.classCallCheck(this, Query); + + /** + * The {@link Collection} on which this query operates. + * + * @name Query#collection + * @since 3.0.0 + * @type {Collection} + */ + this.collection = collection; + + /** + * The current data result of this query. + * + * @name Query#data + * @since 3.0.0 + * @type {Array} + */ + this.data = null; +} + +var Query$1 = Component$1.extend({ + constructor: Query, + + _applyWhereFromObject: function _applyWhereFromObject(where) { + var fields = []; + var ops = []; + var predicates = []; + utils.forOwn(where, function (clause, field) { + if (!utils.isObject(clause)) { + clause = { + '==': clause + }; + } + utils.forOwn(clause, function (expr, op) { + fields.push(field); + ops.push(op); + predicates.push(expr); + }); + }); + return { + fields: fields, + ops: ops, + predicates: predicates + }; + }, + _applyWhereFromArray: function _applyWhereFromArray(where) { + var _this = this; + + var groups = []; + where.forEach(function (_where, i) { + if (utils.isString(_where)) { + return; + } + var prev = where[i - 1]; + var parser = utils.isArray(_where) ? _this._applyWhereFromArray : _this._applyWhereFromObject; + var group = parser.call(_this, _where); + if (prev === 'or') { + group.isOr = true; + } + groups.push(group); + }); + groups.isArray = true; + return groups; + }, + _testObjectGroup: function _testObjectGroup(keep, first, group, item) { + var i = void 0; + var fields = group.fields; + var ops = group.ops; + var predicates = group.predicates; + var len = ops.length; + for (i = 0; i < len; i++) { + var op = ops[i]; + var isOr = op.charAt(0) === '|'; + op = isOr ? op.substr(1) : op; + var expr = this.evaluate(utils.get(item, fields[i]), op, predicates[i]); + if (expr !== undefined) { + keep = first ? expr : isOr ? keep || expr : keep && expr; + } + first = false; + } + return { keep: keep, first: first }; + }, + _testArrayGroup: function _testArrayGroup(keep, first, groups, item) { + var i = void 0; + var len = groups.length; + for (i = 0; i < len; i++) { + var group = groups[i]; + var parser = group.isArray ? this._testArrayGroup : this._testObjectGroup; + var result = parser.call(this, true, true, group, item); + if (groups[i - 1]) { + if (group.isOr) { + keep = keep || result.keep; + } else { + keep = keep && result.keep; + } + } else { + keep = result.keep; + } + first = result.first; + } + return { keep: keep, first: first }; + }, + + + /** + * Find all entities between two boundaries. + * + * @example Get the users ages 18 to 30. + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('user'); + * const users = [ + * { name: 'Peter', age: 25, id: 1 }, + * { name: 'Jim', age: 19, id: 2 }, + * { name: 'Mike', age: 17, id: 3 }, + * { name: 'Alan', age: 29, id: 4 }, + * { name: 'Katie', age: 33, id: 5 } + * ]; + * store.add('user', users) + * const filteredUsers = store + * .query('user') + * .between(18, 30, { index: 'age' }) + * .run(); + * console.log(filteredUsers); + * + * @example Same as above. + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('user'); + * const users = [ + * { name: 'Peter', age: 25, id: 1 }, + * { name: 'Jim', age: 19, id: 2 }, + * { name: 'Mike', age: 17, id: 3 }, + * { name: 'Alan', age: 29, id: 4 }, + * { name: 'Katie', age: 33, id: 5 } + * ]; + * store.add('user', users) + * const filteredUsers = store + * .query('user') + * .between([18], [30], { index: 'age' }) + * .run(); + * console.log(filteredUsers); + * + * @method Query#between + * @param {array} leftKeys Keys defining the left boundary. + * @param {array} rightKeys Keys defining the right boundary. + * @param {object} [opts] Configuration options. + * @param {string} [opts.index] Name of the secondary index to use in the + * query. If no index is specified, the main index is used. + * @param {boolean} [opts.leftInclusive=true] Whether to include entities + * on the left boundary. + * @param {boolean} [opts.rightInclusive=false] Whether to include entities + * on the left boundary. + * @param {boolean} [opts.limit] Limit the result to a certain number. + * @param {boolean} [opts.offset] The number of resulting entities to skip. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + between: function between(leftKeys, rightKeys, opts) { + opts || (opts = {}); + if (this.data) { + throw utils.err(DOMAIN$2 + '#between')(500, 'Cannot access index'); + } + this.data = this.collection.getIndex(opts.index).between(leftKeys, rightKeys, opts); + return this; + }, + + + /** + * The comparison function used by the {@link Query} class. + * + * @method Query#compare + * @param {array} orderBy An orderBy clause used for sorting and sub-sorting. + * @param {number} index The index of the current orderBy clause being used. + * @param {*} a The first item in the comparison. + * @param {*} b The second item in the comparison. + * @returns {number} -1 if `b` should preceed `a`. 0 if `a` and `b` are equal. + * 1 if `a` should preceed `b`. + * @since 3.0.0 + */ + compare: function compare(orderBy, index, a, b) { + var def = orderBy[index]; + var cA = utils.get(a, def[0]); + var cB = utils.get(b, def[0]); + if (cA && utils.isString(cA)) { + cA = cA.toUpperCase(); + } + if (cB && utils.isString(cB)) { + cB = cB.toUpperCase(); + } + if (a === undefined) { + a = null; + } + if (b === undefined) { + b = null; + } + if (def[1].toUpperCase() === 'DESC') { + var temp = cB; + cB = cA; + cA = temp; + } + if (cA < cB) { + return -1; + } else if (cA > cB) { + return 1; + } else { + if (index < orderBy.length - 1) { + return this.compare(orderBy, index + 1, a, b); + } else { + return 0; + } + } + }, + + + /** + * Predicate evaluation function used by the {@link Query} class. + * + * @method Query#evaluate + * @param {*} value The value to evaluate. + * @param {string} op The operator to use in this evaluation. + * @param {*} predicate The predicate to use in this evaluation. + * @returns {boolean} Whether the value passed the evaluation or not. + * @since 3.0.0 + */ + evaluate: function evaluate(value, op, predicate) { + var ops = this.constructor.ops; + if (ops[op]) { + return ops[op](value, predicate); + } + if (op.indexOf('like') === 0) { + return this.like(predicate, op.substr(4)).exec(value) !== null; + } else if (op.indexOf('notLike') === 0) { + return this.like(predicate, op.substr(7)).exec(value) === null; + } + }, + + + /** + * Find the record or records that match the provided query or are accepted by + * the provided filter function. + * + * @example Get the draft posts by authors younger than 30 + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post') + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'published', id: 2 }, + * { author: 'Mike', age: 32, status: 'draft', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'published', id: 5 } + * { author: 'Peter', age: 25, status: 'deleted', id: 6 }, + * { author: 'Sally', age: 21, status: 'draft', id: 7 }, + * { author: 'Jim', age: 27, status: 'draft', id: 8 }, + * { author: 'Jim', age: 27, status: 'published', id: 9 }, + * { author: 'Jason', age: 55, status: 'published', id: 10 } + * ]; + * store.add('post', posts); + * const results = store + * .query('post') + * .filter({ + * where: { + * status: { + * '==': 'draft' + * }, + * age: { + * '<': 30 + * } + * } + * }) + * .run(); + * console.log(results); + * + * @example Use a custom filter function + * const posts = query + * .filter(function (post) { + * return post.isReady(); + * }) + * .run(); + * + * @method Query#filter + * @param {(Object|Function)} [queryOrFn={}] Selection query or filter + * function. + * @param {Function} [thisArg] Context to which to bind `queryOrFn` if + * `queryOrFn` is a function. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + filter: function filter(query, thisArg) { + var _this2 = this; + + /** + * Selection query as defined by JSData's [Query Syntax][querysyntax]. + * + * [querysyntax]: http://www.js-data.io/v3.0/docs/query-syntax + * + * @example Empty "findAll" query + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post') + * store.findAll('post').then((posts) => { + * console.log(posts); // [...] + * }); + * + * @example Empty "filter" query + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * const posts = store.filter('post'); + * console.log(posts); // [...] + * + * @example Complex "filter" query + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * const PAGE_SIZE = 2; + * let currentPage = 3; + * + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'published', id: 2 }, + * { author: 'Mike', age: 32, status: 'draft', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'published', id: 5 } + * { author: 'Peter', age: 25, status: 'deleted', id: 6 }, + * { author: 'Sally', age: 21, status: 'draft', id: 7 }, + * { author: 'Jim', age: 27, status: 'draft', id: 8 }, + * { author: 'Jim', age: 27, status: 'published', id: 9 }, + * { author: 'Jason', age: 55, status: 'published', id: 10 } + * ]; + * store.add('post', posts); + * // Retrieve a filtered page of blog posts + * // Would typically replace filter with findAll + * const results = store.filter('post', { + * where: { + * status: { + * // WHERE status = 'published' + * '==': 'published' + * }, + * author: { + * // AND author IN ('bob', 'alice') + * 'in': ['bob', 'alice'], + * // OR author IN ('karen') + * '|in': ['karen'] + * } + * }, + * orderBy: [ + * // ORDER BY date_published DESC, + * ['date_published', 'DESC'], + * // ORDER BY title ASC + * ['title', 'ASC'] + * ], + * // LIMIT 2 + * limit: PAGE_SIZE, + * // SKIP 4 + * offset: PAGE_SIZE * (currentPage - 1) + * }); + * console.log(results); + * + * @namespace query + * @property {number} [limit] See {@link query.limit}. + * @property {number} [offset] See {@link query.offset}. + * @property {string|Array[]} [orderBy] See {@link query.orderBy}. + * @property {number} [skip] Alias for {@link query.offset}. + * @property {string|Array[]} [sort] Alias for {@link query.orderBy}. + * @property {Object} [where] See {@link query.where}. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/query-syntax","JSData's Query Syntax"] + */ + query || (query = {}); + this.getData(); + if (utils.isObject(query)) { + var where = {}; + + /** + * Filtering criteria. Records that do not meet this criteria will be exluded + * from the result. + * + * @example Return posts where author is at least 32 years old + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post') + * const posts = [ + * { author: 'John', age: 30, id: 5 }, + * { author: 'Sally', age: 31, id: 6 }, + * { author: 'Mike', age: 32, id: 7 }, + * { author: 'Adam', age: 33, id: 8 }, + * { author: 'Adam', age: 33, id: 9 } + * ]; + * store.add('post', posts); + * const results = store.filter('post', { + * where: { + * age: { + * '>=': 30 + * } + * } + * }); + * console.log(results); + * + * @name query.where + * @type {Object} + * @see http://www.js-data.io/v3.0/docs/query-syntax + * @since 3.0.0 + */ + if (utils.isObject(query.where) || utils.isArray(query.where)) { + where = query.where; + } + utils.forOwn(query, function (value, key) { + if (!(key in reserved) && !(key in where)) { + where[key] = { + '==': value + }; + } + }); + var groups = void 0; + + // Apply filter for each field + if (utils.isObject(where) && Object.keys(where).length !== 0) { + groups = this._applyWhereFromArray([where]); + } else if (utils.isArray(where)) { + groups = this._applyWhereFromArray(where); + } + + if (groups) { + this.data = this.data.filter(function (item, i) { + return _this2._testArrayGroup(true, true, groups, item).keep; + }); + } + + // Sort + var orderBy = query.orderBy || query.sort; + + if (utils.isString(orderBy)) { + orderBy = [[orderBy, 'ASC']]; + } + if (!utils.isArray(orderBy)) { + orderBy = null; + } + + /** + * Determines how records should be ordered in the result. + * + * @example Order posts by `author` then by `id` descending + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post') + * const posts = [ + * { author: 'John', age: 30, id: 5 }, + * { author: 'Sally', age: 31, id: 6 }, + * { author: 'Mike', age: 32, id: 7 }, + * { author: 'Adam', age: 33, id: 8 }, + * { author: 'Adam', age: 33, id: 9 } + * ]; + * store.add('post', posts); + * const results = store.filter('post', { + * orderBy:[['author','ASC'],['id','DESC']] + * }); + * console.log(results); + * + * @name query.orderBy + * @type {string|Array[]} + * @see http://www.js-data.io/v3.0/docs/query-syntax + * @since 3.0.0 + */ + if (orderBy) { + var index = 0; + orderBy.forEach(function (def, i) { + if (utils.isString(def)) { + orderBy[i] = [def, 'ASC']; + } + }); + this.data.sort(function (a, b) { + return _this2.compare(orderBy, index, a, b); + }); + } + + /** + * Number of records to skip. + * + * @example Retrieve the first "page" of blog posts using findAll + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * const PAGE_SIZE = 10; + * let currentPage = 1; + * store.findAll('post', { + * offset: PAGE_SIZE * (currentPage 1) + * limit: PAGE_SIZE + * }); + * + * @example Retrieve the last "page" of blog posts using filter + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * + * const PAGE_SIZE = 5; + * let currentPage = 2; + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, id: 1 }, + * { author: 'Sally', age: 31, id: 2 }, + * { author: 'Mike', age: 32, id: 3 }, + * { author: 'Adam', age: 33, id: 4 }, + * { author: 'Adam', age: 33, id: 5 }, + * { author: 'Peter', age: 25, id: 6 }, + * { author: 'Sally', age: 21, id: 7 }, + * { author: 'Jim', age: 27, id: 8 }, + * { author: 'Jim', age: 27, id: 9 }, + * { author: 'Jason', age: 55, id: 10 } + * ]; + * store.add('post', posts); + * const results = store.filter('post', { + * offset: PAGE_SIZE * (currentPage 1) + * limit: PAGE_SIZE + * }); + * console.log(results) + * + * @name query.offset + * @type {number} + * @see http://www.js-data.io/v3.0/docs/query-syntax + * @since 3.0.0 + */ + if (utils.isNumber(query.skip)) { + this.skip(query.skip); + } else if (utils.isNumber(query.offset)) { + this.skip(query.offset); + } + + /** + * Maximum number of records to retrieve. + * + * @example Retrieve the first "page" of blog posts using findAll + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * + * const PAGE_SIZE = 10 + * let currentPage = 1 + * store.findAll('post', { + * offset: PAGE_SIZE * (currentPage 1) + * limit: PAGE_SIZE + * }); + * + * @example Retrieve the last "page" of blog posts using filter + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * + * const PAGE_SIZE = 5 + * let currentPage = 2 + * store.defineMapper('post') + * const posts = [ + * { author: 'John', age: 30, id: 1 }, + * { author: 'Sally', age: 31, id: 2 }, + * { author: 'Mike', age: 32, id: 3 }, + * { author: 'Adam', age: 33, id: 4 }, + * { author: 'Adam', age: 33, id: 5 }, + * { author: 'Peter', age: 25, id: 6 }, + * { author: 'Sally', age: 21, id: 7 }, + * { author: 'Jim', age: 27, id: 8 }, + * { author: 'Jim', age: 27, id: 9 }, + * { author: 'Jason', age: 55, id: 10 } + * ]; + * store.add('post', posts); + * const results = store.filter('post', { + * offset: PAGE_SIZE * (currentPage 1) + * limit: PAGE_SIZE + * }); + * console.log(results) + * + * @name query.limit + * @type {number} + * @see http://www.js-data.io/v3.0/docs/query-syntax + * @since 3.0.0 + */ + if (utils.isNumber(query.limit)) { + this.limit(query.limit); + } + } else if (utils.isFunction(query)) { + this.data = this.data.filter(query, thisArg); + } + return this; + }, + + + /** + * Iterate over all entities. + * + * @method Query#forEach + * @param {Function} forEachFn Iteration function. + * @param {*} [thisArg] Context to which to bind `forEachFn`. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + forEach: function forEach(forEachFn, thisArg) { + this.getData().forEach(forEachFn, thisArg); + return this; + }, + + + /** + * Find the entity or entities that match the provided key. + * + * @example Get the entity whose primary key is 25. + * const entities = query.get(25).run(); + * + * @example Same as above. + * const entities = query.get([25]).run(); + * + * @example Get all users who are active and have the "admin" role. + * const activeAdmins = query.get(['active', 'admin'], { + * index: 'activityAndRoles' + * }).run(); + * + * @example Get all entities that match a certain weather condition. + * const niceDays = query.get(['sunny', 'humid', 'calm'], { + * index: 'weatherConditions' + * }).run(); + * + * @method Query#get + * @param {array} keyList Key(s) defining the entity to retrieve. If + * `keyList` is not an array (i.e. for a single-value key), it will be + * wrapped in an array. + * @param {object} [opts] Configuration options. + * @param {string} [opts.string] Name of the secondary index to use in the + * query. If no index is specified, the main index is used. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + get: function get(keyList, opts) { + keyList || (keyList = []); + opts || (opts = {}); + if (this.data) { + throw utils.err(DOMAIN$2 + '#get')(500, INDEX_ERR); + } + if (keyList && !utils.isArray(keyList)) { + keyList = [keyList]; + } + if (!keyList.length) { + this.getData(); + return this; + } + this.data = this.collection.getIndex(opts.index).get(keyList); + return this; + }, + + + /** + * Find the entity or entities that match the provided keyLists. + * + * @example Get the posts where "status" is "draft" or "inReview". + * const posts = query.getAll('draft', 'inReview', { index: 'status' }).run(); + * + * @example Same as above. + * const posts = query.getAll(['draft'], ['inReview'], { index: 'status' }).run(); + * + * @method Query#getAll + * @param {...Array} [keyList] Provide one or more keyLists, and all + * entities matching each keyList will be retrieved. If no keyLists are + * provided, all entities will be returned. + * @param {object} [opts] Configuration options. + * @param {string} [opts.index] Name of the secondary index to use in the + * query. If no index is specified, the main index is used. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + getAll: function getAll() { + var _this3 = this; + + var opts = {}; + if (this.data) { + throw utils.err(DOMAIN$2 + '#getAll')(500, INDEX_ERR); + } + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + if (!args.length || args.length === 1 && utils.isObject(args[0])) { + this.getData(); + return this; + } else if (args.length && utils.isObject(args[args.length - 1])) { + opts = args[args.length - 1]; + args.pop(); + } + var collection = this.collection; + var index = collection.getIndex(opts.index); + this.data = []; + args.forEach(function (keyList) { + _this3.data = _this3.data.concat(index.get(keyList)); + }); + return this; + }, + + + /** + * Return the current data result of this query. + * + * @method Query#getData + * @returns {Array} The data in this query. + * @since 3.0.0 + */ + getData: function getData() { + if (!this.data) { + this.data = this.collection.index.getAll(); + } + return this.data; + }, + + + /** + * Implementation used by the `like` operator. Takes a pattern and flags and + * returns a `RegExp` instance that can test strings. + * + * @method Query#like + * @param {string} pattern Testing pattern. + * @param {string} flags Flags for the regular expression. + * @returns {RegExp} Regular expression for testing strings. + * @since 3.0.0 + */ + like: function like(pattern, flags) { + return new RegExp('^' + escape(pattern).replace(percentRegExp, '.*').replace(underscoreRegExp, '.') + '$', flags); + }, + + + /** + * Limit the result. + * + * @example Get only the first 2 posts. + * const store = new JSData.DataStore(); + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'draft', id: 2 }, + * { author: 'Mike', age: 32, status: 'draft', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'draft', id: 5 } + * ]; + * store.add('post', posts); + * const results = store.query('post').limit(2).run(); + * console.log(results); + * + * @method Query#limit + * @param {number} num The maximum number of entities to keep in the result. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + limit: function limit(num) { + if (!utils.isNumber(num)) { + throw utils.err(DOMAIN$2 + '#limit', 'num')(400, 'number', num); + } + var data = this.getData(); + this.data = data.slice(0, Math.min(data.length, num)); + return this; + }, + + + /** + * Apply a mapping function to the result data. + * + * @example + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('user'); + * const users = [ + * { name: 'Peter', age: 25, id: 1 }, + * { name: 'Jim', age: 19, id: 2 }, + * { name: 'Mike', age: 17, id: 3 }, + * { name: 'Alan', age: 29, id: 4 }, + * { name: 'Katie', age: 33, id: 5 } + * ]; + * store.add('user', users); + * const ages = store + * .query('user') + * .map(function (user) { + * return user.age; + * }) + * .run(); + * console.log(ages); + * + * @method Query#map + * @param {Function} mapFn Mapping function. + * @param {*} [thisArg] Context to which to bind `mapFn`. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + map: function map(mapFn, thisArg) { + this.data = this.getData().map(mapFn, thisArg); + return this; + }, + + + /** + * Return the result of calling the specified function on each item in this + * collection's main index. + * + * @example + * const stringAges = UserCollection.query().mapCall('toString').run(); + * + * @method Query#mapCall + * @param {string} funcName Name of function to call + * @parama {...*} [args] Remaining arguments to be passed to the function. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + mapCall: function mapCall(funcName) { + for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + this.data = this.getData().map(function (item) { + return item[funcName].apply(item, args); + }); + return this; + }, + + + /** + * Complete the execution of the query and return the resulting data. + * + * @method Query#run + * @returns {Array} The result of executing this query. + * @since 3.0.0 + */ + run: function run() { + var data = this.data; + this.data = null; + return data; + }, + + + /** + * Skip a number of results. + * + * @example Get all but the first 2 posts. + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'draft', id: 2 }, + * { author: 'Mike', age: 32, status: 'draft', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'draft', id: 5 } + * ]; + * store.add('post', posts); + * const results = store.query('post').skip(2).run(); + * console.log(results); + * + * @method Query#skip + * @param {number} num The number of entities to skip. + * @returns {Query} A reference to itself for chaining. + * @since 3.0.0 + */ + skip: function skip(num) { + if (!utils.isNumber(num)) { + throw utils.err(DOMAIN$2 + '#skip', 'num')(400, 'number', num); + } + var data = this.getData(); + if (num < data.length) { + this.data = data.slice(num); + } else { + this.data = []; + } + return this; + } +}, { + /** + * The filtering operators supported by {@link Query#filter}, and which are + * implemented by adapters (for the most part). + * + * @example Variant 1 + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'published', id: 2 }, + * { author: 'Mike', age: 32, status: 'published', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'published', id: 5 } + * ]; + * store.add('post', posts); + * const publishedPosts = store.filter('post', { + * status: 'published', + * limit: 2 + * }); + * console.log(publishedPosts); + * + * + * @example Variant 2 + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post') + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'published', id: 2 }, + * { author: 'Mike', age: 32, status: 'published', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'published', id: 5 } + * ]; + * store.add('post', posts); + * const publishedPosts = store.filter('post', { + * where: { + * status: { + * '==': 'published' + * } + * }, + * limit: 2 + * }); + * console.log(publishedPosts); + * + * @example Variant 3 + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'published', id: 2 }, + * { author: 'Mike', age: 32, status: 'published', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'published', id: 5 } + * ]; + * store.add('post', posts); + * const publishedPosts = store + * .query('post') + * .filter({ status: 'published' }) + * .limit(2) + * .run(); + * console.log(publishedPosts); + * + * @example Variant 4 + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'published', id: 2 }, + * { author: 'Mike', age: 32, status: 'published', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'published', id: 5 } + * ]; + * store.add('post', posts); + * const publishedPosts = store + * .query('post') + * .filter({ + * where: { + * status: { + * '==': 'published' + * } + * } + * }) + * .limit(2) + * .run(); + * console.log(publishedPosts); + * + * @example Multiple operators + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new DataStore(); + * store.defineMapper('post'); + * const posts = [ + * { author: 'John', age: 30, status: 'published', id: 1 }, + * { author: 'Sally', age: 31, status: 'published', id: 2 }, + * { author: 'Mike', age: 32, status: 'published', id: 3 }, + * { author: 'Adam', age: 33, status: 'deleted', id: 4 }, + * { author: 'Adam', age: 33, status: 'published', id: 5 } + * ]; + * store.add('post', posts); + * + * const myPublishedPosts = store.filter('post', { + * where: { + * status: { + * '==': 'published' + * }, + * user_id: { + * '==': currentUser.id + * } + * } + * }); + * + * console.log(myPublishedPosts); + * + * @name Query.ops + * @property {Function} == Equality operator. + * @property {Function} != Inequality operator. + * @property {Function} > Greater than operator. + * @property {Function} >= Greater than (inclusive) operator. + * @property {Function} < Less than operator. + * @property {Function} <= Less than (inclusive) operator. + * @property {Function} isectEmpty Operator that asserts that the intersection + * between two arrays is empty. + * @property {Function} isectNotEmpty Operator that asserts that the + * intersection between two arrays is __not__ empty. + * @property {Function} in Operator that asserts whether a value is in an + * array. + * @property {Function} notIn Operator that asserts whether a value is __not__ + * in an array. + * @property {Function} contains Operator that asserts whether an array + * contains a value. + * @property {Function} notContains Operator that asserts whether an array + * does __not__ contain a value. + * @since 3.0.0 + * @type {Object} + */ + ops: { + '=': function _(value, predicate) { + return value == predicate; // eslint-disable-line + }, + '==': function _(value, predicate) { + return value == predicate; // eslint-disable-line + }, + '===': function _(value, predicate) { + return value === predicate; + }, + '!=': function _(value, predicate) { + return value != predicate; // eslint-disable-line + }, + '!==': function _(value, predicate) { + return value !== predicate; + }, + '>': function _(value, predicate) { + return value > predicate; + }, + '>=': function _(value, predicate) { + return value >= predicate; + }, + '<': function _(value, predicate) { + return value < predicate; + }, + '<=': function _(value, predicate) { + return value <= predicate; + }, + 'isectEmpty': function isectEmpty(value, predicate) { + return !utils.intersection(value || [], predicate || []).length; + }, + 'isectNotEmpty': function isectNotEmpty(value, predicate) { + return utils.intersection(value || [], predicate || []).length; + }, + 'in': function _in(value, predicate) { + return predicate.indexOf(value) !== -1; + }, + 'notIn': function notIn(value, predicate) { + return predicate.indexOf(value) === -1; + }, + 'contains': function contains(value, predicate) { + return (value || []).indexOf(predicate) !== -1; + }, + 'notContains': function notContains(value, predicate) { + return (value || []).indexOf(predicate) === -1; + } + } +}); + +/** + * Create a subclass of this Query: + * @example Query.extend + * const JSData = require('js-data'); + * const { Query } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomQueryClass extends Query { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customQuery = new CustomQueryClass(); + * console.log(customQuery.foo()); + * console.log(CustomQueryClass.beep()); + * + * // Extend the class using alternate method. + * const OtherQueryClass = Query.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherQuery = new OtherQueryClass(); + * console.log(otherQuery.foo()); + * console.log(OtherQueryClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherQueryClass (collection) { + * Query.call(this, collection); + * this.created_at = new Date().getTime(); + * } + * Query.extend({ + * constructor: AnotherQueryClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const anotherQuery = new AnotherQueryClass(); + * console.log(anotherQuery.created_at); + * console.log(anotherQuery.foo()); + * console.log(AnotherQueryClass.beep()); + * + * @method Query.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this Query class. + * @since 3.0.0 + */ + +// TODO: remove this when the rest of the project is cleaned +var belongsToType = 'belongsTo'; +var hasManyType = 'hasMany'; +var hasOneType = 'hasOne'; + +var DOMAIN$4 = 'Relation'; + +function Relation(relatedMapper) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + utils.classCallCheck(this, Relation); + + options.type = this.constructor.TYPE_NAME; + this.validateOptions(relatedMapper, options); + + if ((typeof relatedMapper === 'undefined' ? 'undefined' : _typeof(relatedMapper)) === 'object') { + Object.defineProperty(this, 'relatedMapper', { value: relatedMapper }); + } + + Object.defineProperty(this, 'inverse', { writable: true }); + utils.fillIn(this, options); +} + +Relation.extend = utils.extend; + +utils.addHiddenPropsToTarget(Relation.prototype, { + get canAutoAddLinks() { + return this.add === undefined || !!this.add; + }, + + get relatedCollection() { + return this.mapper.datastore.getCollection(this.relation); + }, + + validateOptions: function validateOptions(related, opts) { + var DOMAIN_ERR = 'new ' + DOMAIN$4; + + var localField = opts.localField; + if (!localField) { + throw utils.err(DOMAIN_ERR, 'opts.localField')(400, 'string', localField); + } + + var foreignKey = opts.foreignKey = opts.foreignKey || opts.localKey; + if (!foreignKey && (opts.type === belongsToType || opts.type === hasOneType)) { + throw utils.err(DOMAIN_ERR, 'opts.foreignKey')(400, 'string', foreignKey); + } + + if (utils.isString(related)) { + opts.relation = related; + if (!utils.isFunction(opts.getRelation)) { + throw utils.err(DOMAIN_ERR, 'opts.getRelation')(400, 'function', opts.getRelation); + } + } else if (related) { + opts.relation = related.name; + } else { + throw utils.err(DOMAIN_ERR, 'related')(400, 'Mapper or string', related); + } + }, + assignTo: function assignTo(mapper) { + this.name = mapper.name; + Object.defineProperty(this, 'mapper', { value: mapper }); + + mapper.relationList || Object.defineProperty(mapper, 'relationList', { value: [] }); + mapper.relationFields || Object.defineProperty(mapper, 'relationFields', { value: [] }); + mapper.relationList.push(this); + mapper.relationFields.push(this.localField); + }, + canFindLinkFor: function canFindLinkFor() { + return !!(this.foreignKey || this.localKey); + }, + getRelation: function getRelation() { + return this.relatedMapper; + }, + getForeignKey: function getForeignKey(record) { + return utils.get(record, this.mapper.idAttribute); + }, + setForeignKey: function setForeignKey(record, relatedRecord) { + if (!record || !relatedRecord) { + return; + } + + this._setForeignKey(record, relatedRecord); + }, + _setForeignKey: function _setForeignKey(record, relatedRecords) { + var _this = this; + + var idAttribute = this.mapper.idAttribute; + + if (!utils.isArray(relatedRecords)) { + relatedRecords = [relatedRecords]; + } + + relatedRecords.forEach(function (relatedRecord) { + utils.set(relatedRecord, _this.foreignKey, utils.get(record, idAttribute)); + }); + }, + getLocalField: function getLocalField(record) { + return utils.get(record, this.localField); + }, + setLocalField: function setLocalField(record, relatedData) { + return utils.set(record, this.localField, relatedData); + }, + getInverse: function getInverse(mapper) { + if (!this.inverse) { + this.findInverseRelation(mapper); + } + + return this.inverse; + }, + findInverseRelation: function findInverseRelation(mapper) { + var _this2 = this; + + this.getRelation().relationList.forEach(function (def) { + if (def.getRelation() === mapper && _this2.isInversedTo(def) && _this2 !== def) { + _this2.inverse = def; + return true; + } + }); + }, + isInversedTo: function isInversedTo(def) { + return !def.foreignKey || def.foreignKey === this.foreignKey; + }, + addLinkedRecords: function addLinkedRecords(records) { + var _this3 = this; + + var datastore = this.mapper.datastore; + + records.forEach(function (record) { + var relatedData = _this3.getLocalField(record); + + if (utils.isFunction(_this3.add)) { + relatedData = _this3.add(datastore, _this3, record); + } else if (relatedData) { + relatedData = _this3.linkRecord(record, relatedData); + } + + var isEmptyLinks = !relatedData || utils.isArray(relatedData) && !relatedData.length; + + if (isEmptyLinks && _this3.canFindLinkFor(record)) { + relatedData = _this3.findExistingLinksFor(record); + } + + if (relatedData) { + _this3.setLocalField(record, relatedData); + } + }); + }, + removeLinkedRecords: function removeLinkedRecords(relatedMapper, records) { + var localField = this.localField; + records.forEach(function (record) { + utils.set(record, localField, undefined); + }); + }, + linkRecord: function linkRecord(record, relatedRecord) { + var relatedId = utils.get(relatedRecord, this.mapper.idAttribute); + + if (relatedId === undefined) { + var unsaved = this.relatedCollection.unsaved(); + if (unsaved.indexOf(relatedRecord) === -1) { + if (this.canAutoAddLinks) { + relatedRecord = this.relatedCollection.add(relatedRecord); + } + } + } else { + if (relatedRecord !== this.relatedCollection.get(relatedId)) { + this.setForeignKey(record, relatedRecord); + + if (this.canAutoAddLinks) { + relatedRecord = this.relatedCollection.add(relatedRecord); + } + } + } + + return relatedRecord; + }, + + + // e.g. user hasMany post via "foreignKey", so find all posts of user + findExistingLinksByForeignKey: function findExistingLinksByForeignKey(id) { + if (id === undefined || id === null) { + return; + } + return this.relatedCollection.filter(defineProperty({}, this.foreignKey, id)); + }, + ensureLinkedDataHasProperType: function ensureLinkedDataHasProperType(props, opts) { + var relatedMapper = this.getRelation(); + var relationData = this.getLocalField(props); + + if (utils.isArray(relationData) && (!relationData.length || relatedMapper.is(relationData[0]))) { + return; + } + + if (relationData && !relatedMapper.is(relationData)) { + utils.set(props, this.localField, relatedMapper.createRecord(relationData, opts)); + } + }, + isRequiresParentId: function isRequiresParentId() { + return false; + }, + isRequiresChildId: function isRequiresChildId() { + return false; + }, + createChildRecord: function createChildRecord(props, relationData, opts) { + var _this4 = this; + + this.setForeignKey(props, relationData); + + return this.createLinked(relationData, opts).then(function (result) { + _this4.setLocalField(props, result); + }); + }, + createLinked: function createLinked(props, opts) { + var create = utils.isArray(props) ? 'createMany' : 'create'; + + return this.getRelation()[create](props, opts); + } +}); + +var BelongsToRelation = Relation.extend({ + getForeignKey: function getForeignKey(record) { + return utils.get(record, this.foreignKey); + }, + _setForeignKey: function _setForeignKey(record, relatedRecord) { + utils.set(record, this.foreignKey, utils.get(relatedRecord, this.getRelation().idAttribute)); + }, + findExistingLinksFor: function findExistingLinksFor(record) { + // console.log('\tBelongsTo#findExistingLinksFor', record) + if (!record) { + return; + } + var relatedId = utils.get(record, this.foreignKey); + if (relatedId !== undefined && relatedId !== null) { + return this.relatedCollection.get(relatedId); + } + }, + isRequiresParentId: function isRequiresParentId() { + return true; + }, + createParentRecord: function createParentRecord(props, opts) { + var _this = this; + + var relationData = this.getLocalField(props); + + return this.createLinked(relationData, opts).then(function (record) { + _this.setForeignKey(props, record); + }); + }, + createChildRecord: function createChildRecord() { + throw new Error('"BelongsTo" relation does not support child creation as it cannot have children.'); + } +}, { + TYPE_NAME: 'belongsTo' +}); + +var HasManyRelation = Relation.extend({ + validateOptions: function validateOptions(related, opts) { + Relation.prototype.validateOptions.call(this, related, opts); + + var localKeys = opts.localKeys, + foreignKeys = opts.foreignKeys, + foreignKey = opts.foreignKey; + + + if (!foreignKey && !localKeys && !foreignKeys) { + throw utils.err('new Relation', 'opts.')(400, 'string', foreignKey); + } + }, + canFindLinkFor: function canFindLinkFor(record) { + var hasForeignKeys = this.foreignKey || this.foreignKeys; + return !!(hasForeignKeys || this.localKeys && utils.get(record, this.localKeys)); + }, + linkRecord: function linkRecord(record, relatedRecords) { + var _this = this; + + var relatedCollection = this.relatedCollection; + var canAutoAddLinks = this.canAutoAddLinks; + var foreignKey = this.foreignKey; + var unsaved = this.relatedCollection.unsaved(); + + return relatedRecords.map(function (relatedRecord) { + var relatedId = relatedCollection.recordId(relatedRecord); + + if (relatedId === undefined && unsaved.indexOf(relatedRecord) === -1 || relatedRecord !== relatedCollection.get(relatedId)) { + if (foreignKey) { + // TODO: slow, could be optimized? But user loses hook + _this.setForeignKey(record, relatedRecord); + } + if (canAutoAddLinks) { + relatedRecord = relatedCollection.add(relatedRecord); + } + } + + return relatedRecord; + }); + }, + findExistingLinksFor: function findExistingLinksFor(record) { + var id = utils.get(record, this.mapper.idAttribute); + var ids = this.localKeys ? utils.get(record, this.localKeys) : null; + var records = void 0; + + if (id !== undefined && this.foreignKey) { + records = this.findExistingLinksByForeignKey(id); + } else if (this.localKeys && ids) { + records = this.findExistingLinksByLocalKeys(ids); + } else if (id !== undefined && this.foreignKeys) { + records = this.findExistingLinksByForeignKeys(id); + } + + if (records && records.length) { + return records; + } + }, + + + // e.g. user hasMany group via "foreignKeys", so find all users of a group + findExistingLinksByLocalKeys: function findExistingLinksByLocalKeys(ids) { + return this.relatedCollection.filter({ + where: defineProperty({}, this.mapper.idAttribute, { + 'in': ids + }) + }); + }, + + + // e.g. group hasMany user via "localKeys", so find all groups that own a user + findExistingLinksByForeignKeys: function findExistingLinksByForeignKeys(id) { + return this.relatedCollection.filter({ + where: defineProperty({}, this.foreignKeys, { + 'contains': id + }) + }); + }, + isRequiresParentId: function isRequiresParentId() { + return !!this.localKeys && this.localKeys.length > 0; + }, + isRequiresChildId: function isRequiresChildId() { + return !!this.foreignKey; + }, + createParentRecord: function createParentRecord(props, opts) { + var _this2 = this; + + var relationData = this.getLocalField(props); + var foreignIdField = this.getRelation().idAttribute; + + return this.createLinked(relationData, opts).then(function (records) { + utils.set(props, _this2.localKeys, records.map(function (record) { + return utils.get(record, foreignIdField); + })); + }); + }, + createLinked: function createLinked(props, opts) { + return this.getRelation().createMany(props, opts); + } +}, { + TYPE_NAME: 'hasMany' +}); + +var HasOneRelation = Relation.extend({ + findExistingLinksFor: function findExistingLinksFor(relatedMapper, record) { + var recordId = utils.get(record, relatedMapper.idAttribute); + var records = this.findExistingLinksByForeignKey(recordId); + + if (records && records.length) { + return records[0]; + } + }, + isRequiresChildId: function isRequiresChildId() { + return true; + } +}, { + TYPE_NAME: 'hasOne' +}); + +[BelongsToRelation, HasManyRelation, HasOneRelation].forEach(function (RelationType) { + Relation[RelationType.TYPE_NAME] = function (related, options) { + return new RelationType(related, options); + }; +}); + +/** + * BelongsTo relation decorator. You probably won't use this directly. + * + * @name module:js-data.belongsTo + * @method + * @param {Mapper} related The relation the target belongs to. + * @param {object} opts Configuration options. + * @param {string} opts.foreignKey The field that holds the primary key of the + * related record. + * @param {string} opts.localField The field that holds a reference to the + * related record object. + * @returns {Function} Invocation function, which accepts the target as the only + * parameter. + */ +var belongsTo = function belongsTo(related, opts) { + return function (mapper) { + Relation.belongsTo(related, opts).assignTo(mapper); + }; +}; + +/** + * HasMany relation decorator. You probably won't use this directly. + * + * @name module:js-data.hasMany + * @method + * @param {Mapper} related The relation of which the target has many. + * @param {object} opts Configuration options. + * @param {string} [opts.foreignKey] The field that holds the primary key of the + * related record. + * @param {string} opts.localField The field that holds a reference to the + * related record object. + * @returns {Function} Invocation function, which accepts the target as the only + * parameter. + */ +var hasMany = function hasMany(related, opts) { + return function (mapper) { + Relation.hasMany(related, opts).assignTo(mapper); + }; +}; + +/** + * HasOne relation decorator. You probably won't use this directly. + * + * @name module:js-data.hasOne + * @method + * @param {Mapper} related The relation of which the target has one. + * @param {object} opts Configuration options. + * @param {string} [opts.foreignKey] The field that holds the primary key of the + * related record. + * @param {string} opts.localField The field that holds a reference to the + * related record object. + * @returns {Function} Invocation function, which accepts the target as the only + * parameter. + */ +var hasOne = function hasOne(related, opts) { + return function (mapper) { + Relation.hasOne(related, opts).assignTo(mapper); + }; +}; + +var DOMAIN$3 = 'Record'; + +var superMethod = function superMethod(mapper, name) { + var store = mapper.datastore; + if (store && store[name]) { + return function () { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return store[name].apply(store, [mapper.name].concat(args)); + }; + } + return mapper[name].bind(mapper); +}; + +// Cache these strings +var creatingPath = 'creating'; +var noValidatePath$1 = 'noValidate'; +var keepChangeHistoryPath = 'keepChangeHistory'; +var previousPath = 'previous'; + +/** + * js-data's Record class. An instance of `Record` corresponds to an in-memory + * representation of a single row or document in a database, Firebase, + * localstorage, etc. Basically, a `Record` instance represents whatever kind of + * entity in your persistence layer that has a primary key. + * + * ```javascript + * import {Record} from 'js-data' + * ``` + * + * @example Record#constructor + * const JSData = require('js-data'); + * const { Record } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Instantiate a plain record + * let record = new Record(); + * console.log('record: ' + JSON.stringify(record)); + * + * // You can supply properties on instantiation + * record = new Record({ name: 'John' }); + * console.log('record: ' + JSON.stringify(record)); + * + * @example Record#constructor2 + * const JSData = require('js-data'); + * const { Mapper } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Instantiate a record that's associated with a Mapper: + * const UserMapper = new Mapper({ name: 'user' }); + * const User = UserMapper.recordClass; + * const user = UserMapper.createRecord({ name: 'John' }); + * const user2 = new User({ name: 'Sally' }); + * console.log('user: ' + JSON.stringify(user)); + * console.log('user2: ' + JSON.stringify(user2)); + * + * @example Record#constructor3 + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * store.defineMapper('user'); + * + * // Instantiate a record that's associated with a store's Mapper + * const user = store.createRecord('user', { name: 'John' }); + * console.log('user: ' + JSON.stringify(user)); + * + * @example Record#constructor4 + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * store.defineMapper('user', { + * schema: { + * properties: { + * name: { type: 'string' } + * } + * } + * }); + * + * // Validate on instantiation + * const user = store.createRecord('user', { name: 1234 }); + * console.log('user: ' + JSON.stringify(user)); + * + * @example Record#constructor5 + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * store.defineMapper('user', { + * schema: { + * properties: { + * name: { type: 'string' } + * } + * } + * }); + * + * // Skip validation on instantiation + * const user = store.createRecord('user', { name: 1234 }, { noValidate: true }); + * console.log('user: ' + JSON.stringify(user)); + * console.log('user.isValid(): ' + user.isValid()); + * + * @class Record + * @extends Component + * @param {object} [props] The initial properties of the new Record instance. + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.noValidate=false] Whether to skip validation on the + * initial properties. + * @param {boolean} [opts.validateOnSet=true] Whether to enable setter + * validation on properties after the Record has been initialized. + * @since 3.0.0 + */ +function Record(props, opts) { + utils.classCallCheck(this, Record); + Settable.call(this); + props || (props = {}); + opts || (opts = {}); + var _set = this._set; + var mapper = this.constructor.mapper; + + _set(creatingPath, true); + _set(noValidatePath$1, !!opts.noValidate); + _set(keepChangeHistoryPath, opts.keepChangeHistory === undefined ? mapper ? mapper.keepChangeHistory : true : opts.keepChangeHistory); + + // Set the idAttribute value first, if it exists. + var id = mapper ? utils.get(props, mapper.idAttribute) : undefined; + if (id !== undefined) { + utils.set(this, mapper.idAttribute, id); + } + + utils.fillIn(this, props); + _set(creatingPath, false); + if (opts.validateOnSet !== undefined) { + _set(noValidatePath$1, !opts.validateOnSet); + } else if (mapper && mapper.validateOnSet !== undefined) { + _set(noValidatePath$1, !mapper.validateOnSet); + } else { + _set(noValidatePath$1, false); + } + _set(previousPath, mapper ? mapper.toJSON(props) : utils.plainCopy(props)); +} + +var Record$1 = Component$1.extend({ + constructor: Record, + + /** + * Returns the {@link Mapper} paired with this record's class, if any. + * + * @method Record#_mapper + * @returns {Mapper} The {@link Mapper} paired with this record's class, if any. + * @since 3.0.0 + */ + _mapper: function _mapper() { + var mapper = this.constructor.mapper; + if (!mapper) { + throw utils.err(DOMAIN$3 + '#_mapper', '')(404, 'mapper'); + } + return mapper; + }, + + + /** + * Lifecycle hook. + * + * @method Record#afterLoadRelations + * @param {string[]} relations The `relations` argument passed to {@link Record#loadRelations}. + * @param {object} opts The `opts` argument passed to {@link Record#loadRelations}. + * @since 3.0.0 + */ + afterLoadRelations: function afterLoadRelations() {}, + + + /** + * Lifecycle hook. + * + * @method Record#beforeLoadRelations + * @param {string[]} relations The `relations` argument passed to {@link Record#loadRelations}. + * @param {object} opts The `opts` argument passed to {@link Record#loadRelations}. + * @since 3.0.0 + */ + beforeLoadRelations: function beforeLoadRelations() {}, + + + /** + * Return the change history of this record since it was instantiated or + * {@link Record#commit} was called. + * + * @method Record#changeHistory + * @since 3.0.0 + */ + changeHistory: function changeHistory() { + return (this._get('history') || []).slice(); + }, + + + /** + * Return changes to this record since it was instantiated or + * {@link Record#commit} was called. + * + * @example Record#changes + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * store.defineMapper('user'); + * const user = store.createRecord('user'); + * console.log('user changes: ' + JSON.stringify(user.changes())); + * user.name = 'John'; + * console.log('user changes: ' + JSON.stringify(user.changes())); + * + * @method Record#changes + * @param [opts] Configuration options. + * @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function. + * @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore. + * @returns {Object} Object describing the changes to this record since it was + * instantiated or its {@link Record#commit} method was last called. + * @since 3.0.0 + */ + changes: function changes(opts) { + opts || (opts = {}); + return utils.diffObjects(typeof this.toJSON === 'function' ? this.toJSON(opts) : this, this._get('previous'), opts); + }, + + + /** + * Make the record's current in-memory state it's only state, with any + * previous property values being set to current values. + * + * @example Record#commit + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * store.defineMapper('user'); + * const user = store.createRecord('user'); + * console.log('user hasChanges: ' + user.hasChanges()); + * user.name = 'John'; + * console.log('user hasChanges: ' + user.hasChanges()); + * user.commit(); + * console.log('user hasChanges: ' + user.hasChanges()); + * + * @method Record#commit + * @param {object} [opts] Configuration options. Passed to {@link Record#toJSON}. + * @since 3.0.0 + */ + commit: function commit(opts) { + this._set('changed'); // unset + this._set('changing', false); + this._set('history', []); // clear history + this._set('previous', this.toJSON(opts)); + }, + + + /** + * Call {@link Mapper#destroy} using this record's primary key. + * + * @example + * import { Container } from 'js-data'; + * import { RethinkDBAdapter } from 'js-data-rethinkdb'; + * + * const store = new Container(); + * store.registerAdapter('rethink', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('user'); + * store.find('user', 1234).then((user) => { + * console.log(user.id); // 1234 + * + * // Destroy this user from the database + * return user.destroy(); + * }); + * + * @method Record#destroy + * @param {object} [opts] Configuration options passed to {@link Mapper#destroy}. + * @returns {Promise} The result of calling {@link Mapper#destroy} with the + * primary key of this record. + * @since 3.0.0 + */ + destroy: function destroy(opts) { + opts || (opts = {}); + var mapper = this._mapper(); + return superMethod(mapper, 'destroy')(utils.get(this, mapper.idAttribute), opts); + }, + + + /** + * Return the value at the given path for this instance. + * + * @example Record#get + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user'); + * + * const user = store.createRecord('user', { name: 'Bob' }); + * console.log('user.get("name"): ' + user.get('name')); + * + * @method Record#get + * @param {string} key Path of value to retrieve. + * @returns {*} Value at path. + * @since 3.0.0 + */ + 'get': function get$$1(key) { + return utils.get(this, key); + }, + + + /** + * Return whether this record has changed since it was instantiated or + * {@link Record#commit} was called. + * + * @example Record#hasChanges + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user'); + * const user = store.createRecord('user'); + * console.log('user hasChanges: ' + user.hasChanges()); + * user.name = 'John'; + * console.log('user hasChanges: ' + user.hasChanges()); + * user.commit(); + * console.log('user hasChanges: ' + user.hasChanges()); + * + * @method Record#hasChanges + * @param [opts] Configuration options. + * @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function. + * @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore. + * @returns {boolean} Return whether the record has changed since it was + * instantiated or since its {@link Record#commit} method was called. + * @since 3.0.0 + */ + hasChanges: function hasChanges(opts) { + var quickHasChanges = !!(this._get('changed') || []).length; + return quickHasChanges || utils.areDifferent(typeof this.toJSON === 'function' ? this.toJSON(opts) : this, this._get('previous'), opts); + }, + + + /** + * Return whether the record is unsaved. Records that have primary keys are + * considered "saved". Records without primary keys are considered "unsaved". + * + * @example Record#isNew + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user'); + * const user = store.createRecord('user', { + * id: 1234 + * }); + * const user2 = store.createRecord('user'); + * console.log('user isNew: ' + user.isNew()); // false + * console.log('user2 isNew: ' + user2.isNew()); // true + * + * @method Record#isNew + * @returns {boolean} Whether the record is unsaved. + * @since 3.0.0 + */ + isNew: function isNew(opts) { + return utils.get(this, this._mapper().idAttribute) === undefined; + }, + + + /** + * Return whether the record in its current state passes validation. + * + * @example Record#isValid + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user', { + * schema: { + * properties: { + * name: { type: 'string' } + * } + * } + * }); + * const user = store.createRecord('user', { + * name: 1234 + * }, { + * noValidate: true // this allows us to put the record into an invalid state + * }); + * console.log('user isValid: ' + user.isValid()); + * user.name = 'John'; + * console.log('user isValid: ' + user.isValid()); + * + * @method Record#isValid + * @param {object} [opts] Configuration options. Passed to {@link Mapper#validate}. + * @returns {boolean} Whether the record in its current state passes + * validation. + * @since 3.0.0 + */ + isValid: function isValid(opts) { + return !this._mapper().validate(this, opts); + }, + removeInverseRelation: function removeInverseRelation(currentParent, id, inverseDef, idAttribute) { + var _this = this; + + if (inverseDef.type === hasOneType) { + safeSetLink(currentParent, inverseDef.localField, undefined); + } else if (inverseDef.type === hasManyType) { + // e.g. remove comment from otherPost.comments + var children = utils.get(currentParent, inverseDef.localField); + if (id === undefined) { + utils.remove(children, function (child) { + return child === _this; + }); + } else { + utils.remove(children, function (child) { + return child === _this || id === utils.get(child, idAttribute); + }); + } + } + }, + setupInverseRelation: function setupInverseRelation(record, id, inverseDef, idAttribute) { + var _this2 = this; + + // Update (set) inverse relation + if (inverseDef.type === hasOneType) { + // e.g. someUser.profile = profile + safeSetLink(record, inverseDef.localField, this); + } else if (inverseDef.type === hasManyType) { + // e.g. add comment to somePost.comments + var children = utils.get(record, inverseDef.localField); + if (id === undefined) { + utils.noDupeAdd(children, this, function (child) { + return child === _this2; + }); + } else { + utils.noDupeAdd(children, this, function (child) { + return child === _this2 || id === utils.get(child, idAttribute); + }); + } + } + }, + + + /** + * Lazy load relations of this record, to be attached to the record once their + * loaded. + * + * @example + * import { Container } from 'js-data'; + * import { RethinkDBAdapter } from 'js-data-rethinkdb'; + * + * const store = new Container(); + * store.registerAdapter('rethink', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('user', { + * relations: { + * hasMany: { + * post: { + * localField: 'posts', + * foreignKey: 'user_id' + * } + * } + * } + * }); + * store.defineMapper('post', { + * relations: { + * belongsTo: { + * user: { + * localField: 'user', + * foreignKey: 'user_id' + * } + * } + * } + * }); + * store.find('user', 1234).then((user) => { + * console.log(user.id); // 1234 + * + * // Load the user's post relations + * return user.loadRelations(['post']); + * }).then((user) => { + * console.log(user.posts); // [{...}, {...}, ...] + * }); + * + * @method Record#loadRelations + * @param {string[]} [relations] List of relations to load. Can use localField + * names or Mapper names to pick relations. + * @param {object} [opts] Configuration options. + * @returns {Promise} Resolves with the record, with the loaded relations now + * attached. + * @since 3.0.0 + */ + loadRelations: function loadRelations(relations, opts) { + var _this3 = this; + + var op = void 0; + var mapper = this._mapper(); + + // Default values for arguments + relations || (relations = []); + if (utils.isString(relations)) { + relations = [relations]; + } + opts || (opts = {}); + opts.with = relations; + + // Fill in "opts" with the Model's configuration + utils._(opts, mapper); + opts.adapter = mapper.getAdapterName(opts); + + // beforeLoadRelations lifecycle hook + op = opts.op = 'beforeLoadRelations'; + return utils.resolve(this[op](relations, opts)).then(function () { + // Now delegate to the adapter + op = opts.op = 'loadRelations'; + mapper.dbg(op, _this3, relations, opts); + var tasks = []; + var task = void 0; + utils.forEachRelation(mapper, opts, function (def, optsCopy) { + var relatedMapper = def.getRelation(); + optsCopy.raw = false; + if (utils.isFunction(def.load)) { + task = def.load(mapper, def, _this3, opts); + } else if (def.type === 'hasMany' || def.type === 'hasOne') { + if (def.foreignKey) { + task = superMethod(relatedMapper, 'findAll')(defineProperty({}, def.foreignKey, utils.get(_this3, mapper.idAttribute)), optsCopy).then(function (relatedData) { + if (def.type === 'hasOne') { + return relatedData.length ? relatedData[0] : undefined; + } + return relatedData; + }); + } else if (def.localKeys) { + task = superMethod(relatedMapper, 'findAll')({ + where: defineProperty({}, relatedMapper.idAttribute, { + 'in': utils.get(_this3, def.localKeys) + }) + }); + } else if (def.foreignKeys) { + task = superMethod(relatedMapper, 'findAll')({ + where: defineProperty({}, def.foreignKeys, { + 'contains': utils.get(_this3, mapper.idAttribute) + }) + }, opts); + } + } else if (def.type === 'belongsTo') { + var key = utils.get(_this3, def.foreignKey); + if (utils.isSorN(key)) { + task = superMethod(relatedMapper, 'find')(key, optsCopy); + } + } + if (task) { + task = task.then(function (relatedData) { + def.setLocalField(_this3, relatedData); + }); + tasks.push(task); + } + }); + return Promise.all(tasks); + }).then(function () { + // afterLoadRelations lifecycle hook + op = opts.op = 'afterLoadRelations'; + return utils.resolve(_this3[op](relations, opts)).then(function () { + return _this3; + }); + }); + }, + + + /** + * Return the properties with which this record was instantiated. + * + * @example Record#previous + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user'); + * const user = store.createRecord('user', { + * name: 'William' + * }); + * console.log('user previous: ' + JSON.stringify(user.previous())); + * user.name = 'Bob'; + * console.log('user previous: ' + JSON.stringify(user.previous())); + * user.commit(); + * console.log('user previous: ' + JSON.stringify(user.previous())); + * + * @method Record#previous + * @param {string} [key] If specified, return just the initial value of the + * given key. + * @returns {Object} The initial properties of this record. + * @since 3.0.0 + */ + previous: function previous(key) { + if (key) { + return this._get('previous.' + key); + } + return this._get('previous'); + }, + + + /** + * Revert changes to this record back to the properties it had when it was + * instantiated. + * + * @example Record#revert + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user'); + * const user = store.createRecord('user', { + * name: 'William' + * }); + * console.log('user: ' + JSON.stringify(user)); + * user.name = 'Bob'; + * console.log('user: ' + JSON.stringify(user)); + * user.revert(); + * console.log('user: ' + JSON.stringify(user)); + * + * @method Record#revert + * @param {object} [opts] Configuration options. + * @param {string[]} [opts.preserve] Array of strings or Regular Expressions + * denoting properties that should not be reverted. + * @since 3.0.0 + */ + revert: function revert(opts) { + var _this4 = this; + + var previous = this._get('previous'); + opts || (opts = {}); + opts.preserve || (opts.preserve = []); + utils.forOwn(this, function (value, key) { + if (key !== _this4._mapper().idAttribute && !previous.hasOwnProperty(key) && _this4.hasOwnProperty(key) && opts.preserve.indexOf(key) === -1) { + delete _this4[key]; + } + }); + utils.forOwn(previous, function (value, key) { + if (opts.preserve.indexOf(key) === -1) { + _this4[key] = value; + } + }); + this.commit(); + }, + + + /** + * Delegates to {@link Mapper#create} or {@link Mapper#update}. + * + * @example + * import { Container } from 'js-data'; + * import { RethinkDBAdapter } from 'js-data-rethinkdb'; + * + * const store = new Container(); + * store.registerAdapter('rethink', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('session'); + * const session = store.createRecord('session', { topic: 'Node.js' }); + * + * // Create a new record in the database + * session.save().then(() => { + * console.log(session.id); // 1234 + * + * session.skill_level = 'beginner'; + * + * // Update the record in the database + * return session.save(); + * }); + * + * @method Record#save + * @param {object} [opts] Configuration options. See {@link Mapper#create} and + * {@link Mapper#update}. + * @param {boolean} [opts.changesOnly] Equality function. Default uses `===`. + * @param {Function} [opts.equalsFn] Passed to {@link Record#changes} when + * `opts.changesOnly` is `true`. + * @param {array} [opts.ignore] Passed to {@link Record#changes} when + * `opts.changesOnly` is `true`. + * @returns {Promise} The result of calling {@link Mapper#create} or + * {@link Mapper#update}. + * @since 3.0.0 + */ + save: function save(opts) { + var _this5 = this; + + opts || (opts = {}); + var mapper = this._mapper(); + var id = utils.get(this, mapper.idAttribute); + var props = this; + + var postProcess = function postProcess(result) { + var record = opts.raw ? result.data : result; + if (record) { + utils.deepMixIn(_this5, record); + _this5.commit(); + } + return result; + }; + + if (id === undefined) { + return superMethod(mapper, 'create')(props, opts).then(postProcess); + } + if (opts.changesOnly) { + var changes = this.changes(opts); + props = {}; + utils.fillIn(props, changes.added); + utils.fillIn(props, changes.changed); + } + return superMethod(mapper, 'update')(id, props, opts).then(postProcess); + }, + + + /** + * Set the value for a given key, or the values for the given keys if "key" is + * an object. Triggers change events on those properties that have `track: true` + * in {@link Mapper#schema}. + * + * @example Record#set + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user'); + * + * const user = store.createRecord('user'); + * console.log('user: ' + JSON.stringify(user)); + * + * user.set('name', 'Bob'); + * console.log('user: ' + JSON.stringify(user)); + * + * user.set({ age: 30, role: 'admin' }); + * console.log('user: ' + JSON.stringify(user)); + * + * @fires Record#change + * @method Record#set + * @param {(string|Object)} key Key to set or hash of key-value pairs to set. + * @param {*} [value] Value to set for the given key. + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.silent=false] Whether to trigger change events. + * @since 3.0.0 + */ + 'set': function set$$1(key, value, opts) { + if (utils.isObject(key)) { + opts = value; + } + opts || (opts = {}); + if (opts.silent) { + this._set('silent', true); + } + utils.set(this, key, value); + if (!this._get('eventId')) { + this._set('silent'); // unset + } + }, + + + /** + * Return a plain object representation of this record. If the class from + * which this record was created has a Mapper, then {@link Mapper#toJSON} will + * be called with this record instead. + * + * @example Record#toJSON + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user', { + * schema: { + * properties: { + * name: { type: 'string' } + * } + * } + * }); + * + * const user = store.createRecord('user', { + * name: 'John', + * $$hashKey: '1234' + * }); + * console.log('user: ' + JSON.stringify(user.toJSON())); + * + * @method Record#toJSON + * @param {object} [opts] Configuration options. + * @param {string[]} [opts.with] Array of relation names or relation fields + * to include in the representation. Only available as an option if the class + * from which this record was created has a Mapper and this record resides in + * an instance of {@link DataStore}. + * @returns {Object} Plain object representation of this record. + * @since 3.0.0 + */ + toJSON: function toJSON(opts) { + var mapper = this.constructor.mapper; + if (mapper) { + return mapper.toJSON(this, opts); + } else { + var json = {}; + utils.forOwn(this, function (prop, key) { + json[key] = utils.plainCopy(prop); + }); + return json; + } + }, + + + /** + * Unset the value for a given key. Triggers change events on those properties + * that have `track: true` in {@link Mapper#schema}. + * + * @example Record#unset + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user'); + * + * const user = store.createRecord('user', { + * name: 'John' + * }); + * console.log('user: ' + JSON.stringify(user)); + * + * user.unset('name'); + * console.log('user: ' + JSON.stringify(user)); + * + * @method Record#unset + * @param {string} key Key to unset. + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.silent=false] Whether to trigger change events. + * @since 3.0.0 + */ + unset: function unset(key, opts) { + this.set(key, undefined, opts); + }, + + + /** + * Validate this record based on its current properties. + * + * @example Record#validate + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * const store = new Container(); + * store.defineMapper('user', { + * schema: { + * properties: { + * name: { type: 'string' } + * } + * } + * }); + * const user = store.createRecord('user', { + * name: 1234 + * }, { + * noValidate: true // this allows us to put the record into an invalid state + * }); + * console.log('user validation: ' + JSON.stringify(user.validate())); + * user.name = 'John'; + * console.log('user validation: ' + user.validate()); + * + * @method Record#validate + * @param {object} [opts] Configuration options. Passed to {@link Mapper#validate}. + * @returns {*} Array of errors or `undefined` if no errors. + * @since 3.0.0 + */ + validate: function validate(opts) { + return this._mapper().validate(this, opts); + } +}, { + creatingPath: creatingPath, + noValidatePath: noValidatePath$1, + keepChangeHistoryPath: keepChangeHistoryPath, + previousPath: previousPath +}); + +/** + * Allow records to emit events. + * + * An record's registered listeners are stored in the record's private data. + */ +utils.eventify(Record.prototype, function () { + return this._get('events'); +}, function (value) { + this._set('events', value); +}); + +/** + * Fired when a record changes. Only works for records that have tracked fields. + * See {@link Record~changeListener} on how to listen for this event. + * + * @event Record#change + * @see Record~changeListener + */ + +/** + * Callback signature for the {@link Record#event:change} event. + * + * @example + * function onChange (record, changes) { + * // do something + * } + * record.on('change', onChange); + * + * @callback Record~changeListener + * @param {Record} The Record that changed. + * @param {object} The changes. + * @see Record#event:change + * @since 3.0.0 + */ + +/** + * Create a subclass of this Record: + * @example Record.extend + * const JSData = require('js-data'); + * const { Record } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomRecordClass extends Record { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customRecord = new CustomRecordClass(); + * console.log(customRecord.foo()); + * console.log(CustomRecordClass.beep()); + * + * // Extend the class using alternate method. + * const OtherRecordClass = Record.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherRecord = new OtherRecordClass(); + * console.log(otherRecord.foo()); + * console.log(OtherRecordClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherRecordClass () { + * Record.call(this); + * this.created_at = new Date().getTime(); + * } + * Record.extend({ + * constructor: AnotherRecordClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const anotherRecord = new AnotherRecordClass(); + * console.log(anotherRecord.created_at); + * console.log(anotherRecord.foo()); + * console.log(AnotherRecordClass.beep()); + * + * @method Record.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this Record class. + * @since 3.0.0 + */ + +function sort(a, b, hashCode) { + // Short-circuit comparison if a and b are strictly equal + // This is absolutely necessary for indexed objects that + // don't have the idAttribute field + if (a === b) { + return 0; + } + if (hashCode) { + a = hashCode(a); + b = hashCode(b); + } + if (a === null && b === null || a === undefined && b === undefined) { + return -1; + } + + if (a === null || a === undefined) { + return -1; + } + + if (b === null || b === undefined) { + return 1; + } + + if (a < b) { + return -1; + } + + if (a > b) { + return 1; + } + + return 0; +} + +function insertAt(array, index, value) { + array.splice(index, 0, value); + return array; +} + +function removeAt(array, index) { + array.splice(index, 1); + return array; +} + +function binarySearch(array, value, field) { + var lo = 0; + var hi = array.length; + var compared = void 0; + var mid = void 0; + + while (lo < hi) { + mid = (lo + hi) / 2 | 0; + compared = sort(value, array[mid], field); + if (compared === 0) { + return { + found: true, + index: mid + }; + } else if (compared < 0) { + hi = mid; + } else { + lo = mid + 1; + } + } + + return { + found: false, + index: hi + }; +} + +// Copyright (c) 2015, InternalFX. + +// Permission to use, copy, modify, and/or distribute this software for any purpose with or +// without fee is hereby granted, provided that the above copyright notice and this permission +// notice appear in all copies. + +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO +// THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT +// SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR +// ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE +// USE OR PERFORMANCE OF THIS SOFTWARE. + +// Modifications +// Copyright 2015-2016 Jason Dobry +// +// Summary of modifications: +// Reworked dependencies so as to re-use code already in js-data +// Removed unused code +function Index(fieldList, opts) { + utils.classCallCheck(this, Index); + fieldList || (fieldList = []); + + if (!utils.isArray(fieldList)) { + throw new Error('fieldList must be an array.'); + } + + opts || (opts = {}); + this.fieldList = fieldList; + this.fieldGetter = opts.fieldGetter; + this.hashCode = opts.hashCode; + this.isIndex = true; + this.keys = []; + this.values = []; +} + +utils.addHiddenPropsToTarget(Index.prototype, { + 'set': function set(keyList, value) { + if (!utils.isArray(keyList)) { + keyList = [keyList]; + } + + var key = keyList.shift() || undefined; + var pos = binarySearch(this.keys, key); + + if (keyList.length === 0) { + if (pos.found) { + var dataLocation = binarySearch(this.values[pos.index], value, this.hashCode); + if (!dataLocation.found) { + insertAt(this.values[pos.index], dataLocation.index, value); + } + } else { + insertAt(this.keys, pos.index, key); + insertAt(this.values, pos.index, [value]); + } + } else { + if (pos.found) { + this.values[pos.index].set(keyList, value); + } else { + insertAt(this.keys, pos.index, key); + var newIndex = new Index([], { hashCode: this.hashCode }); + newIndex.set(keyList, value); + insertAt(this.values, pos.index, newIndex); + } + } + }, + 'get': function get(keyList) { + if (!utils.isArray(keyList)) { + keyList = [keyList]; + } + + var key = keyList.shift() || undefined; + var pos = binarySearch(this.keys, key); + + if (keyList.length === 0) { + if (pos.found) { + if (this.values[pos.index].isIndex) { + return this.values[pos.index].getAll(); + } else { + return this.values[pos.index].slice(); + } + } else { + return []; + } + } else { + if (pos.found) { + return this.values[pos.index].get(keyList); + } else { + return []; + } + } + }, + getAll: function getAll(opts) { + opts || (opts = {}); + var results = []; + var values = this.values; + if (opts.order === 'desc') { + for (var i = values.length - 1; i >= 0; i--) { + var value = values[i]; + if (value.isIndex) { + results = results.concat(value.getAll(opts)); + } else { + results = results.concat(value); + } + } + } else { + for (var _i = 0; _i < values.length; _i++) { + var _value = values[_i]; + if (_value.isIndex) { + results = results.concat(_value.getAll(opts)); + } else { + results = results.concat(_value); + } + } + } + return results; + }, + visitAll: function visitAll(cb, thisArg) { + this.values.forEach(function (value) { + if (value.isIndex) { + value.visitAll(cb, thisArg); + } else { + value.forEach(cb, thisArg); + } + }); + }, + between: function between(leftKeys, rightKeys, opts) { + opts || (opts = {}); + if (!utils.isArray(leftKeys)) { + leftKeys = [leftKeys]; + } + if (!utils.isArray(rightKeys)) { + rightKeys = [rightKeys]; + } + utils.fillIn(opts, { + leftInclusive: true, + rightInclusive: false, + limit: undefined, + offset: 0 + }); + + var results = this._between(leftKeys, rightKeys, opts); + + if (opts.limit) { + return results.slice(opts.offset, opts.limit + opts.offset); + } else { + return results.slice(opts.offset); + } + }, + _between: function _between(leftKeys, rightKeys, opts) { + var results = []; + + var leftKey = leftKeys.shift(); + var rightKey = rightKeys.shift(); + + var pos = void 0; + + if (leftKey !== undefined) { + pos = binarySearch(this.keys, leftKey); + } else { + pos = { + found: false, + index: 0 + }; + } + + if (leftKeys.length === 0) { + if (pos.found && opts.leftInclusive === false) { + pos.index += 1; + } + + for (var i = pos.index; i < this.keys.length; i += 1) { + if (rightKey !== undefined) { + if (opts.rightInclusive) { + if (this.keys[i] > rightKey) { + break; + } + } else { + if (this.keys[i] >= rightKey) { + break; + } + } + } + + if (this.values[i].isIndex) { + results = results.concat(this.values[i].getAll()); + } else { + results = results.concat(this.values[i]); + } + + if (opts.limit) { + if (results.length >= opts.limit + opts.offset) { + break; + } + } + } + } else { + for (var _i2 = pos.index; _i2 < this.keys.length; _i2 += 1) { + var currKey = this.keys[_i2]; + if (currKey > rightKey) { + break; + } + + if (this.values[_i2].isIndex) { + if (currKey === leftKey) { + results = results.concat(this.values[_i2]._between(utils.copy(leftKeys), rightKeys.map(function () { + return undefined; + }), opts)); + } else if (currKey === rightKey) { + results = results.concat(this.values[_i2]._between(leftKeys.map(function () { + return undefined; + }), utils.copy(rightKeys), opts)); + } else { + results = results.concat(this.values[_i2].getAll()); + } + } else { + results = results.concat(this.values[_i2]); + } + + if (opts.limit) { + if (results.length >= opts.limit + opts.offset) { + break; + } + } + } + } + + if (opts.limit) { + return results.slice(0, opts.limit + opts.offset); + } else { + return results; + } + }, + peek: function peek() { + if (this.values.length) { + if (this.values[0].isIndex) { + return this.values[0].peek(); + } else { + return this.values[0]; + } + } + return []; + }, + clear: function clear() { + this.keys = []; + this.values = []; + }, + insertRecord: function insertRecord(data) { + var keyList = this.fieldList.map(function (field) { + if (utils.isFunction(field)) { + return field(data) || undefined; + } else { + return data[field] || undefined; + } + }); + this.set(keyList, data); + }, + removeRecord: function removeRecord(data) { + var _this = this; + + var removed = void 0; + var isUnique = this.hashCode(data) !== undefined; + this.values.forEach(function (value, i) { + if (value.isIndex) { + if (value.removeRecord(data)) { + if (value.keys.length === 0) { + removeAt(_this.keys, i); + removeAt(_this.values, i); + } + removed = true; + return false; + } + } else { + var dataLocation = {}; + if (_this.keys[i] === undefined || !isUnique) { + for (var j = value.length - 1; j >= 0; j--) { + if (value[j] === data) { + dataLocation = { + found: true, + index: j + }; + break; + } + } + } else if (isUnique) { + dataLocation = binarySearch(value, data, _this.hashCode); + } + if (dataLocation.found) { + removeAt(value, dataLocation.index); + if (value.length === 0) { + removeAt(_this.keys, i); + removeAt(_this.values, i); + } + removed = true; + return false; + } + } + }); + return removed ? data : undefined; + }, + updateRecord: function updateRecord(data) { + var removed = this.removeRecord(data); + if (removed !== undefined) { + this.insertRecord(data); + } + } +}); + +var noValidatePath = Record$1.noValidatePath; + + +var DOMAIN$1 = 'Collection'; + +var COLLECTION_DEFAULTS = { + /** + * Whether to call {@link Record#commit} on records that are added to the + * collection and already exist in the collection. + * + * @name Collection#commitOnMerge + * @type {boolean} + * @default true + */ + commitOnMerge: true, + + /** + * Whether record events should bubble up and be emitted by the collection. + * + * @name Collection#emitRecordEvents + * @type {boolean} + * @default true + */ + emitRecordEvents: true, + + /** + * Field to be used as the unique identifier for records in this collection. + * Defaults to `"id"` unless {@link Collection#mapper} is set, in which case + * this will default to {@link Mapper#idAttribute}. + * + * @name Collection#idAttribute + * @type {string} + * @default "id" + */ + idAttribute: 'id', + + /** + * What to do when inserting a record into this Collection that shares a + * primary key with a record already in this Collection. + * + * Possible values: + * merge + * replace + * skip + * + * Merge: + * + * Recursively shallow copy properties from the new record onto the existing + * record. + * + * Replace: + * + * Shallow copy top-level properties from the new record onto the existing + * record. Any top-level own properties of the existing record that are _not_ + * on the new record will be removed. + * + * Skip: + * + * Ignore new record, keep existing record. + * + * @name Collection#onConflict + * @type {string} + * @default "merge" + */ + onConflict: 'merge' + + /** + * An ordered set of {@link Record} instances. + * + * @example Collection#constructor + * // import { Collection, Record } from 'js-data'; + * const JSData = require('js-data'); + * const {Collection, Record} = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const user1 = new Record({ id: 1 }); + * const user2 = new Record({ id: 2 }); + * const UserCollection = new Collection([user1, user2]); + * console.log(UserCollection.get(1) === user1); + * + * @class Collection + * @extends Component + * @param {array} [records] Initial set of records to insert into the + * collection. + * @param {object} [opts] Configuration options. + * @param {string} [opts.commitOnMerge] See {@link Collection#commitOnMerge}. + * @param {string} [opts.idAttribute] See {@link Collection#idAttribute}. + * @param {string} [opts.onConflict="merge"] See {@link Collection#onConflict}. + * @param {string} [opts.mapper] See {@link Collection#mapper}. + * @since 3.0.0 + */ +};function Collection(records, opts) { + utils.classCallCheck(this, Collection); + Component$1.call(this, opts); + + if (records && !utils.isArray(records)) { + opts = records; + records = []; + } + if (utils.isString(opts)) { + opts = { idAttribute: opts }; + } + + // Default values for arguments + records || (records = []); + opts || (opts = {}); + + Object.defineProperties(this, { + /** + * Default Mapper for this collection. Optional. If a Mapper is provided, then + * the collection will use the {@link Mapper#idAttribute} setting, and will + * wrap records in {@link Mapper#recordClass}. + * + * @example Collection#mapper + * const JSData = require('js-data'); + * const {Collection, Mapper} = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * class MyMapperClass extends Mapper { + * foo () { return 'bar'; } + * } + * const myMapper = new MyMapperClass({ name: 'myMapper' }); + * const collection = new Collection(null, { mapper: myMapper }); + * + * @name Collection#mapper + * @type {Mapper} + * @default null + * @since 3.0.0 + */ + mapper: { + value: undefined, + writable: true + }, + // Query class used by this collection + queryClass: { + value: undefined, + writable: true + } + }); + + // Apply user-provided configuration + utils.fillIn(this, opts); + // Fill in any missing options with the defaults + utils.fillIn(this, utils.copy(COLLECTION_DEFAULTS)); + + if (!this.queryClass) { + this.queryClass = Query$1; + } + + var idAttribute = this.recordId(); + + Object.defineProperties(this, { + /** + * The main index, which uses @{link Collection#recordId} as the key. + * + * @name Collection#index + * @type {Index} + */ + index: { + value: new Index([idAttribute], { + hashCode: function hashCode(obj) { + return utils.get(obj, idAttribute); + } + }) + }, + + /** + * Object that holds the secondary indexes of this collection. + * + * @name Collection#indexes + * @type {Object.} + */ + indexes: { + value: {} + } + }); + + // Insert initial data into the collection + if (utils.isObject(records) || utils.isArray(records) && records.length) { + this.add(records); + } +} + +var Collection$1 = Component$1.extend({ + constructor: Collection, + + /** + * Used to bind to events emitted by records in this Collection. + * + * @method Collection#_onRecordEvent + * @since 3.0.0 + * @private + * @param {...*} [arg] Args passed to {@link Collection#emit}. + */ + _onRecordEvent: function _onRecordEvent() { + if (this.emitRecordEvents) { + this.emit.apply(this, arguments); + } + }, + + + /** + * Insert the provided record or records. + * + * If a record is already in the collection then the provided record will + * either merge with or replace the existing record based on the value of the + * `onConflict` option. + * + * The collection's secondary indexes will be updated as each record is + * visited. + * + * @method Collection#add + * @since 3.0.0 + * @param {(Object|Object[]|Record|Record[])} data The record or records to insert. + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.commitOnMerge=true] See {@link Collection#commitOnMerge}. + * @param {boolean} [opts.noValidate] See {@link Record#noValidate}. + * @param {string} [opts.onConflict] See {@link Collection#onConflict}. + * @returns {(Object|Object[]|Record|Record[])} The added record or records. + */ + add: function add(records, opts) { + var _this = this; + + // Default values for arguments + opts || (opts = {}); + + // Fill in "opts" with the Collection's configuration + utils._(opts, this); + records = this.beforeAdd(records, opts) || records; + + // Track whether just one record or an array of records is being inserted + var singular = false; + var idAttribute = this.recordId(); + if (!utils.isArray(records)) { + if (utils.isObject(records)) { + records = [records]; + singular = true; + } else { + throw utils.err(DOMAIN$1 + '#add', 'records')(400, 'object or array', records); + } + } + + // Map the provided records to existing records. + // New records will be inserted. If any records map to existing records, + // they will be merged into the existing records according to the onConflict + // option. + records = records.map(function (record) { + var id = _this.recordId(record); + // Grab existing record if there is one + var existing = id === undefined ? id : _this.get(id); + // If the currently visited record is just a reference to an existing + // record, then there is nothing to be done. Exit early. + if (record === existing) { + return existing; + } + + if (existing) { + // Here, the currently visited record corresponds to a record already + // in the collection, so we need to merge them + var onConflict = opts.onConflict || _this.onConflict; + if (onConflict !== 'merge' && onConflict !== 'replace' && onConflict !== 'skip') { + throw utils.err(DOMAIN$1 + '#add', 'opts.onConflict')(400, 'one of (merge, replace, skip)', onConflict, true); + } + var existingNoValidate = existing._get(noValidatePath); + if (opts.noValidate) { + // Disable validation + existing._set(noValidatePath, true); + } + if (onConflict === 'merge') { + utils.deepMixIn(existing, record); + } else if (onConflict === 'replace') { + utils.forOwn(existing, function (value, key) { + if (key !== idAttribute && record[key] === undefined) { + existing[key] = undefined; + } + }); + existing.set(record); + } // else if(onConflict === 'skip'){ do nothing } + + if (opts.noValidate) { + // Restore previous `noValidate` value + existing._set(noValidatePath, existingNoValidate); + } + record = existing; + if (opts.commitOnMerge && utils.isFunction(record.commit)) { + record.commit(); + } + // Update all indexes in the collection + _this.updateIndexes(record); + } else { + // Here, the currently visted record does not correspond to any record + // in the collection, so (optionally) instantiate this record and insert + // it into the collection + record = _this.mapper ? _this.mapper.createRecord(record, opts) : record; + _this.index.insertRecord(record); + utils.forOwn(_this.indexes, function (index, name) { + index.insertRecord(record); + }); + if (record && utils.isFunction(record.on)) { + record.on('all', _this._onRecordEvent, _this); + } + } + return record; + }); + // Finally, return the inserted data + var result = singular ? records[0] : records; + if (!opts.silent) { + this.emit('add', result); + } + return this.afterAdd(records, opts, result) || result; + }, + + + /** + * Lifecycle hook called by {@link Collection#add}. If this method returns a + * value then {@link Collection#add} will return that same value. + * + * @method Collection#method + * @since 3.0.0 + * @param {(Object|Object[]|Record|Record[])} result The record or records + * that were added to this Collection by {@link Collection#add}. + * @param {object} opts The `opts` argument passed to {@link Collection#add}. + */ + afterAdd: function afterAdd() {}, + + + /** + * Lifecycle hook called by {@link Collection#remove}. If this method returns + * a value then {@link Collection#remove} will return that same value. + * + * @method Collection#afterRemove + * @since 3.0.0 + * @param {(string|number)} id The `id` argument passed to {@link Collection#remove}. + * @param {object} opts The `opts` argument passed to {@link Collection#remove}. + * @param {object} record The result that will be returned by {@link Collection#remove}. + */ + afterRemove: function afterRemove() {}, + + + /** + * Lifecycle hook called by {@link Collection#removeAll}. If this method + * returns a value then {@link Collection#removeAll} will return that same + * value. + * + * @method Collection#afterRemoveAll + * @since 3.0.0 + * @param {object} query The `query` argument passed to {@link Collection#removeAll}. + * @param {object} opts The `opts` argument passed to {@link Collection#removeAll}. + * @param {object} records The result that will be returned by {@link Collection#removeAll}. + */ + afterRemoveAll: function afterRemoveAll() {}, + + + /** + * Lifecycle hook called by {@link Collection#add}. If this method returns a + * value then the `records` argument in {@link Collection#add} will be + * re-assigned to the returned value. + * + * @method Collection#beforeAdd + * @since 3.0.0 + * @param {(Object|Object[]|Record|Record[])} records The `records` argument passed to {@link Collection#add}. + * @param {object} opts The `opts` argument passed to {@link Collection#add}. + */ + beforeAdd: function beforeAdd() {}, + + + /** + * Lifecycle hook called by {@link Collection#remove}. + * + * @method Collection#beforeRemove + * @since 3.0.0 + * @param {(string|number)} id The `id` argument passed to {@link Collection#remove}. + * @param {object} opts The `opts` argument passed to {@link Collection#remove}. + */ + beforeRemove: function beforeRemove() {}, + + + /** + * Lifecycle hook called by {@link Collection#removeAll}. + * + * @method Collection#beforeRemoveAll + * @since 3.0.0 + * @param {object} query The `query` argument passed to {@link Collection#removeAll}. + * @param {object} opts The `opts` argument passed to {@link Collection#removeAll}. + */ + beforeRemoveAll: function beforeRemoveAll() {}, + + + /** + * Find all records between two boundaries. + * + * Shortcut for `collection.query().between(18, 30, { index: 'age' }).run()` + * + * @example + * // Get all users ages 18 to 30 + * const users = collection.between(18, 30, { index: 'age' }); + * + * @example + * // Same as above + * const users = collection.between([18], [30], { index: 'age' }); + * + * @method Collection#between + * @since 3.0.0 + * @param {array} leftKeys Keys defining the left boundary. + * @param {array} rightKeys Keys defining the right boundary. + * @param {object} [opts] Configuration options. + * @param {string} [opts.index] Name of the secondary index to use in the + * query. If no index is specified, the main index is used. + * @param {boolean} [opts.leftInclusive=true] Whether to include records + * on the left boundary. + * @param {boolean} [opts.rightInclusive=false] Whether to include records + * on the left boundary. + * @param {boolean} [opts.limit] Limit the result to a certain number. + * @param {boolean} [opts.offset] The number of resulting records to skip. + * @returns {Object[]|Record[]} The result. + */ + between: function between(leftKeys, rightKeys, opts) { + return this.query().between(leftKeys, rightKeys, opts).run(); + }, + + + /** + * Create a new secondary index on the contents of the collection. + * + * @example + * // Index users by age + * collection.createIndex('age'); + * + * @example + * // Index users by status and role + * collection.createIndex('statusAndRole', ['status', 'role']); + * + * @method Collection#createIndex + * @since 3.0.0 + * @param {string} name The name of the new secondary index. + * @param {string[]} [fieldList] Array of field names to use as the key or + * compound key of the new secondary index. If no fieldList is provided, then + * the name will also be the field that is used to index the collection. + */ + createIndex: function createIndex(name, fieldList, opts) { + var _this2 = this; + + if (utils.isString(name) && fieldList === undefined) { + fieldList = [name]; + } + opts || (opts = {}); + opts.hashCode || (opts.hashCode = function (obj) { + return _this2.recordId(obj); + }); + var index = this.indexes[name] = new Index(fieldList, opts); + this.index.visitAll(index.insertRecord, index); + }, + + + /** + * Find the record or records that match the provided query or pass the + * provided filter function. + * + * Shortcut for `collection.query().filter(queryOrFn[, thisArg]).run()` + * + * @example Collection#filter + * const JSData = require('js-data'); + * const { Collection } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const collection = new Collection([ + * { id: 1, status: 'draft', created_at_timestamp: new Date().getTime() } + * ]); + * + * // Get the draft posts created less than three months ago + * let posts = collection.filter({ + * where: { + * status: { + * '==': 'draft' + * }, + * created_at_timestamp: { + * '>=': (new Date().getTime() - (1000 \* 60 \* 60 \* 24 \* 30 \* 3)) // 3 months ago + * } + * } + * }); + * console.log(posts); + * + * // Use a custom filter function + * posts = collection.filter((post) => post.id % 2 === 0); + * + * @method Collection#filter + * @param {(Object|Function)} [queryOrFn={}] Selection query or filter + * function. + * @param {object} [thisArg] Context to which to bind `queryOrFn` if + * `queryOrFn` is a function. + * @returns {Array} The result. + * @see query + * @since 3.0.0 + */ + filter: function filter(query, thisArg) { + return this.query().filter(query, thisArg).run(); + }, + + + /** + * Iterate over all records. + * + * @example + * collection.forEach(function (record) { + * // do something + * }); + * + * @method Collection#forEach + * @since 3.0.0 + * @param {Function} forEachFn Iteration function. + * @param {*} [thisArg] Context to which to bind `forEachFn`. + * @returns {Array} The result. + */ + forEach: function forEach(cb, thisArg) { + this.index.visitAll(cb, thisArg); + }, + + + /** + * Get the record with the given id. + * + * @method Collection#get + * @since 3.0.0 + * @param {(string|number)} id The primary key of the record to get. + * @returns {(Object|Record)} The record with the given id. + */ + get: function get(id) { + var instances = id === undefined ? [] : this.query().get(id).run(); + return instances.length ? instances[0] : undefined; + }, + + + /** + * Find the record or records that match the provided keyLists. + * + * Shortcut for `collection.query().getAll(keyList1, keyList2, ...).run()` + * + * @example + * // Get the posts where "status" is "draft" or "inReview" + * const posts = collection.getAll('draft', 'inReview', { index: 'status' }); + * + * @example + * // Same as above + * const posts = collection.getAll(['draft'], ['inReview'], { index: 'status' }); + * + * @method Collection#getAll + * @since 3.0.0 + * @param {...Array} [keyList] Provide one or more keyLists, and all + * records matching each keyList will be retrieved. If no keyLists are + * provided, all records will be returned. + * @param {object} [opts] Configuration options. + * @param {string} [opts.index] Name of the secondary index to use in the + * query. If no index is specified, the main index is used. + * @returns {Array} The result. + */ + getAll: function getAll() { + var _query; + + return (_query = this.query()).getAll.apply(_query, arguments).run(); + }, + + + /** + * Return the index with the given name. If no name is provided, return the + * main index. Throws an error if the specified index does not exist. + * + * @method Collection#getIndex + * @since 3.0.0 + * @param {string} [name] The name of the index to retrieve. + */ + getIndex: function getIndex(name) { + var index = name ? this.indexes[name] : this.index; + if (!index) { + throw utils.err(DOMAIN$1 + '#getIndex', name)(404, 'index'); + } + return index; + }, + + + /** + * Limit the result. + * + * Shortcut for `collection.query().limit(maximumNumber).run()` + * + * @example + * const posts = collection.limit(10); + * + * @method Collection#limit + * @since 3.0.0 + * @param {number} num The maximum number of records to keep in the result. + * @returns {Array} The result. + */ + limit: function limit(num) { + return this.query().limit(num).run(); + }, + + + /** + * Apply a mapping function to all records. + * + * @example + * const names = collection.map((user) => user.name); + * + * @method Collection#map + * @since 3.0.0 + * @param {Function} mapFn Mapping function. + * @param {*} [thisArg] Context to which to bind `mapFn`. + * @returns {Array} The result of the mapping. + */ + map: function map(cb, thisArg) { + var data = []; + this.index.visitAll(function (value) { + data.push(cb.call(thisArg, value)); + }); + return data; + }, + + + /** + * Return the result of calling the specified function on each record in this + * collection's main index. + * + * @method Collection#mapCall + * @since 3.0.0 + * @param {string} funcName Name of function to call + * @parama {...*} [args] Remaining arguments to be passed to the function. + * @returns {Array} The result. + */ + mapCall: function mapCall(funcName) { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + var data = []; + this.index.visitAll(function (record) { + data.push(record[funcName].apply(record, args)); + }); + return data; + }, + + + /** + * Return all "unsaved" (not uniquely identifiable) records in this colleciton. + * + * @method Collection#prune + * @param {object} [opts] Configuration options, passed to {@link Collection#removeAll}. + * @since 3.0.0 + * @returns {Array} The removed records, if any. + */ + prune: function prune(opts) { + return this.removeAll(this.unsaved(), opts); + }, + + + /** + * Create a new query to be executed against the contents of the collection. + * The result will be all or a subset of the contents of the collection. + * + * @example + * // Grab page 2 of users between ages 18 and 30 + * collection.query() + * .between(18, 30, { index: 'age' }) // between ages 18 and 30 + * .skip(10) // second page + * .limit(10) // page size + * .run(); + * + * @method Collection#query + * @since 3.0.0 + * @returns {Query} New query object. + */ + query: function query() { + var Ctor = this.queryClass; + return new Ctor(this); + }, + + + /** + * Return the primary key of the given, or if no record is provided, return the + * name of the field that holds the primary key of records in this Collection. + * + * @method Collection#recordId + * @since 3.0.0 + * @param {(Object|Record)} [record] The record whose primary key is to be + * returned. + * @returns {(string|number)} Primary key or name of field that holds primary + * key. + */ + recordId: function recordId(record) { + if (record) { + return utils.get(record, this.recordId()); + } + return this.mapper ? this.mapper.idAttribute : this.idAttribute; + }, + + + /** + * Reduce the data in the collection to a single value and return the result. + * + * @example + * const totalVotes = collection.reduce((prev, record) => { + * return prev + record.upVotes + record.downVotes; + * }, 0); + * + * @method Collection#reduce + * @since 3.0.0 + * @param {Function} cb Reduction callback. + * @param {*} initialValue Initial value of the reduction. + * @returns {*} The result. + */ + reduce: function reduce(cb, initialValue) { + var data = this.getAll(); + return data.reduce(cb, initialValue); + }, + + + /** + * Remove the record with the given id from this Collection. + * + * @method Collection#remove + * @since 3.0.0 + * @param {(string|number|object|Record)} idOrRecord The primary key of the + * record to be removed, or a reference to the record that is to be removed. + * @param {object} [opts] Configuration options. + * @returns {Object|Record} The removed record, if any. + */ + remove: function remove(idOrRecord, opts) { + // Default values for arguments + opts || (opts = {}); + this.beforeRemove(idOrRecord, opts); + var record = utils.isSorN(idOrRecord) ? this.get(idOrRecord) : idOrRecord; + + // The record is in the collection, remove it + if (utils.isObject(record)) { + record = this.index.removeRecord(record); + if (record) { + utils.forOwn(this.indexes, function (index, name) { + index.removeRecord(record); + }); + if (utils.isFunction(record.off)) { + record.off('all', this._onRecordEvent, this); + if (!opts.silent) { + this.emit('remove', record); + } + } + } + } + return this.afterRemove(idOrRecord, opts, record) || record; + }, + + + /** + * Remove from this collection the given records or the records selected by + * the given "query". + * + * @method Collection#removeAll + * @since 3.0.0 + * @param {Object|Object[]|Record[]} [queryOrRecords={}] Records to be removed or selection query. See {@link query}. + * @param {object} [queryOrRecords.where] See {@link query.where}. + * @param {number} [queryOrRecords.offset] See {@link query.offset}. + * @param {number} [queryOrRecords.limit] See {@link query.limit}. + * @param {string|Array[]} [queryOrRecords.orderBy] See {@link query.orderBy}. + * @param {object} [opts] Configuration options. + * @returns {(Object[]|Record[])} The removed records, if any. + */ + removeAll: function removeAll(queryOrRecords, opts) { + var _this3 = this; + + // Default values for arguments + opts || (opts = {}); + this.beforeRemoveAll(queryOrRecords, opts); + var records = utils.isArray(queryOrRecords) ? queryOrRecords.slice() : this.filter(queryOrRecords); + + // Remove each selected record from the collection + var optsCopy = utils.plainCopy(opts); + optsCopy.silent = true; + records = records.map(function (record) { + return _this3.remove(record, optsCopy); + }).filter(function (record) { + return record; + }); + if (!opts.silent) { + this.emit('remove', records); + } + return this.afterRemoveAll(queryOrRecords, opts, records) || records; + }, + + + /** + * Skip a number of results. + * + * Shortcut for `collection.query().skip(numberToSkip).run()` + * + * @example + * const posts = collection.skip(10); + * + * @method Collection#skip + * @since 3.0.0 + * @param {number} num The number of records to skip. + * @returns {Array} The result. + */ + skip: function skip(num) { + return this.query().skip(num).run(); + }, + + + /** + * Return the plain JSON representation of all items in this collection. + * Assumes records in this collection have a toJSON method. + * + * @method Collection#toJSON + * @since 3.0.0 + * @param {object} [opts] Configuration options. + * @param {string[]} [opts.with] Array of relation names or relation fields + * to include in the representation. + * @returns {Array} The records. + */ + toJSON: function toJSON(opts) { + return this.mapCall('toJSON', opts); + }, + + + /** + * Return all "unsaved" (not uniquely identifiable) records in this colleciton. + * + * @method Collection#unsaved + * @since 3.0.0 + * @returns {Array} The unsaved records, if any. + */ + unsaved: function unsaved(opts) { + return this.index.get(); + }, + + + /** + * Update a record's position in a single index of this collection. See + * {@link Collection#updateIndexes} to update a record's position in all + * indexes at once. + * + * @method Collection#updateIndex + * @since 3.0.0 + * @param {object} record The record to update. + * @param {object} [opts] Configuration options. + * @param {string} [opts.index] The index in which to update the record's + * position. If you don't specify an index then the record will be updated + * in the main index. + */ + updateIndex: function updateIndex(record, opts) { + opts || (opts = {}); + this.getIndex(opts.index).updateRecord(record); + }, + + + /** + * Updates all indexes in this collection for the provided record. Has no + * effect if the record is not in the collection. + * + * @method Collection#updateIndexes + * @since 3.0.0 + * @param {object} record TODO + */ + updateIndexes: function updateIndexes(record) { + this.index.updateRecord(record); + utils.forOwn(this.indexes, function (index, name) { + index.updateRecord(record); + }); + } +}); + +/** + * Fired when a record changes. Only works for records that have tracked changes. + * See {@link Collection~changeListener} on how to listen for this event. + * + * @event Collection#change + * @see Collection~changeListener + */ + +/** + * Callback signature for the {@link Collection#event:change} event. + * + * @example + * function onChange (record, changes) { + * // do something + * } + * collection.on('change', onChange); + * + * @callback Collection~changeListener + * @param {Record} The Record that changed. + * @param {object} The changes. + * @see Collection#event:change + * @since 3.0.0 + */ + +/** + * Fired when one or more records are added to the Collection. See + * {@link Collection~addListener} on how to listen for this event. + * + * @event Collection#add + * @see Collection~addListener + * @see Collection#event:add + * @see Collection#add + */ + +/** + * Callback signature for the {@link Collection#event:add} event. + * + * @example + * function onAdd (recordOrRecords) { + * // do something + * } + * collection.on('add', onAdd); + * + * @callback Collection~addListener + * @param {Record|Record[]} The Record or Records that were added. + * @see Collection#event:add + * @see Collection#add + * @since 3.0.0 + */ + +/** + * Fired when one or more records are removed from the Collection. See + * {@link Collection~removeListener} for how to listen for this event. + * + * @event Collection#remove + * @see Collection~removeListener + * @see Collection#event:remove + * @see Collection#remove + * @see Collection#removeAll + */ + +/** + * Callback signature for the {@link Collection#event:remove} event. + * + * @example + * function onRemove (recordsOrRecords) { + * // do something + * } + * collection.on('remove', onRemove); + * + * @callback Collection~removeListener + * @param {Record|Record[]} Record or Records that were removed. + * @see Collection#event:remove + * @see Collection#remove + * @see Collection#removeAll + * @since 3.0.0 + */ + +/** + * Create a subclass of this Collection: + * @example Collection.extend + * const JSData = require('js-data'); + * const { Collection } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomCollectionClass extends Collection { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customCollection = new CustomCollectionClass(); + * console.log(customCollection.foo()); + * console.log(CustomCollectionClass.beep()); + * + * // Extend the class using alternate method. + * const OtherCollectionClass = Collection.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherCollection = new OtherCollectionClass(); + * console.log(otherCollection.foo()); + * console.log(OtherCollectionClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherCollectionClass () { + * Collection.call(this); + * this.created_at = new Date().getTime(); + * } + * Collection.extend({ + * constructor: AnotherCollectionClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const anotherCollection = new AnotherCollectionClass(); + * console.log(anotherCollection.created_at); + * console.log(anotherCollection.foo()); + * console.log(AnotherCollectionClass.beep()); + * + * @method Collection.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this Collection class. + * @since 3.0.0 + */ + +var DOMAIN$7 = 'Schema'; + +/** + * A function map for each of the seven primitive JSON types defined by the core specification. + * Each function will check a given value and return true or false if the value is an instance of that type. + * ``` + * types.integer(1) // returns true + * types.string({}) // returns false + * ``` + * http://json-schema.org/latest/json-schema-core.html#anchor8 + * @name Schema.types + * @type {object} + */ +var types = { + array: utils.isArray, + boolean: utils.isBoolean, + integer: utils.isInteger, + 'null': utils.isNull, + number: utils.isNumber, + object: utils.isObject, + string: utils.isString + + /** + * @ignore + */ +};var segmentToString = function segmentToString(segment, prev) { + var str = ''; + if (segment) { + if (utils.isNumber(segment)) { + str += '[' + segment + ']'; + } else if (prev) { + str += '.' + segment; + } else { + str += '' + segment; + } + } + return str; +}; + +/** + * @ignore + */ +var makePath = function makePath(opts) { + opts || (opts = {}); + var path = ''; + var segments = opts.path || []; + segments.forEach(function (segment) { + path += segmentToString(segment, path); + }); + path += segmentToString(opts.prop, path); + return path; +}; + +/** + * @ignore + */ +var makeError = function makeError(actual, expected, opts) { + return { + expected: expected, + actual: '' + actual, + path: makePath(opts) + }; +}; + +/** + * @ignore + */ +var addError = function addError(actual, expected, opts, errors) { + errors.push(makeError(actual, expected, opts)); +}; + +/** + * @ignore + */ +var maxLengthCommon = function maxLengthCommon(keyword, value, schema, opts) { + var max = schema[keyword]; + if (value.length > max) { + return makeError(value.length, 'length no more than ' + max, opts); + } +}; + +/** + * @ignore + */ +var minLengthCommon = function minLengthCommon(keyword, value, schema, opts) { + var min = schema[keyword]; + if (value.length < min) { + return makeError(value.length, 'length no less than ' + min, opts); + } +}; + +/** + * A map of all object member validation functions for each keyword defined in the JSON Schema. + * @name Schema.validationKeywords + * @type {object} + */ +var validationKeywords = { + /** + * Validates the provided value against all schemas defined in the Schemas `allOf` keyword. + * The instance is valid against if and only if it is valid against all the schemas declared in the Schema's value. + * + * The value of this keyword MUST be an array. This array MUST have at least one element. + * Each element of this array MUST be a valid JSON Schema. + * + * see http://json-schema.org/latest/json-schema-validation.html#anchor82 + * + * @name Schema.validationKeywords.allOf + * @method + * @param {*} value Value to be validated. + * @param {object} schema Schema containing the `allOf` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + allOf: function allOf(value, schema, opts) { + var allErrors = []; + schema.allOf.forEach(function (_schema) { + allErrors = allErrors.concat(_validate(value, _schema, opts) || []); + }); + return allErrors.length ? allErrors : undefined; + }, + + + /** + * Validates the provided value against all schemas defined in the Schemas `anyOf` keyword. + * The instance is valid against this keyword if and only if it is valid against + * at least one of the schemas in this keyword's value. + * + * The value of this keyword MUST be an array. This array MUST have at least one element. + * Each element of this array MUST be an object, and each object MUST be a valid JSON Schema. + * see http://json-schema.org/latest/json-schema-validation.html#anchor85 + * + * @name Schema.validationKeywords.anyOf + * @method + * @param {*} value Value to be validated. + * @param {object} schema Schema containing the `anyOf` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + anyOf: function anyOf(value, schema, opts) { + var validated = false; + var allErrors = []; + schema.anyOf.forEach(function (_schema) { + var errors = _validate(value, _schema, opts); + if (errors) { + allErrors = allErrors.concat(errors); + } else { + validated = true; + } + }); + return validated ? undefined : allErrors; + }, + + + /** + * http://json-schema.org/latest/json-schema-validation.html#anchor70 + * + * @name Schema.validationKeywords.dependencies + * @method + * @param {*} value TODO + * @param {object} schema TODO + * @param {object} opts TODO + */ + dependencies: function dependencies(value, schema, opts) { + // TODO + }, + + + /** + * Validates the provided value against an array of possible values defined by the Schema's `enum` keyword + * Validation succeeds if the value is deeply equal to one of the values in the array. + * see http://json-schema.org/latest/json-schema-validation.html#anchor76 + * + * @name Schema.validationKeywords.enum + * @method + * @param {*} value Value to validate + * @param {object} schema Schema containing the `enum` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + enum: function _enum(value, schema, opts) { + var possibleValues = schema['enum']; + if (utils.findIndex(possibleValues, function (item) { + return utils.deepEqual(item, value); + }) === -1) { + return makeError(value, 'one of (' + possibleValues.join(', ') + ')', opts); + } + }, + + + /** + * Validates each of the provided array values against a schema or an array of schemas defined by the Schema's `items` keyword + * see http://json-schema.org/latest/json-schema-validation.html#anchor37 for validation rules. + * + * @name Schema.validationKeywords.items + * @method + * @param {*} value Array to be validated. + * @param {object} schema Schema containing the items keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + items: function items(value, schema, opts) { + opts || (opts = {}); + // TODO: additionalItems + var items = schema.items; + var errors = []; + var checkingTuple = utils.isArray(items); + var length = value.length; + for (var prop = 0; prop < length; prop++) { + if (checkingTuple) { + // Validating a tuple, instead of just checking each item against the + // same schema + items = schema.items[prop]; + } + opts.prop = prop; + errors = errors.concat(_validate(value[prop], items, opts) || []); + } + return errors.length ? errors : undefined; + }, + + + /** + * Validates the provided number against a maximum value defined by the Schema's `maximum` keyword + * Validation succeeds if the value is a number, and is less than, or equal to, the value of this keyword. + * http://json-schema.org/latest/json-schema-validation.html#anchor17 + * + * @name Schema.validationKeywords.maximum + * @method + * @param {*} value Number to validate against the keyword. + * @param {object} schema Schema containing the `maximum` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + maximum: function maximum(value, schema, opts) { + // Must be a number + var maximum = schema.maximum; + // Must be a boolean + // Depends on maximum + // default: false + var exclusiveMaximum = schema.exclusiveMaximum; + if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === (typeof maximum === 'undefined' ? 'undefined' : _typeof(maximum)) && !(exclusiveMaximum ? maximum > value : maximum >= value)) { + return exclusiveMaximum ? makeError(value, 'no more than nor equal to ' + maximum, opts) : makeError(value, 'no more than ' + maximum, opts); + } + }, + + + /** + * Validates the length of the provided array against a maximum value defined by the Schema's `maxItems` keyword. + * Validation succeeds if the length of the array is less than, or equal to the value of this keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor42 + * + * @name Schema.validationKeywords.maxItems + * @method + * @param {*} value Array to be validated. + * @param {object} schema Schema containing the `maxItems` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + maxItems: function maxItems(value, schema, opts) { + if (utils.isArray(value)) { + return maxLengthCommon('maxItems', value, schema, opts); + } + }, + + + /** + * Validates the length of the provided string against a maximum value defined in the Schema's `maxLength` keyword. + * Validation succeeds if the length of the string is less than, or equal to the value of this keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor26 + * + * @name Schema.validationKeywords.maxLength + * @method + * @param {*} value String to be validated. + * @param {object} schema Schema containing the `maxLength` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + maxLength: function maxLength(value, schema, opts) { + return maxLengthCommon('maxLength', value, schema, opts); + }, + + + /** + * Validates the count of the provided object's properties against a maximum value defined in the Schema's `maxProperties` keyword. + * Validation succeeds if the object's property count is less than, or equal to the value of this keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor54 + * + * @name Schema.validationKeywords.maxProperties + * @method + * @param {*} value Object to be validated. + * @param {object} schema Schema containing the `maxProperties` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + maxProperties: function maxProperties(value, schema, opts) { + // validate only objects + if (!utils.isObject(value)) return; + var maxProperties = schema.maxProperties; + var length = Object.keys(value).length; + if (length > maxProperties) { + return makeError(length, 'no more than ' + maxProperties + ' properties', opts); + } + }, + + + /** + * Validates the provided value against a minimum value defined by the Schema's `minimum` keyword + * Validation succeeds if the value is a number and is greater than, or equal to, the value of this keyword. + * http://json-schema.org/latest/json-schema-validation.html#anchor21 + * + * @name Schema.validationKeywords.minimum + * @method + * @param {*} value Number to validate against the keyword. + * @param {object} schema Schema containing the `minimum` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + minimum: function minimum(value, schema, opts) { + // Must be a number + var minimum = schema.minimum; + // Must be a boolean + // Depends on minimum + // default: false + var exclusiveMinimum = schema.exclusiveMinimum; + if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === (typeof minimum === 'undefined' ? 'undefined' : _typeof(minimum)) && !(exclusiveMinimum ? value > minimum : value >= minimum)) { + return exclusiveMinimum ? makeError(value, 'no less than nor equal to ' + minimum, opts) : makeError(value, 'no less than ' + minimum, opts); + } + }, + + + /** + * Validates the length of the provided array against a minimum value defined by the Schema's `minItems` keyword. + * Validation succeeds if the length of the array is greater than, or equal to the value of this keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor45 + * + * @name Schema.validationKeywords.minItems + * @method + * @param {*} value Array to be validated. + * @param {object} schema Schema containing the `minItems` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + minItems: function minItems(value, schema, opts) { + if (utils.isArray(value)) { + return minLengthCommon('minItems', value, schema, opts); + } + }, + + + /** + * Validates the length of the provided string against a minimum value defined in the Schema's `minLength` keyword. + * Validation succeeds if the length of the string is greater than, or equal to the value of this keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor29 + * + * @name Schema.validationKeywords.minLength + * @method + * @param {*} value String to be validated. + * @param {object} schema Schema containing the `minLength` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + minLength: function minLength(value, schema, opts) { + return minLengthCommon('minLength', value, schema, opts); + }, + + + /** + * Validates the count of the provided object's properties against a minimum value defined in the Schema's `minProperties` keyword. + * Validation succeeds if the object's property count is greater than, or equal to the value of this keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor57 + * + * @name Schema.validationKeywords.minProperties + * @method + * @param {*} value Object to be validated. + * @param {object} schema Schema containing the `minProperties` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + minProperties: function minProperties(value, schema, opts) { + // validate only objects + if (!utils.isObject(value)) return; + var minProperties = schema.minProperties; + var length = Object.keys(value).length; + if (length < minProperties) { + return makeError(length, 'no more than ' + minProperties + ' properties', opts); + } + }, + + + /** + * Validates the provided number is a multiple of the number defined in the Schema's `multipleOf` keyword. + * Validation succeeds if the number can be divided equally into the value of this keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor14 + * + * @name Schema.validationKeywords.multipleOf + * @method + * @param {*} value Number to be validated. + * @param {object} schema Schema containing the `multipleOf` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + multipleOf: function multipleOf(value, schema, opts) { + var multipleOf = schema.multipleOf; + if (utils.isNumber(value)) { + if (value / multipleOf % 1 !== 0) { + return makeError(value, 'multipleOf ' + multipleOf, opts); + } + } + }, + + + /** + * Validates the provided value is not valid with any of the schemas defined in the Schema's `not` keyword. + * An instance is valid against this keyword if and only if it is NOT valid against the schemas in this keyword's value. + * + * see http://json-schema.org/latest/json-schema-validation.html#anchor91 + * @name Schema.validationKeywords.not + * @method + * @param {*} value to be checked. + * @param {object} schema Schema containing the not keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + not: function not(value, schema, opts) { + if (!_validate(value, schema.not, opts)) { + // TODO: better messaging + return makeError('succeeded', 'should have failed', opts); + } + }, + + + /** + * Validates the provided value is valid with one and only one of the schemas defined in the Schema's `oneOf` keyword. + * An instance is valid against this keyword if and only if it is valid against a single schemas in this keyword's value. + * + * see http://json-schema.org/latest/json-schema-validation.html#anchor88 + * @name Schema.validationKeywords.oneOf + * @method + * @param {*} value to be checked. + * @param {object} schema Schema containing the `oneOf` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + oneOf: function oneOf(value, schema, opts) { + var validated = false; + var allErrors = []; + schema.oneOf.forEach(function (_schema) { + var errors = _validate(value, _schema, opts); + if (errors) { + allErrors = allErrors.concat(errors); + } else if (validated) { + allErrors = [makeError('valid against more than one', 'valid against only one', opts)]; + validated = false; + return false; + } else { + validated = true; + } + }); + return validated ? undefined : allErrors; + }, + + + /** + * Validates the provided string matches a pattern defined in the Schema's `pattern` keyword. + * Validation succeeds if the string is a match of the regex value of this keyword. + * + * see http://json-schema.org/latest/json-schema-validation.html#anchor33 + * @name Schema.validationKeywords.pattern + * @method + * @param {*} value String to be validated. + * @param {object} schema Schema containing the `pattern` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + pattern: function pattern(value, schema, opts) { + var pattern = schema.pattern; + if (utils.isString(value) && !value.match(pattern)) { + return makeError(value, pattern, opts); + } + }, + + + /** + * Validates the provided object's properties against a map of values defined in the Schema's `properties` keyword. + * Validation succeeds if the object's property are valid with each of the schema's in the provided map. + * Validation also depends on the additionalProperties and or patternProperties. + * + * see http://json-schema.org/latest/json-schema-validation.html#anchor64 for more info. + * + * @name Schema.validationKeywords.properties + * @method + * @param {*} value Object to be validated. + * @param {object} schema Schema containing the `properties` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + properties: function properties(value, schema, opts) { + opts || (opts = {}); + + if (utils.isArray(value)) { + return; + } + + // Can be a boolean or an object + // Technically the default is an "empty schema", but here "true" is + // functionally the same + var additionalProperties = schema.additionalProperties === undefined ? true : schema.additionalProperties; + var validated = []; + // "p": The property set from "properties". + // Default is an object + var properties = schema.properties || {}; + // "pp": The property set from "patternProperties". + // Default is an object + var patternProperties = schema.patternProperties || {}; + var errors = []; + + utils.forOwn(properties, function (_schema, prop) { + opts.prop = prop; + errors = errors.concat(_validate(value[prop], _schema, opts) || []); + validated.push(prop); + }); + + var toValidate = utils.omit(value, validated); + utils.forOwn(patternProperties, function (_schema, pattern) { + utils.forOwn(toValidate, function (undef, prop) { + if (prop.match(pattern)) { + opts.prop = prop; + errors = errors.concat(_validate(value[prop], _schema, opts) || []); + validated.push(prop); + } + }); + }); + var keys = Object.keys(utils.omit(value, validated)); + // If "s" is not empty, validation fails + if (additionalProperties === false) { + if (keys.length) { + var origProp = opts.prop; + opts.prop = ''; + addError('extra fields: ' + keys.join(', '), 'no extra fields', opts, errors); + opts.prop = origProp; + } + } else if (utils.isObject(additionalProperties)) { + // Otherwise, validate according to provided schema + keys.forEach(function (prop) { + opts.prop = prop; + errors = errors.concat(_validate(value[prop], additionalProperties, opts) || []); + }); + } + return errors.length ? errors : undefined; + }, + + + /** + * Validates the provided object's has all properties listed in the Schema's `properties` keyword array. + * Validation succeeds if the object contains all properties provided in the array value of this keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor61 + * + * @name Schema.validationKeywords.required + * @method + * @param {*} value Object to be validated. + * @param {object} schema Schema containing the `required` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + required: function required(value, schema, opts) { + opts || (opts = {}); + var required = schema.required; + var errors = []; + if (!opts.existingOnly) { + required.forEach(function (prop) { + if (utils.get(value, prop) === undefined) { + var prevProp = opts.prop; + opts.prop = prop; + addError(undefined, 'a value', opts, errors); + opts.prop = prevProp; + } + }); + } + return errors.length ? errors : undefined; + }, + + + /** + * Validates the provided value's type is equal to the type, or array of types, defined in the Schema's `type` keyword. + * see http://json-schema.org/latest/json-schema-validation.html#anchor79 + * + * @name Schema.validationKeywords.type + * @method + * @param {*} value Value to be validated. + * @param {object} schema Schema containing the `type` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + type: function type(value, schema, opts) { + var type = schema.type; + var validType = void 0; + // Can be one of several types + if (utils.isString(type)) { + type = [type]; + } + // Try to match the value against an expected type + type.forEach(function (_type) { + // TODO: throw an error if type is not defined + if (types[_type](value, schema, opts)) { + // Matched a type + validType = _type; + return false; + } + }); + // Value did not match any expected type + if (!validType) { + return makeError(value !== undefined && value !== null ? typeof value === 'undefined' ? 'undefined' : _typeof(value) : '' + value, 'one of (' + type.join(', ') + ')', opts); + } + // Run keyword validators for matched type + // http://json-schema.org/latest/json-schema-validation.html#anchor12 + var validator = typeGroupValidators[validType]; + if (validator) { + return validator(value, schema, opts); + } + }, + + + /** + * Validates the provided array values are unique. + * Validation succeeds if the items in the array are unique, but only if the value of this keyword is true + * see http://json-schema.org/latest/json-schema-validation.html#anchor49 + * + * @name Schema.validationKeywords.uniqueItems + * @method + * @param {*} value Array to be validated. + * @param {object} schema Schema containing the `uniqueItems` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + uniqueItems: function uniqueItems(value, schema, opts) { + if (value && value.length && schema.uniqueItems) { + var length = value.length; + var item = void 0, + i = void 0, + j = void 0; + // Check n - 1 items + for (i = length - 1; i > 0; i--) { + item = value[i]; + // Only compare against unchecked items + for (j = i - 1; j >= 0; j--) { + // Found a duplicate + if (utils.deepEqual(item, value[j])) { + return makeError(item, 'no duplicates', opts); + } + } + } + } + } +}; + +/** + * @ignore + */ +var runOps = function runOps(ops, value, schema, opts) { + var errors = []; + ops.forEach(function (op) { + if (schema[op] !== undefined) { + errors = errors.concat(validationKeywords[op](value, schema, opts) || []); + } + }); + return errors.length ? errors : undefined; +}; + +/** + * Validation keywords validated for any type: + * + * - `enum` + * - `type` + * - `allOf` + * - `anyOf` + * - `oneOf` + * - `not` + * + * @name Schema.ANY_OPS + * @type {string[]} + */ +var ANY_OPS = ['enum', 'type', 'allOf', 'anyOf', 'oneOf', 'not']; + +/** + * Validation keywords validated for array types: + * + * - `items` + * - `maxItems` + * - `minItems` + * - `uniqueItems` + * + * @name Schema.ARRAY_OPS + * @type {string[]} + */ +var ARRAY_OPS = ['items', 'maxItems', 'minItems', 'uniqueItems']; + +/** + * Validation keywords validated for numeric (number and integer) types: + * + * - `multipleOf` + * - `maximum` + * - `minimum` + * + * @name Schema.NUMERIC_OPS + * @type {string[]} + */ +var NUMERIC_OPS = ['multipleOf', 'maximum', 'minimum']; + +/** + * Validation keywords validated for object types: + * + * - `maxProperties` + * - `minProperties` + * - `required` + * - `properties` + * - `dependencies` + * + * @name Schema.OBJECT_OPS + * @type {string[]} + */ +var OBJECT_OPS = ['maxProperties', 'minProperties', 'required', 'properties', 'dependencies']; + +/** + * Validation keywords validated for string types: + * + * - `maxLength` + * - `minLength` + * - `pattern` + * + * @name Schema.STRING_OPS + * @type {string[]} + */ +var STRING_OPS = ['maxLength', 'minLength', 'pattern']; + +/** + * http://json-schema.org/latest/json-schema-validation.html#anchor75 + * @ignore + */ +var validateAny = function validateAny(value, schema, opts) { + return runOps(ANY_OPS, value, schema, opts); +}; + +/** + * Validates the provided value against a given Schema according to the http://json-schema.org/ v4 specification. + * + * @name Schema.validate + * @method + * @param {*} value Value to be validated. + * @param {object} schema Valid Schema according to the http://json-schema.org/ v4 specification. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ +var _validate = function _validate(value, schema, opts) { + var errors = []; + opts || (opts = {}); + opts.ctx || (opts.ctx = { value: value, schema: schema }); + var shouldPop = void 0; + var prevProp = opts.prop; + if (schema === undefined) { + return; + } + if (!utils.isObject(schema)) { + throw utils.err(DOMAIN$7 + '#validate')(500, 'Invalid schema at path: "' + opts.path + '"'); + } + if (opts.path === undefined) { + opts.path = []; + } + // Track our location as we recurse + if (opts.prop !== undefined) { + shouldPop = true; + opts.path.push(opts.prop); + opts.prop = undefined; + } + // Validate against parent schema + if (schema['extends']) { + // opts.path = path + // opts.prop = prop + if (utils.isFunction(schema['extends'].validate)) { + errors = errors.concat(schema['extends'].validate(value, opts) || []); + } else { + errors = errors.concat(_validate(value, schema['extends'], opts) || []); + } + } + if (value === undefined) { + // Check if property is required + if (schema.required === true && !opts.existingOnly) { + addError(value, 'a value', opts, errors); + } + if (shouldPop) { + opts.path.pop(); + opts.prop = prevProp; + } + return errors.length ? errors : undefined; + } + + errors = errors.concat(validateAny(value, schema, opts) || []); + if (shouldPop) { + opts.path.pop(); + opts.prop = prevProp; + } + return errors.length ? errors : undefined; +}; + +// These strings are cached for optimal performance of the change detection +// boolean - Whether a Record is changing in the current execution frame +var changingPath = 'changing'; +// string[] - Properties that have changed in the current execution frame +var changedPath = 'changed'; +// Object[] - History of change records +var changeHistoryPath = 'history'; +// boolean - Whether a Record is currently being instantiated +var creatingPath$1 = 'creating'; +// number - The setTimeout change event id of a Record, if any +var eventIdPath = 'eventId'; +// boolean - Whether to skip validation for a Record's currently changing property +var noValidatePath$2 = 'noValidate'; +// boolean - Whether to preserve Change History for a Record +var keepChangeHistoryPath$1 = 'keepChangeHistory'; +// boolean - Whether to skip change notification for a Record's currently +// changing property +var silentPath = 'silent'; +var validationFailureMsg = 'validation failed'; + +/** + * A map of validation functions grouped by type. + * + * @name Schema.typeGroupValidators + * @type {object} + */ +var typeGroupValidators = { + /** + * Validates the provided value against the schema using all of the validation keywords specific to instances of an array. + * The validation keywords for the type `array` are: + *``` + * ['items', 'maxItems', 'minItems', 'uniqueItems'] + *``` + * see http://json-schema.org/latest/json-schema-validation.html#anchor25 + * + * @name Schema.typeGroupValidators.array + * @method + * @param {*} value Array to be validated. + * @param {object} schema Schema containing at least one array keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + array: function array(value, schema, opts) { + return runOps(ARRAY_OPS, value, schema, opts); + }, + + /** + * Validates the provided value against the schema using all of the validation keywords specific to instances of an integer. + * The validation keywords for the type `integer` are: + *``` + * ['multipleOf', 'maximum', 'minimum'] + *``` + * @name Schema.typeGroupValidators.integer + * @method + * @param {*} value Number to be validated. + * @param {object} schema Schema containing at least one `integer` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + integer: function integer(value, schema, opts) { + // Additional validations for numerics are the same + return typeGroupValidators.numeric(value, schema, opts); + }, + + /** + * Validates the provided value against the schema using all of the validation keywords specific to instances of an number. + * The validation keywords for the type `number` are: + *``` + * ['multipleOf', 'maximum', 'minimum'] + *``` + * @name Schema.typeGroupValidators.number + * @method + * @param {*} value Number to be validated. + * @param {object} schema Schema containing at least one `number` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + number: function number(value, schema, opts) { + // Additional validations for numerics are the same + return typeGroupValidators.numeric(value, schema, opts); + }, + + /** + * Validates the provided value against the schema using all of the validation keywords specific to instances of a number or integer. + * The validation keywords for the type `numeric` are: + *``` + * ['multipleOf', 'maximum', 'minimum'] + *``` + * See http://json-schema.org/latest/json-schema-validation.html#anchor13. + * + * @name Schema.typeGroupValidators.numeric + * @method + * @param {*} value Number to be validated. + * @param {object} schema Schema containing at least one `numeric` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + numeric: function numeric(value, schema, opts) { + return runOps(NUMERIC_OPS, value, schema, opts); + }, + + /** + * Validates the provided value against the schema using all of the validation keywords specific to instances of an object. + * The validation keywords for the type `object` are: + *``` + * ['maxProperties', 'minProperties', 'required', 'properties', 'dependencies'] + *``` + * See http://json-schema.org/latest/json-schema-validation.html#anchor53. + * + * @name Schema.typeGroupValidators.object + * @method + * @param {*} value Object to be validated. + * @param {object} schema Schema containing at least one `object` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + object: function object(value, schema, opts) { + return runOps(OBJECT_OPS, value, schema, opts); + }, + + /** + * Validates the provided value against the schema using all of the validation keywords specific to instances of an string. + * The validation keywords for the type `string` are: + *``` + * ['maxLength', 'minLength', 'pattern'] + *``` + * See http://json-schema.org/latest/json-schema-validation.html#anchor25. + * + * @name Schema.typeGroupValidators.string + * @method + * @param {*} value String to be validated. + * @param {object} schema Schema containing at least one `string` keyword. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + string: function string(value, schema, opts) { + return runOps(STRING_OPS, value, schema, opts); + } + + /** + * js-data's Schema class. + * + * @example Schema#constructor + * const JSData = require('js-data'); + * const { Schema } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const PostSchema = new Schema({ + * type: 'object', + * properties: { + * title: { type: 'string' } + * } + * }); + * PostSchema.validate({ title: 1234 }); + * + * @class Schema + * @extends Component + * @param {object} definition Schema definition according to json-schema.org + */ +};function Schema(definition) { + var _this = this; + + definition || (definition = {}); + // TODO: schema validation + utils.fillIn(this, definition); + + if (this.type === 'object') { + this.properties = this.properties || {}; + utils.forOwn(this.properties, function (_definition, prop) { + if (!(_definition instanceof Schema)) { + _this.properties[prop] = new Schema(_definition); + } + }); + } else if (this.type === 'array' && this.items && !(this.items instanceof Schema)) { + this.items = new Schema(this.items); + } + if (this.extends && !(this.extends instanceof Schema)) { + this.extends = new Schema(this.extends); + } + ['allOf', 'anyOf', 'oneOf'].forEach(function (validationKeyword) { + if (_this[validationKeyword]) { + _this[validationKeyword].forEach(function (_definition, i) { + if (!(_definition instanceof Schema)) { + _this[validationKeyword][i] = new Schema(_definition); + } + }); + } + }); +} + +var Schema$1 = Component$1.extend({ + constructor: Schema, + + /** + * This adds ES5 getters/setters to the target based on the "properties" in + * this Schema, which makes possible change tracking and validation on + * property assignment. + * + * @name Schema#apply + * @method + * @param {object} target The prototype to which to apply this schema. + */ + apply: function apply(target, opts) { + var _this2 = this; + + opts || (opts = {}); + opts.getter || (opts.getter = '_get'); + opts.setter || (opts.setter = '_set'); + opts.unsetter || (opts.unsetter = '_unset'); + opts.track || (opts.track = this.track); + var properties = this.properties || {}; + utils.forOwn(properties, function (schema, prop) { + Object.defineProperty(target, prop, _this2.makeDescriptor(prop, schema, opts)); + }); + }, + + + /** + * Apply default values to the target object for missing values. + * + * @name Schema#applyDefaults + * @method + * @param {object} target The target to which to apply values for missing values. + */ + applyDefaults: function applyDefaults(target) { + if (!target) { + return; + } + var properties = this.properties || {}; + var hasSet = utils.isFunction(target.set) || utils.isFunction(target._set); + utils.forOwn(properties, function (schema, prop) { + if (schema.hasOwnProperty('default') && utils.get(target, prop) === undefined) { + if (hasSet) { + target.set(prop, utils.plainCopy(schema['default']), { silent: true }); + } else { + utils.set(target, prop, utils.plainCopy(schema['default'])); + } + } + if (schema.type === 'object' && schema.properties) { + if (hasSet) { + var orig = target._get('noValidate'); + target._set('noValidate', true); + utils.set(target, prop, utils.get(target, prop) || {}, { silent: true }); + target._set('noValidate', orig); + } else { + utils.set(target, prop, utils.get(target, prop) || {}); + } + schema.applyDefaults(utils.get(target, prop)); + } + }); + }, + + + /** + * Assemble a property descriptor for tracking and validating changes to + * a property according to the given schema. This method is called when + * {@link Mapper#applySchema} is set to `true`. + * + * @name Schema#makeDescriptor + * @method + * @param {string} prop The property name. + * @param {(Schema|object)} schema The schema for the property. + * @param {object} [opts] Optional configuration. + * @param {function} [opts.getter] Custom getter function. + * @param {function} [opts.setter] Custom setter function. + * @param {function} [opts.track] Whether to track changes. + * @returns {object} A property descriptor for the given schema. + */ + makeDescriptor: function makeDescriptor(prop, schema, opts) { + var descriptor = { + // Better to allow configurability, but at the user's own risk + configurable: true, + // These properties are enumerable by default, but regardless of their + // enumerability, they won't be "own" properties of individual records + enumerable: schema.enumerable === undefined ? true : !!schema.enumerable + // Cache a few strings for optimal performance + };var keyPath = 'props.' + prop; + var previousPath = 'previous.' + prop; + var getter = opts.getter; + var setter = opts.setter; + var unsetter = opts.unsetter; + var track = utils.isBoolean(opts.track) ? opts.track : schema.track; + + descriptor.get = function () { + return this._get(keyPath); + }; + + if (utils.isFunction(schema.get)) { + var originalGet = descriptor.get; + descriptor.get = function () { + return schema.get.call(this, originalGet); + }; + } + + descriptor.set = function (value) { + var _this3 = this; + + // These are accessed a lot + var _get = this[getter]; + var _set = this[setter]; + var _unset = this[unsetter]; + // Optionally check that the new value passes validation + if (!_get(noValidatePath$2)) { + var errors = schema.validate(value, { path: [prop] }); + if (errors) { + // Immediately throw an error, preventing the record from getting into + // an invalid state + var error = new Error(validationFailureMsg); + error.errors = errors; + throw error; + } + } + // TODO: Make it so tracking can be turned on for all properties instead of + // only per-property + if (track && !_get(creatingPath$1)) { + // previous is versioned on database commit + // props are versioned on set() + var previous = _get(previousPath); + var current = _get(keyPath); + var changing = _get(changingPath); + var changed = _get(changedPath); + + if (!changing) { + // Track properties that are changing in the current event loop + changed = []; + } + + // Add changing properties to this array once at most + var index = changed.indexOf(prop); + if (current !== value && index === -1) { + changed.push(prop); + } + if (previous === value) { + if (index >= 0) { + changed.splice(index, 1); + } + } + // No changes in current event loop + if (!changed.length) { + changing = false; + _unset(changingPath); + _unset(changedPath); + // Cancel pending change event + if (_get(eventIdPath)) { + clearTimeout(_get(eventIdPath)); + _unset(eventIdPath); + } + } + // Changes detected in current event loop + if (!changing && changed.length) { + _set(changedPath, changed); + _set(changingPath, true); + // Saving the timeout id allows us to batch all changes in the same + // event loop into a single "change" + // TODO: Optimize + _set(eventIdPath, setTimeout(function () { + // Previous event loop where changes were gathered has ended, so + // notify any listeners of those changes and prepare for any new + // changes + _unset(changedPath); + _unset(eventIdPath); + _unset(changingPath); + // TODO: Optimize + if (!_get(silentPath)) { + var i = void 0; + for (i = 0; i < changed.length; i++) { + _this3.emit('change:' + changed[i], _this3, utils.get(_this3, changed[i])); + } + + var changes = utils.diffObjects(defineProperty({}, prop, value), defineProperty({}, prop, current)); + + if (_get(keepChangeHistoryPath$1)) { + var changeRecord = utils.plainCopy(changes); + changeRecord.timestamp = new Date().getTime(); + var changeHistory = _get(changeHistoryPath); + !changeHistory && _set(changeHistoryPath, changeHistory = []); + changeHistory.push(changeRecord); + } + _this3.emit('change', _this3, changes); + } + _unset(silentPath); + }, 0)); + } + } + _set(keyPath, value); + return value; + }; + + if (utils.isFunction(schema.set)) { + var originalSet = descriptor.set; + descriptor.set = function (value) { + return schema.set.call(this, value, originalSet); + }; + } + + return descriptor; + }, + + + /** + * Create a copy of the given value that contains only the properties defined + * in this schema. + * + * @name Schema#pick + * @method + * @param {*} value The value to copy. + * @returns {*} The copy. + */ + pick: function pick(value) { + var _this4 = this; + + if (value === undefined) { + return; + } + if (this.type === 'object') { + var copy = {}; + var properties = this.properties; + if (properties) { + utils.forOwn(properties, function (_definition, prop) { + copy[prop] = _definition.pick(value[prop]); + }); + } + if (this.extends) { + utils.fillIn(copy, this.extends.pick(value)); + } + // Conditionally copy properties not defined in "properties" + if (this.additionalProperties) { + for (var key in value) { + if (!properties[key]) { + copy[key] = utils.plainCopy(value[key]); + } + } + } + return copy; + } else if (this.type === 'array') { + return value.map(function (item) { + var _copy = _this4.items ? _this4.items.pick(item) : {}; + if (_this4.extends) { + utils.fillIn(_copy, _this4.extends.pick(item)); + } + return _copy; + }); + } + return utils.plainCopy(value); + }, + + + /** + * Validate the provided value against this schema. + * + * @name Schema#validate + * @method + * @param {*} value Value to validate. + * @param {object} [opts] Configuration options. + * @returns {(array|undefined)} Array of errors or `undefined` if valid. + */ + validate: function validate(value, opts) { + return _validate(value, this, opts); + } +}, { + ANY_OPS: ANY_OPS, + ARRAY_OPS: ARRAY_OPS, + NUMERIC_OPS: NUMERIC_OPS, + OBJECT_OPS: OBJECT_OPS, + STRING_OPS: STRING_OPS, + typeGroupValidators: typeGroupValidators, + types: types, + validate: _validate, + validationKeywords: validationKeywords +}); + +/** + * Create a subclass of this Schema: + * @example Schema.extend + * const JSData = require('js-data'); + * const { Schema } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomSchemaClass extends Schema { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customSchema = new CustomSchemaClass(); + * console.log(customSchema.foo()); + * console.log(CustomSchemaClass.beep()); + * + * // Extend the class using alternate method. + * const OtherSchemaClass = Schema.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherSchema = new OtherSchemaClass(); + * console.log(otherSchema.foo()); + * console.log(OtherSchemaClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherSchemaClass () { + * Schema.call(this); + * this.created_at = new Date().getTime(); + * } + * Schema.extend({ + * constructor: AnotherSchemaClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const anotherSchema = new AnotherSchemaClass(); + * console.log(anotherSchema.created_at); + * console.log(anotherSchema.foo()); + * console.log(AnotherSchemaClass.beep()); + * + * @method Schema.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this Schema class. + * @since 3.0.0 + */ + +var DOMAIN$6 = 'Mapper'; +var applyDefaultsHooks = ['beforeCreate', 'beforeCreateMany']; +var validatingHooks = ['beforeCreate', 'beforeCreateMany', 'beforeUpdate', 'beforeUpdateAll', 'beforeUpdateMany']; +var makeNotify = function makeNotify(num) { + return function () { + var _this = this; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var opts = args[args.length - num]; + var op = opts.op; + this.dbg.apply(this, [op].concat(args)); + + if (applyDefaultsHooks.indexOf(op) !== -1 && opts.applyDefaults !== false) { + var schema = this.getSchema(); + if (schema && schema.applyDefaults) { + var toProcess = args[0]; + if (!utils.isArray(toProcess)) { + toProcess = [toProcess]; + } + toProcess.forEach(function (record) { + schema.applyDefaults(record); + }); + } + } + + // Automatic validation + if (validatingHooks.indexOf(op) !== -1 && !opts.noValidate) { + // Save current value of option + var originalExistingOnly = opts.existingOnly; + + // For updates, ignore required fields if they aren't present + if (op.indexOf('beforeUpdate') === 0 && opts.existingOnly === undefined) { + opts.existingOnly = true; + } + var errors = this.validate(args[op === 'beforeUpdate' ? 1 : 0], utils.pick(opts, ['existingOnly'])); + + // Restore option + opts.existingOnly = originalExistingOnly; + + // Abort lifecycle due to validation errors + if (errors) { + var err = new Error('validation failed'); + err.errors = errors; + return utils.reject(err); + } + } + + // Emit lifecycle event + if (opts.notify || opts.notify === undefined && this.notify) { + setTimeout(function () { + _this.emit.apply(_this, [op].concat(args)); + }); + } + }; +}; + +// These are the default implementations of all of the lifecycle hooks +var notify = makeNotify(1); +var notify2 = makeNotify(2); + +// This object provides meta information used by Mapper#crud to actually +// execute each lifecycle method +var LIFECYCLE_METHODS = { + count: { + defaults: [{}, {}], + skip: true, + types: [] + }, + destroy: { + defaults: [{}, {}], + skip: true, + types: [] + }, + destroyAll: { + defaults: [{}, {}], + skip: true, + types: [] + }, + find: { + defaults: [undefined, {}], + types: [] + }, + findAll: { + defaults: [{}, {}], + types: [] + }, + sum: { + defaults: [undefined, {}, {}], + skip: true, + types: [] + }, + update: { + adapterArgs: function adapterArgs(mapper, id, props, opts) { + return [id, mapper.toJSON(props, opts), opts]; + }, + + beforeAssign: 1, + defaults: [undefined, {}, {}], + types: [] + }, + updateAll: { + adapterArgs: function adapterArgs(mapper, props, query, opts) { + return [mapper.toJSON(props, opts), query, opts]; + }, + + beforeAssign: 0, + defaults: [{}, {}, {}], + types: [] + }, + updateMany: { + adapterArgs: function adapterArgs(mapper, records, opts) { + return [records.map(function (record) { + return mapper.toJSON(record, opts); + }), opts]; + }, + + beforeAssign: 0, + defaults: [[], {}], + types: [] + } +}; + +var MAPPER_DEFAULTS = { + /** + * Hash of registered adapters. Don't modify directly. Use + * {@link Mapper#registerAdapter} instead. + * + * @default {} + * @name Mapper#_adapters + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/connecting-to-a-data-source","Connecting to a data source"] + */ + _adapters: {}, + + /** + * Whether {@link Mapper#beforeCreate} and {@link Mapper#beforeCreateMany} + * should automatically receive default values according to the Mapper's schema. + * + * @default true + * @name Mapper#applyDefaults + * @since 3.0.0 + * @type {boolean} + */ + applyDefaults: true, + + /** + * Whether to augment {@link Mapper#recordClass} with ES5 getters and setters + * according to the properties defined in {@link Mapper#schema}. This makes + * possible validation and change tracking on individual properties + * when using the dot (e.g. `user.name = "Bob"`) operator to modify a + * property, and is `true` by default. + * + * @default true + * @name Mapper#applySchema + * @since 3.0.0 + * @type {boolean} + */ + applySchema: true, + + /** + * The name of the registered adapter that this Mapper should used by default. + * + * @default "http" + * @name Mapper#defaultAdapter + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/connecting-to-a-data-source","Connecting to a data source"] + * @type {string} + */ + defaultAdapter: 'http', + + /** + * The field used as the unique identifier on records handled by this Mapper. + * + * @default id + * @name Mapper#idAttribute + * @since 3.0.0 + * @type {string} + */ + idAttribute: 'id', + + /** + * Whether records created from this mapper keep changeHistory on property changes. + * + * @default true + * @name Mapper#keepChangeHistory + * @since 3.0.0 + * @type {boolean} + */ + keepChangeHistory: true, + + /** + * Whether this Mapper should emit operational events. + * + * @default true + * @name Mapper#notify + * @since 3.0.0 + * @type {boolean} + */ + notify: true, + + /** + * Whether to skip validation when the Record instances are created. + * + * @default false + * @name Mapper#noValidate + * @since 3.0.0 + * @type {boolean} + */ + noValidate: false, + + /** + * Whether {@link Mapper#create}, {@link Mapper#createMany}, + * {@link Mapper#update}, {@link Mapper#updateAll}, {@link Mapper#updateMany}, + * {@link Mapper#find}, {@link Mapper#findAll}, {@link Mapper#destroy}, + * {@link Mapper#destroyAll}, {@link Mapper#count}, and {@link Mapper#sum} + * should return a raw result object that contains both the instance data + * returned by the adapter _and_ metadata about the operation. + * + * The default is to NOT return the result object, and instead return just the + * instance data. + * + * @default false + * @name Mapper#raw + * @since 3.0.0 + * @type {boolean} + */ + raw: false, + + /** + * Whether records created from this mapper automatically validate their properties + * when their properties are modified. + * + * @default true + * @name Mapper#validateOnSet + * @since 3.0.0 + * @type {boolean} + */ + validateOnSet: true + + /** + * The core of JSData's [ORM/ODM][orm] implementation. Given a minimum amout of + * meta information about a resource, a Mapper can perform generic CRUD + * operations against that resource. Apart from its configuration, a Mapper is + * stateless. The particulars of various persistence layers have been abstracted + * into adapters, which a Mapper uses to perform its operations. + * + * The term "Mapper" comes from the [Data Mapper Pattern][pattern] described in + * Martin Fowler's [Patterns of Enterprise Application Architecture][book]. A + * Data Mapper moves data between [in-memory object instances][record] and a + * relational or document-based database. JSData's Mapper can work with any + * persistence layer you can write an adapter for. + * + * _("Model" is a heavily overloaded term and is avoided in this documentation + * to prevent confusion.)_ + * + * [orm]: https://en.wikipedia.org/wiki/Object-relational_mapping + * + * @example + * [pattern]: https://en.wikipedia.org/wiki/Data_mapper_pattern + * [book]: http://martinfowler.com/books/eaa.html + * [record]: Record.html + * // Import and instantiate + * import { Mapper } from 'js-data'; + * const UserMapper = new Mapper({ name: 'user' }); + * + * @example + * // Define a Mapper using the Container component + * import { Container } from 'js-data'; + * const store = new Container(); + * store.defineMapper('user'); + * + * @class Mapper + * @extends Component + * @param {object} opts Configuration options. + * @param {boolean} [opts.applySchema=true] See {@link Mapper#applySchema}. + * @param {boolean} [opts.debug=false] See {@link Component#debug}. + * @param {string} [opts.defaultAdapter=http] See {@link Mapper#defaultAdapter}. + * @param {string} [opts.idAttribute=id] See {@link Mapper#idAttribute}. + * @param {object} [opts.methods] See {@link Mapper#methods}. + * @param {string} opts.name See {@link Mapper#name}. + * @param {boolean} [opts.notify] See {@link Mapper#notify}. + * @param {boolean} [opts.raw=false] See {@link Mapper#raw}. + * @param {Function|boolean} [opts.recordClass] See {@link Mapper#recordClass}. + * @param {Object|Schema} [opts.schema] See {@link Mapper#schema}. + * @returns {Mapper} A new {@link Mapper} instance. + * @see http://www.js-data.io/v3.0/docs/components-of-jsdata#mapper + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#mapper","Components of JSData: Mapper"] + * @tutorial ["http://www.js-data.io/v3.0/docs/modeling-your-data","Modeling your data"] + */ +};function Mapper(opts) { + utils.classCallCheck(this, Mapper); + Component$1.call(this); + opts || (opts = {}); + + // Prepare certain properties to be non-enumerable + Object.defineProperties(this, { + _adapters: { + value: undefined, + writable: true + }, + + /** + * The {@link Container} that holds this Mapper. __Do not modify.__ + * + * @name Mapper#lifecycleMethods + * @since 3.0.0 + * @type {Object} + */ + datastore: { + value: undefined, + writable: true + }, + + /** + * The meta information describing this Mapper's available lifecycle + * methods. __Do not modify.__ + * + * @name Mapper#lifecycleMethods + * @since 3.0.0 + * @type {Object} + */ + lifecycleMethods: { + value: LIFECYCLE_METHODS + }, + + /** + * Set to `false` to force the Mapper to work with POJO objects only. + * + * @example + * // Use POJOs only. + * import { Mapper, Record } from 'js-data'; + * const UserMapper = new Mapper({ recordClass: false }); + * UserMapper.recordClass // false; + * const user = UserMapper.createRecord(); + * user instanceof Record; // false + * + * @example + * // Set to a custom class to have records wrapped in your custom class. + * import { Mapper, Record } from 'js-data'; + * // Custom class + * class User { + * constructor (props = {}) { + * for (var key in props) { + * if (props.hasOwnProperty(key)) { + * this[key] = props[key]; + * } + * } + * } + * } + * const UserMapper = new Mapper({ recordClass: User }); + * UserMapper.recordClass; // function User() {} + * const user = UserMapper.createRecord(); + * user instanceof Record; // false + * user instanceof User; // true + * + * + * @example + * // Extend the {@link Record} class. + * import { Mapper, Record } from 'js-data'; + * // Custom class + * class User extends Record { + * constructor () { + * super(props); + * } + * } + * const UserMapper = new Mapper({ recordClass: User }); + * UserMapper.recordClass; // function User() {} + * const user = UserMapper.createRecord(); + * user instanceof Record; // true + * user instanceof User; // true + * + * @name Mapper#recordClass + * @default {@link Record} + * @see Record + * @since 3.0.0 + */ + recordClass: { + value: undefined, + writable: true + }, + + /** + * This Mapper's {@link Schema}. + * + * @example Mapper#schema + * const JSData = require('js-data'); + * const { Mapper } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const UserMapper = new Mapper({ + * name: 'user', + * schema: { + * properties: { + * id: { type: 'number' }, + * first: { type: 'string', track: true }, + * last: { type: 'string', track: true }, + * role: { type: 'string', track: true, required: true }, + * age: { type: 'integer', track: true }, + * is_active: { type: 'number' } + * } + * } + * }); + * const user = UserMapper.createRecord({ + * id: 1, + * name: 'John', + * role: 'admin' + * }); + * user.on('change', function (user, changes) { + * console.log(changes); + * }); + * user.on('change:role', function (user, value) { + * console.log('change:role - ' + value); + * }); + * user.role = 'owner'; + * + * @name Mapper#schema + * @see Schema + * @since 3.0.0 + * @type {Schema} + */ + schema: { + value: undefined, + writable: true + } + }); + + // Apply user-provided configuration + utils.fillIn(this, opts); + // Fill in any missing options with the defaults + utils.fillIn(this, utils.copy(MAPPER_DEFAULTS)); + + /** + * The name for this Mapper. This is the minimum amount of meta information + * required for a Mapper to be able to execute CRUD operations for a + * Resource. + * + * @name Mapper#name + * @since 3.0.0 + * @type {string} + */ + if (!this.name) { + throw utils.err('new ' + DOMAIN$6, 'opts.name')(400, 'string', this.name); + } + + // Setup schema, with an empty default schema if necessary + if (this.schema) { + this.schema.type || (this.schema.type = 'object'); + if (!(this.schema instanceof Schema$1)) { + this.schema = new Schema$1(this.schema || { type: 'object' }); + } + } + + // Create a subclass of Record that's tied to this Mapper + if (this.recordClass === undefined) { + var superClass = Record$1; + this.recordClass = superClass.extend({ + constructor: function Record() { + var subClass = function Record(props, opts) { + utils.classCallCheck(this, subClass); + superClass.call(this, props, opts); + }; + return subClass; + }() + }); + } + + if (this.recordClass) { + this.recordClass.mapper = this; + + /** + * Functions that should be added to the prototype of {@link Mapper#recordClass}. + * + * @name Mapper#methods + * @since 3.0.0 + * @type {Object} + */ + if (utils.isObject(this.methods)) { + utils.addHiddenPropsToTarget(this.recordClass.prototype, this.methods); + } + + // We can only apply the schema to the prototype of this.recordClass if the + // class extends Record + if (Record$1.prototype.isPrototypeOf(Object.create(this.recordClass.prototype)) && this.schema && this.schema.apply && this.applySchema) { + this.schema.apply(this.recordClass.prototype); + } + } +} + +var Mapper$1 = Component$1.extend({ + constructor: Mapper, + + /** + * Mapper lifecycle hook called by {@link Mapper#count}. If this method + * returns a promise then {@link Mapper#count} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterCount + * @param {object} query The `query` argument passed to {@link Mapper#count}. + * @param {object} opts The `opts` argument passed to {@link Mapper#count}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterCount: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#create}. If this method + * returns a promise then {@link Mapper#create} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterCreate + * @param {object} props The `props` argument passed to {@link Mapper#create}. + * @param {object} opts The `opts` argument passed to {@link Mapper#create}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterCreate: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#createMany}. If this method + * returns a promise then {@link Mapper#createMany} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterCreateMany + * @param {array} records The `records` argument passed to {@link Mapper#createMany}. + * @param {object} opts The `opts` argument passed to {@link Mapper#createMany}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterCreateMany: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#destroy}. If this method + * returns a promise then {@link Mapper#destroy} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterDestroy + * @param {(string|number)} id The `id` argument passed to {@link Mapper#destroy}. + * @param {object} opts The `opts` argument passed to {@link Mapper#destroy}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterDestroy: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#destroyAll}. If this method + * returns a promise then {@link Mapper#destroyAll} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterDestroyAll + * @param {*} data The `data` returned by the adapter. + * @param {query} query The `query` argument passed to {@link Mapper#destroyAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#destroyAll}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterDestroyAll: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#find}. If this method + * returns a promise then {@link Mapper#find} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterFind + * @param {(string|number)} id The `id` argument passed to {@link Mapper#find}. + * @param {object} opts The `opts` argument passed to {@link Mapper#find}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterFind: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#findAll}. If this method + * returns a promise then {@link Mapper#findAll} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterFindAll + * @param {object} query The `query` argument passed to {@link Mapper#findAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#findAll}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterFindAll: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#sum}. If this method + * returns a promise then {@link Mapper#sum} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterSum + * @param {object} query The `query` argument passed to {@link Mapper#sum}. + * @param {object} opts The `opts` argument passed to {@link Mapper#sum}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterSum: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#update}. If this method + * returns a promise then {@link Mapper#update} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterUpdate + * @param {(string|number)} id The `id` argument passed to {@link Mapper#update}. + * @param {props} props The `props` argument passed to {@link Mapper#update}. + * @param {object} opts The `opts` argument passed to {@link Mapper#update}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterUpdate: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#updateAll}. If this method + * returns a promise then {@link Mapper#updateAll} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterUpdateAll + * @param {object} props The `props` argument passed to {@link Mapper#updateAll}. + * @param {object} query The `query` argument passed to {@link Mapper#updateAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#updateAll}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterUpdateAll: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#updateMany}. If this method + * returns a promise then {@link Mapper#updateMany} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#afterUpdateMany + * @param {array} records The `records` argument passed to {@link Mapper#updateMany}. + * @param {object} opts The `opts` argument passed to {@link Mapper#updateMany}. + * @param {*} result The result, if any. + * @since 3.0.0 + */ + afterUpdateMany: notify2, + + /** + * Mapper lifecycle hook called by {@link Mapper#create}. If this method + * returns a promise then {@link Mapper#create} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeCreate + * @param {object} props The `props` argument passed to {@link Mapper#create}. + * @param {object} opts The `opts` argument passed to {@link Mapper#create}. + * @since 3.0.0 + */ + beforeCreate: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#createMany}. If this method + * returns a promise then {@link Mapper#createMany} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeCreateMany + * @param {array} records The `records` argument passed to {@link Mapper#createMany}. + * @param {object} opts The `opts` argument passed to {@link Mapper#createMany}. + * @since 3.0.0 + */ + beforeCreateMany: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#count}. If this method + * returns a promise then {@link Mapper#count} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeCount + * @param {object} query The `query` argument passed to {@link Mapper#count}. + * @param {object} opts The `opts` argument passed to {@link Mapper#count}. + * @since 3.0.0 + */ + beforeCount: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#destroy}. If this method + * returns a promise then {@link Mapper#destroy} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeDestroy + * @param {(string|number)} id The `id` argument passed to {@link Mapper#destroy}. + * @param {object} opts The `opts` argument passed to {@link Mapper#destroy}. + * @since 3.0.0 + */ + beforeDestroy: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#destroyAll}. If this method + * returns a promise then {@link Mapper#destroyAll} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeDestroyAll + * @param {query} query The `query` argument passed to {@link Mapper#destroyAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#destroyAll}. + * @since 3.0.0 + */ + beforeDestroyAll: notify, + + /** + * Mappers lifecycle hook called by {@link Mapper#find}. If this method + * returns a promise then {@link Mapper#find} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeFind + * @param {(string|number)} id The `id` argument passed to {@link Mapper#find}. + * @param {object} opts The `opts` argument passed to {@link Mapper#find}. + * @since 3.0.0 + */ + beforeFind: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#findAll}. If this method + * returns a promise then {@link Mapper#findAll} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeFindAll + * @param {object} query The `query` argument passed to {@link Mapper#findAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#findAll}. + * @since 3.0.0 + */ + beforeFindAll: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#sum}. If this method + * returns a promise then {@link Mapper#sum} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeSum + * @param {string} field The `field` argument passed to {@link Mapper#sum}. + * @param {object} query The `query` argument passed to {@link Mapper#sum}. + * @param {object} opts The `opts` argument passed to {@link Mapper#sum}. + * @since 3.0.0 + */ + beforeSum: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#update}. If this method + * returns a promise then {@link Mapper#update} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeUpdate + * @param {(string|number)} id The `id` argument passed to {@link Mapper#update}. + * @param {props} props The `props` argument passed to {@link Mapper#update}. + * @param {object} opts The `opts` argument passed to {@link Mapper#update}. + * @since 3.0.0 + */ + beforeUpdate: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#updateAll}. If this method + * returns a promise then {@link Mapper#updateAll} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeUpdateAll + * @param {object} props The `props` argument passed to {@link Mapper#updateAll}. + * @param {object} query The `query` argument passed to {@link Mapper#updateAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#updateAll}. + * @since 3.0.0 + */ + beforeUpdateAll: notify, + + /** + * Mapper lifecycle hook called by {@link Mapper#updateMany}. If this method + * returns a promise then {@link Mapper#updateMany} will wait for the promise + * to resolve before continuing. + * + * @method Mapper#beforeUpdateMany + * @param {array} records The `records` argument passed to {@link Mapper#updateMany}. + * @param {object} opts The `opts` argument passed to {@link Mapper#updateMany}. + * @since 3.0.0 + */ + beforeUpdateMany: notify, + + /** + * This method is called at the end of most lifecycle methods. It does the + * following: + * + * 1. If `opts.raw` is `true`, add this Mapper's configuration to the `opts` + * argument as metadata for the operation. + * 2. Wrap the result data appropriately using {@link Mapper#wrap}, which + * calls {@link Mapper#createRecord}. + * + * @method Mapper#_end + * @private + * @since 3.0.0 + */ + _end: function _end(result, opts, skip) { + if (opts.raw) { + utils._(result, opts); + } + if (skip) { + return result; + } + var _data = opts.raw ? result.data : result; + if (_data && utils.isFunction(this.wrap)) { + _data = this.wrap(_data, opts); + if (opts.raw) { + result.data = _data; + } else { + result = _data; + } + } + return result; + }, + + + /** + * Define a belongsTo relationship. Only useful if you're managing your + * Mappers manually and not using a Container or DataStore component. + * + * @example + * PostMapper.belongsTo(UserMapper, { + * // post.user_id points to user.id + * foreignKey: 'user_id' + * // user records will be attached to post records at "post.user" + * localField: 'user' + * }); + * + * CommentMapper.belongsTo(UserMapper, { + * // comment.user_id points to user.id + * foreignKey: 'user_id' + * // user records will be attached to comment records at "comment.user" + * localField: 'user' + * }); + * CommentMapper.belongsTo(PostMapper, { + * // comment.post_id points to post.id + * foreignKey: 'post_id' + * // post records will be attached to comment records at "comment.post" + * localField: 'post' + * }); + * + * @method Mapper#belongsTo + * @see http://www.js-data.io/v3.0/docs/relations + * @since 3.0.0 + */ + belongsTo: function belongsTo$$1(relatedMapper, opts) { + return belongsTo(relatedMapper, opts)(this); + }, + + + /** + * Select records according to the `query` argument and return the count. + * + * {@link Mapper#beforeCount} will be called before calling the adapter. + * {@link Mapper#afterCount} will be called after calling the adapter. + * + * @example + * // Get the number of published blog posts + * PostMapper.count({ status: 'published' }).then((numPublished) => { + * console.log(numPublished); // e.g. 45 + * }); + * + * @method Mapper#count + * @param {object} [query={}] Selection query. See {@link query}. + * @param {object} [query.where] See {@link query.where}. + * @param {number} [query.offset] See {@link query.offset}. + * @param {number} [query.limit] See {@link query.limit}. + * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}. + * @param {object} [opts] Configuration options. Refer to the `count` method + * of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @returns {Promise} Resolves with the count of the selected records. + * @since 3.0.0 + */ + count: function count(query, opts) { + return this.crud('count', query, opts); + }, + + + /** + * Fired during {@link Mapper#create}. See + * {@link Mapper~beforeCreateListener} for how to listen for this event. + * + * @event Mapper#beforeCreate + * @see Mapper~beforeCreateListener + * @see Mapper#create + */ + /** + * Callback signature for the {@link Mapper#event:beforeCreate} event. + * + * @example + * function onBeforeCreate (props, opts) { + * // do something + * } + * store.on('beforeCreate', onBeforeCreate); + * + * @callback Mapper~beforeCreateListener + * @param {object} props The `props` argument passed to {@link Mapper#beforeCreate}. + * @param {object} opts The `opts` argument passed to {@link Mapper#beforeCreate}. + * @see Mapper#event:beforeCreate + * @see Mapper#create + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#create}. See + * {@link Mapper~afterCreateListener} for how to listen for this event. + * + * @event Mapper#afterCreate + * @see Mapper~afterCreateListener + * @see Mapper#create + */ + /** + * Callback signature for the {@link Mapper#event:afterCreate} event. + * + * @example + * function onAfterCreate (props, opts, result) { + * // do something + * } + * store.on('afterCreate', onAfterCreate); + * + * @callback Mapper~afterCreateListener + * @param {object} props The `props` argument passed to {@link Mapper#afterCreate}. + * @param {object} opts The `opts` argument passed to {@link Mapper#afterCreate}. + * @param {object} result The `result` argument passed to {@link Mapper#afterCreate}. + * @see Mapper#event:afterCreate + * @see Mapper#create + * @since 3.0.0 + */ + /** + * Create and save a new the record using the provided `props`. + * + * {@link Mapper#beforeCreate} will be called before calling the adapter. + * {@link Mapper#afterCreate} will be called after calling the adapter. + * + * @example + * // Create and save a new blog post + * PostMapper.create({ + * title: 'Modeling your data', + * status: 'draft' + * }).then((post) => { + * console.log(post); // { id: 1234, status: 'draft', ... } + * }); + * + * @fires Mapper#beforeCreate + * @fires Mapper#afterCreate + * @method Mapper#create + * @param {object} props The properties for the new record. + * @param {object} [opts] Configuration options. Refer to the `create` method + * of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @param {string[]} [opts.with=[]] Relations to create in a cascading + * create if `props` contains nested relations. NOT performed in a + * transaction. Each nested create will result in another {@link Mapper#create} + * or {@link Mapper#createMany} call. + * @param {string[]} [opts.pass=[]] Relations to send to the adapter as part + * of the payload. Normally relations are not sent. + * @returns {Promise} Resolves with the created record. + * @since 3.0.0 + */ + create: function create(props, opts) { + var _this2 = this; + + // Default values for arguments + props || (props = {}); + opts || (opts = {}); + var originalRecord = props; + var parentRelationMap = {}; + var adapterResponse = {}; + + // Fill in "opts" with the Mapper's configuration + utils._(opts, this); + opts.adapter = this.getAdapterName(opts); + + opts.op = 'beforeCreate'; + return this._runHook(opts.op, props, opts).then(function (props) { + opts.with || (opts.with = []); + return _this2._createParentRecordIfRequired(props, opts); + }).then(function (relationMap) { + parentRelationMap = relationMap; + }).then(function () { + opts.op = 'create'; + return _this2._invokeAdapterMethod(opts.op, props, opts); + }).then(function (result) { + adapterResponse = result; + }).then(function () { + var createdProps = opts.raw ? adapterResponse.data : adapterResponse; + + return _this2._createOrAssignChildRecordIfRequired(createdProps, { + opts: opts, + parentRelationMap: parentRelationMap, + originalProps: props + }); + }).then(function (createdProps) { + return _this2._commitChanges(originalRecord, createdProps); + }).then(function (record) { + if (opts.raw) { + adapterResponse.data = record; + } else { + adapterResponse = record; + } + var result = _this2._end(adapterResponse, opts); + opts.op = 'afterCreate'; + return _this2._runHook(opts.op, props, opts, result); + }); + }, + _commitChanges: function _commitChanges(recordOrRecords, newValues) { + var _this3 = this; + + if (utils.isArray(recordOrRecords)) { + return recordOrRecords.map(function (record, i) { + return _this3._commitChanges(record, newValues[i]); + }); + } + + utils.set(recordOrRecords, newValues, { silent: true }); + + if (utils.isFunction(recordOrRecords.commit)) { + recordOrRecords.commit(); + } + + return recordOrRecords; + }, + + + /** + * Use {@link Mapper#createRecord} instead. + * @deprecated + * @method Mapper#createInstance + * @param {Object|Array} props See {@link Mapper#createRecord}. + * @param {object} [opts] See {@link Mapper#createRecord}. + * @returns {Object|Array} See {@link Mapper#createRecord}. + * @see Mapper#createRecord + * @since 3.0.0 + */ + createInstance: function createInstance(props, opts) { + return this.createRecord(props, opts); + }, + + + /** + * Creates parent record for relation types like BelongsTo or HasMany with localKeys + * in order to satisfy foreignKey dependency (so called child records). + * @param {object} props See {@link Mapper#create}. + * @param {object} opts See {@link Mapper#create}. + * @returns {Object} cached parent records map + * @see Mapper#create + * @since 3.0.0 + */ + _createParentRecordIfRequired: function _createParentRecordIfRequired(props, opts) { + var tasks = []; + var relations = []; + + utils.forEachRelation(this, opts, function (def, optsCopy) { + if (!def.isRequiresParentId() || !def.getLocalField(props)) { + return; + } + + optsCopy.raw = false; + relations.push(def); + tasks.push(def.createParentRecord(props, optsCopy)); + }); + + return utils.Promise.all(tasks).then(function (records) { + return relations.reduce(function (map, relation, index) { + relation.setLocalField(map, records[index]); + return map; + }, {}); + }); + }, + + + /** + * Creates child record for relation types like HasOne or HasMany with foreignKey + * in order to satisfy foreignKey dependency (so called parent records). + * @param {object} props See {@link Mapper#create}. + * @param {object} context contains collected information. + * @param {object} context.opts See {@link Mapper#create}. + * @param {object} context.parentRelationMap contains parent records map + * @param {object} context.originalProps contains data passed into {@link Mapper#create} method + * @return {Promise} updated props + * @see Mapper#create + * @since 3.0.0 + */ + _createOrAssignChildRecordIfRequired: function _createOrAssignChildRecordIfRequired(props, context) { + var tasks = []; + + utils.forEachRelation(this, context.opts, function (def, optsCopy) { + var relationData = def.getLocalField(context.originalProps); + + if (!relationData) { + return; + } + + optsCopy.raw = false; + // Create hasMany and hasOne after the main create because we needed + // a generated id to attach to these items + if (def.isRequiresChildId()) { + tasks.push(def.createChildRecord(props, relationData, optsCopy)); + } else if (def.isRequiresParentId()) { + var parent = def.getLocalField(context.parentRelationMap); + + if (parent) { + def.setLocalField(props, parent); + } + } + }); + + return utils.Promise.all(tasks).then(function () { + return props; + }); + }, + + + /** + * Fired during {@link Mapper#createMany}. See + * {@link Mapper~beforeCreateManyListener} for how to listen for this event. + * + * @event Mapper#beforeCreateMany + * @see Mapper~beforeCreateManyListener + * @see Mapper#createMany + */ + /** + * Callback signature for the {@link Mapper#event:beforeCreateMany} event. + * + * @example + * function onBeforeCreateMany (records, opts) { + * // do something + * } + * store.on('beforeCreateMany', onBeforeCreateMany); + * + * @callback Mapper~beforeCreateManyListener + * @param {object} records The `records` argument received by {@link Mapper#beforeCreateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreateMany}. + * @see Mapper#event:beforeCreateMany + * @see Mapper#createMany + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#createMany}. See + * {@link Mapper~afterCreateManyListener} for how to listen for this event. + * + * @event Mapper#afterCreateMany + * @see Mapper~afterCreateManyListener + * @see Mapper#createMany + */ + /** + * Callback signature for the {@link Mapper#event:afterCreateMany} event. + * + * @example + * function onAfterCreateMany (records, opts, result) { + * // do something + * } + * store.on('afterCreateMany', onAfterCreateMany); + * + * @callback Mapper~afterCreateManyListener + * @param {object} records The `records` argument received by {@link Mapper#afterCreateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterCreateMany}. + * @param {object} result The `result` argument received by {@link Mapper#afterCreateMany}. + * @see Mapper#event:afterCreateMany + * @see Mapper#createMany + * @since 3.0.0 + */ + /** + * Given an array of records, batch create them via an adapter. + * + * {@link Mapper#beforeCreateMany} will be called before calling the adapter. + * {@link Mapper#afterCreateMany} will be called after calling the adapter. + * + * @example + * // Create and save several new blog posts + * PostMapper.createMany([{ + * title: 'Modeling your data', + * status: 'draft' + * }, { + * title: 'Reading data', + * status: 'draft' + * }]).then((posts) => { + * console.log(posts[0]); // { id: 1234, status: 'draft', ... } + * console.log(posts[1]); // { id: 1235, status: 'draft', ... } + * }); + * + * @fires Mapper#beforeCreate + * @fires Mapper#afterCreate + * @method Mapper#createMany + * @param {Record[]} records Array of records to be created in one batch. + * @param {object} [opts] Configuration options. Refer to the `createMany` + * method of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @param {string[]} [opts.with=[]] Relations to create in a cascading + * create if `records` contains nested relations. NOT performed in a + * transaction. Each nested create will result in another {@link Mapper#createMany} + * call. + * @param {string[]} [opts.pass=[]] Relations to send to the adapter as part + * of the payload. Normally relations are not sent. + * @returns {Promise} Resolves with the created records. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/saving-data","Saving data"] + */ + createMany: function createMany(records, opts) { + var _this4 = this; + + // Default values for arguments + records || (records = []); + opts || (opts = {}); + var originalRecords = records; + var adapterResponse = void 0; + + // Fill in "opts" with the Mapper's configuration + utils._(opts, this); + opts.adapter = this.getAdapterName(opts); + + // beforeCreateMany lifecycle hook + opts.op = 'beforeCreateMany'; + return this._runHook(opts.op, records, opts).then(function (records) { + // Deep pre-create belongsTo relations + var belongsToRelationData = {}; + opts.with || (opts.with = []); + var tasks = []; + utils.forEachRelation(_this4, opts, function (def, optsCopy) { + var relationData = records.map(function (record) { + return def.getLocalField(record); + }).filter(Boolean); + if (def.type === belongsToType && relationData.length === records.length) { + // Create belongsTo relation first because we need a generated id to + // attach to the child + optsCopy.raw = false; + tasks.push(def.createLinked(relationData, optsCopy).then(function (relatedRecords) { + records.forEach(function (record, i) { + return def.setForeignKey(record, relatedRecords[i]); + }); + }).then(function (relatedRecords) { + def.setLocalField(belongsToRelationData, relatedRecords); + })); + } + }); + return utils.Promise.all(tasks).then(function () { + opts.op = 'createMany'; + return _this4._invokeAdapterMethod(opts.op, records, opts); + }).then(function (result) { + adapterResponse = result; + }).then(function () { + var createdRecordsData = opts.raw ? adapterResponse.data : adapterResponse; + + // Deep post-create hasOne relations + tasks = []; + utils.forEachRelation(_this4, opts, function (def, optsCopy) { + var relationData = records.map(function (record) { + return def.getLocalField(record); + }).filter(Boolean); + if (relationData.length !== records.length) { + return; + } + + optsCopy.raw = false; + var belongsToData = def.getLocalField(belongsToRelationData); + var task = void 0; + // Create hasMany and hasOne after the main create because we needed + // a generated id to attach to these items + if (def.type === hasManyType) { + // Not supported + _this4.log('warn', 'deep createMany of hasMany type not supported!'); + } else if (def.type === hasOneType) { + createdRecordsData.forEach(function (createdRecordData, i) { + def.setForeignKey(createdRecordData, relationData[i]); + }); + task = def.getRelation().createMany(relationData, optsCopy).then(function (relatedData) { + createdRecordsData.forEach(function (createdRecordData, i) { + def.setLocalField(createdRecordData, relatedData[i]); + }); + }); + } else if (def.type === belongsToType && belongsToData && belongsToData.length === createdRecordsData.length) { + createdRecordsData.forEach(function (createdRecordData, i) { + def.setLocalField(createdRecordData, belongsToData[i]); + }); + } + if (task) { + tasks.push(task); + } + }); + return utils.Promise.all(tasks).then(function () { + return _this4._commitChanges(originalRecords, createdRecordsData); + }); + }); + }).then(function (records) { + if (opts.raw) { + adapterResponse.data = records; + } else { + adapterResponse = records; + } + var result = _this4._end(adapterResponse, opts); + opts.op = 'afterCreateMany'; + return _this4._runHook(opts.op, records, opts, result); + }); + }, + + + /** + * Create an unsaved, uncached instance of this Mapper's + * {@link Mapper#recordClass}. + * + * Returns `props` if `props` is already an instance of + * {@link Mapper#recordClass}. + * + * __Note:__ This method does __not__ interact with any adapter, and does + * __not__ save any data. It only creates new objects in memory. + * + * @example + * // Create empty unsaved record instance + * const post = PostMapper.createRecord(); + * + * @example + * // Create an unsaved record instance with inital properties + * const post = PostMapper.createRecord({ + * title: 'Modeling your data', + * status: 'draft' + * }); + * + * @example + * // Create a record instance that corresponds to a saved record + * const post = PostMapper.createRecord({ + * // JSData thinks this record has been saved if it has a primary key + * id: 1234, + * title: 'Modeling your data', + * status: 'draft' + * }); + * + * @example + * // Create record instances from an array + * const posts = PostMapper.createRecord([{ + * title: 'Modeling your data', + * status: 'draft' + * }, { + * title: 'Reading data', + * status: 'draft' + * }]); + * + * @example + * // Records are validated by default + * import { Mapper } from 'js-data'; + * const PostMapper = new Mapper({ + * name: 'post', + * schema: { properties: { title: { type: 'string' } } } + * }); + * try { + * const post = PostMapper.createRecord({ + * title: 1234, + * }); + * } catch (err) { + * console.log(err.errors); // [{ expected: 'one of (string)', actual: 'number', path: 'title' }] + * } + * + * @example + * // Skip validation + * import { Mapper } from 'js-data'; + * const PostMapper = new Mapper({ + * name: 'post', + * schema: { properties: { title: { type: 'string' } } } + * }); + * const post = PostMapper.createRecord({ + * title: 1234, + * }, { noValidate: true }); + * console.log(post.isValid()); // false + * + * @method Mapper#createRecord + * @param {Object|Object[]} props The properties for the Record instance or an + * array of property objects for the Record instances. + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}. + * @returns {Record|Record[]} The Record instance or Record instances. + * @since 3.0.0 + */ + createRecord: function createRecord(props, opts) { + var _this5 = this; + + props || (props = {}); + if (utils.isArray(props)) { + return props.map(function (_props) { + return _this5.createRecord(_props, opts); + }); + } + if (!utils.isObject(props)) { + throw utils.err(DOMAIN$6 + '#createRecord', 'props')(400, 'array or object', props); + } + + if (this.relationList) { + this.relationList.forEach(function (def) { + def.ensureLinkedDataHasProperType(props, opts); + }); + } + var RecordCtor = this.recordClass; + + return !RecordCtor || props instanceof RecordCtor ? props : new RecordCtor(props, opts); + }, + + + /** + * Lifecycle invocation method. You probably won't call this method directly. + * + * @method Mapper#crud + * @param {string} method Name of the lifecycle method to invoke. + * @param {...*} args Arguments to pass to the lifecycle method. + * @returns {Promise} + * @since 3.0.0 + */ + crud: function crud(method) { + var _this6 = this; + + for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + var config = this.lifecycleMethods[method]; + if (!config) { + throw utils.err(DOMAIN$6 + '#crud', method)(404, 'method'); + } + + var upper = '' + method.charAt(0).toUpperCase() + method.substr(1); + var before = 'before' + upper; + var after = 'after' + upper; + + var op = void 0, + adapter = void 0; + + // Default values for arguments + config.defaults.forEach(function (value, i) { + if (args[i] === undefined) { + args[i] = utils.copy(value); + } + }); + + var opts = args[args.length - 1]; + + // Fill in "opts" with the Mapper's configuration + utils._(opts, this); + adapter = opts.adapter = this.getAdapterName(opts); + + // before lifecycle hook + op = opts.op = before; + return utils.resolve(this[op].apply(this, toConsumableArray(args))).then(function (_value) { + var _getAdapter; + + if (args[config.beforeAssign] !== undefined) { + // Allow for re-assignment from lifecycle hook + args[config.beforeAssign] = _value === undefined ? args[config.beforeAssign] : _value; + } + // Now delegate to the adapter + op = opts.op = method; + args = config.adapterArgs ? config.adapterArgs.apply(config, [_this6].concat(toConsumableArray(args))) : args; + _this6.dbg.apply(_this6, [op].concat(toConsumableArray(args))); + return utils.resolve((_getAdapter = _this6.getAdapter(adapter))[op].apply(_getAdapter, [_this6].concat(toConsumableArray(args)))); + }).then(function (result) { + result = _this6._end(result, opts, !!config.skip); + args.push(result); + // after lifecycle hook + op = opts.op = after; + return utils.resolve(_this6[op].apply(_this6, toConsumableArray(args))).then(function (_result) { + // Allow for re-assignment from lifecycle hook + return _result === undefined ? result : _result; + }); + }); + }, + + + /** + * Fired during {@link Mapper#destroy}. See + * {@link Mapper~beforeDestroyListener} for how to listen for this event. + * + * @event Mapper#beforeDestroy + * @see Mapper~beforeDestroyListener + * @see Mapper#destroy + */ + /** + * Callback signature for the {@link Mapper#event:beforeDestroy} event. + * + * @example + * function onBeforeDestroy (id, opts) { + * // do something + * } + * store.on('beforeDestroy', onBeforeDestroy); + * + * @callback Mapper~beforeDestroyListener + * @param {string|number} id The `id` argument passed to {@link Mapper#beforeDestroy}. + * @param {object} opts The `opts` argument passed to {@link Mapper#beforeDestroy}. + * @see Mapper#event:beforeDestroy + * @see Mapper#destroy + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#destroy}. See + * {@link Mapper~afterDestroyListener} for how to listen for this event. + * + * @event Mapper#afterDestroy + * @see Mapper~afterDestroyListener + * @see Mapper#destroy + */ + /** + * Callback signature for the {@link Mapper#event:afterDestroy} event. + * + * @example + * function onAfterDestroy (id, opts, result) { + * // do something + * } + * store.on('afterDestroy', onAfterDestroy); + * + * @callback Mapper~afterDestroyListener + * @param {string|number} id The `id` argument passed to {@link Mapper#afterDestroy}. + * @param {object} opts The `opts` argument passed to {@link Mapper#afterDestroy}. + * @param {object} result The `result` argument passed to {@link Mapper#afterDestroy}. + * @see Mapper#event:afterDestroy + * @see Mapper#destroy + * @since 3.0.0 + */ + /** + * Using an adapter, destroy the record with the given primary key. + * + * {@link Mapper#beforeDestroy} will be called before destroying the record. + * {@link Mapper#afterDestroy} will be called after destroying the record. + * + * @example + * // Destroy a specific blog post + * PostMapper.destroy(1234).then(() => { + * // Blog post #1234 has been destroyed + * }); + * + * @example + * // Get full response + * PostMapper.destroy(1234, { raw: true }).then((result) => { + * console.log(result.deleted); e.g. 1 + * console.log(...); // etc., more metadata can be found on the result + * }); + * + * @fires Mapper#beforeDestroy + * @fires Mapper#afterDestroy + * @method Mapper#destroy + * @param {(string|number)} id The primary key of the record to destroy. + * @param {object} [opts] Configuration options. Refer to the `destroy` method + * of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @returns {Promise} Resolves when the record has been destroyed. Resolves + * even if no record was found to be destroyed. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/saving-data","Saving data"] + */ + destroy: function destroy(id, opts) { + return this.crud('destroy', id, opts); + }, + + + /** + * Fired during {@link Mapper#destroyAll}. See + * {@link Mapper~beforeDestroyAllListener} for how to listen for this event. + * + * @event Mapper#beforeDestroyAll + * @see Mapper~beforeDestroyAllListener + * @see Mapper#destroyAll + */ + /** + * Callback signature for the {@link Mapper#event:beforeDestroyAll} event. + * + * @example + * function onBeforeDestroyAll (query, opts) { + * // do something + * } + * store.on('beforeDestroyAll', onBeforeDestroyAll); + * + * @callback Mapper~beforeDestroyAllListener + * @param {object} query The `query` argument passed to {@link Mapper#beforeDestroyAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#beforeDestroyAll}. + * @see Mapper#event:beforeDestroyAll + * @see Mapper#destroyAll + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#destroyAll}. See + * {@link Mapper~afterDestroyAllListener} for how to listen for this event. + * + * @event Mapper#afterDestroyAll + * @see Mapper~afterDestroyAllListener + * @see Mapper#destroyAll + */ + /** + * Callback signature for the {@link Mapper#event:afterDestroyAll} event. + * + * @example + * function onAfterDestroyAll (query, opts, result) { + * // do something + * } + * store.on('afterDestroyAll', onAfterDestroyAll); + * + * @callback Mapper~afterDestroyAllListener + * @param {object} query The `query` argument passed to {@link Mapper#afterDestroyAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#afterDestroyAll}. + * @param {object} result The `result` argument passed to {@link Mapper#afterDestroyAll}. + * @see Mapper#event:afterDestroyAll + * @see Mapper#destroyAll + * @since 3.0.0 + */ + /** + * Destroy the records selected by `query` via an adapter. If no `query` is + * provided then all records will be destroyed. + * + * {@link Mapper#beforeDestroyAll} will be called before destroying the records. + * {@link Mapper#afterDestroyAll} will be called after destroying the records. + * + * @example + * // Destroy all blog posts + * PostMapper.destroyAll().then(() => { + * // All blog posts have been destroyed + * }); + * + * @example + * // Destroy all "draft" blog posts + * PostMapper.destroyAll({ status: 'draft' }).then(() => { + * // All "draft" blog posts have been destroyed + * }); + * + * @example + * // Get full response + * const query = null; + * const options = { raw: true }; + * PostMapper.destroyAll(query, options).then((result) => { + * console.log(result.deleted); e.g. 14 + * console.log(...); // etc., more metadata can be found on the result + * }); + * + * @fires Mapper#beforeDestroyAll + * @fires Mapper#afterDestroyAll + * @method Mapper#destroyAll + * @param {object} [query={}] Selection query. See {@link query}. + * @param {object} [query.where] See {@link query.where}. + * @param {number} [query.offset] See {@link query.offset}. + * @param {number} [query.limit] See {@link query.limit}. + * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}. + * @param {object} [opts] Configuration options. Refer to the `destroyAll` + * method of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @returns {Promise} Resolves when the records have been destroyed. Resolves + * even if no records were found to be destroyed. + * @see query + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/saving-data","Saving data"] + */ + destroyAll: function destroyAll(query, opts) { + return this.crud('destroyAll', query, opts); + }, + + + /** + * Fired during {@link Mapper#find}. See + * {@link Mapper~beforeFindListener} for how to listen for this event. + * + * @event Mapper#beforeFind + * @see Mapper~beforeFindListener + * @see Mapper#find + */ + /** + * Callback signature for the {@link Mapper#event:beforeFind} event. + * + * @example + * function onBeforeFind (id, opts) { + * // do something + * } + * store.on('beforeFind', onBeforeFind); + * + * @callback Mapper~beforeFindListener + * @param {string|number} id The `id` argument passed to {@link Mapper#beforeFind}. + * @param {object} opts The `opts` argument passed to {@link Mapper#beforeFind}. + * @see Mapper#event:beforeFind + * @see Mapper#find + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#find}. See + * {@link Mapper~afterFindListener} for how to listen for this event. + * + * @event Mapper#afterFind + * @see Mapper~afterFindListener + * @see Mapper#find + */ + /** + * Callback signature for the {@link Mapper#event:afterFind} event. + * + * @example + * function onAfterFind (id, opts, result) { + * // do something + * } + * store.on('afterFind', onAfterFind); + * + * @callback Mapper~afterFindListener + * @param {string|number} id The `id` argument passed to {@link Mapper#afterFind}. + * @param {object} opts The `opts` argument passed to {@link Mapper#afterFind}. + * @param {object} result The `result` argument passed to {@link Mapper#afterFind}. + * @see Mapper#event:afterFind + * @see Mapper#find + * @since 3.0.0 + */ + /** + * Retrieve via an adapter the record with the given primary key. + * + * {@link Mapper#beforeFind} will be called before calling the adapter. + * {@link Mapper#afterFind} will be called after calling the adapter. + * + * @example + * PostMapper.find(1).then((post) => { + * console.log(post); // { id: 1, ...} + * }); + * + * @example + * // Get full response + * PostMapper.find(1, { raw: true }).then((result) => { + * console.log(result.data); // { id: 1, ...} + * console.log(result.found); // 1 + * console.log(...); // etc., more metadata can be found on the result + * }); + * + * @fires Mapper#beforeFind + * @fires Mapper#afterFind + * @method Mapper#find + * @param {(string|number)} id The primary key of the record to retrieve. + * @param {object} [opts] Configuration options. Refer to the `find` method + * of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @param {string[]} [opts.with=[]] Relations to eager load in the request. + * @returns {Promise} Resolves with the found record. Resolves with + * `undefined` if no record was found. + * @see http://www.js-data.io/v3.0/docs/reading-data + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/reading-data","Reading data"] + */ + find: function find(id, opts) { + return this.crud('find', id, opts); + }, + + + /** + * Fired during {@link Mapper#findAll}. See + * {@link Mapper~beforeFindAllListener} for how to listen for this event. + * + * @event Mapper#beforeFindAll + * @see Mapper~beforeFindAllListener + * @see Mapper#findAll + */ + /** + * Callback signature for the {@link Mapper#event:beforeFindAll} event. + * + * @example + * function onBeforeFindAll (query, opts) { + * // do something + * } + * store.on('beforeFindAll', onBeforeFindAll); + * + * @callback Mapper~beforeFindAllListener + * @param {object} query The `query` argument passed to {@link Mapper#beforeFindAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#beforeFindAll}. + * @see Mapper#event:beforeFindAll + * @see Mapper#findAll + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#findAll}. See + * {@link Mapper~afterFindAllListener} for how to listen for this event. + * + * @event Mapper#afterFindAll + * @see Mapper~afterFindAllListener + * @see Mapper#findAll + */ + /** + * Callback signature for the {@link Mapper#event:afterFindAll} event. + * + * @example + * function onAfterFindAll (query, opts, result) { + * // do something + * } + * store.on('afterFindAll', onAfterFindAll); + * + * @callback Mapper~afterFindAllListener + * @param {object} query The `query` argument passed to {@link Mapper#afterFindAll}. + * @param {object} opts The `opts` argument passed to {@link Mapper#afterFindAll}. + * @param {object} result The `result` argument passed to {@link Mapper#afterFindAll}. + * @see Mapper#event:afterFindAll + * @see Mapper#findAll + * @since 3.0.0 + */ + /** + * Using the `query` argument, select records to retrieve via an adapter. + * + * {@link Mapper#beforeFindAll} will be called before calling the adapter. + * {@link Mapper#afterFindAll} will be called after calling the adapter. + * + * @example + * // Find all "published" blog posts + * PostMapper.findAll({ status: 'published' }).then((posts) => { + * console.log(posts); // [{ id: 1, status: 'published', ...}, ...] + * }); + * + * @example + * // Get full response + * PostMapper.findAll({ status: 'published' }, { raw: true }).then((result) => { + * console.log(result.data); // [{ id: 1, status: 'published', ...}, ...] + * console.log(result.found); // e.g. 13 + * console.log(...); // etc., more metadata can be found on the result + * }); + * + * @fires Mapper#beforeFindAll + * @fires Mapper#afterFindAll + * @method Mapper#findAll + * @param {object} [query={}] Selection query. See {@link query}. + * @param {object} [query.where] See {@link query.where}. + * @param {number} [query.offset] See {@link query.offset}. + * @param {number} [query.limit] See {@link query.limit}. + * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}. + * @param {object} [opts] Configuration options. Refer to the `findAll` method + * of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @param {string[]} [opts.with=[]] Relations to eager load in the request. + * @returns {Promise} Resolves with the found records, if any. + * @see query + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/reading-data","Reading data"] + */ + findAll: function findAll(query, opts) { + return this.crud('findAll', query, opts); + }, + + + /** + * Return the registered adapter with the given name or the default adapter if + * no name is provided. + * + * @method Mapper#getAdapter + * @param {string} [name] The name of the adapter to retrieve. + * @returns {Adapter} The adapter. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/connecting-to-a-data-source","Connecting to a data source"] + */ + getAdapter: function getAdapter(name) { + this.dbg('getAdapter', 'name:', name); + var adapter = this.getAdapterName(name); + if (!adapter) { + throw utils.err(DOMAIN$6 + '#getAdapter', 'name')(400, 'string', name); + } + return this.getAdapters()[adapter]; + }, + + + /** + * Return the name of a registered adapter based on the given name or options, + * or the name of the default adapter if no name provided. + * + * @method Mapper#getAdapterName + * @param {(Object|string)} [opts] The name of an adapter or options, if any. + * @returns {string} The name of the adapter. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/connecting-to-a-data-source","Connecting to a data source"] + */ + getAdapterName: function getAdapterName(opts) { + opts || (opts = {}); + if (utils.isString(opts)) { + opts = { adapter: opts }; + } + return opts.adapter || opts.defaultAdapter; + }, + + + /** + * Get the object of registered adapters for this Mapper. + * + * @method Mapper#getAdapters + * @returns {Object} {@link Mapper#_adapters} + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/connecting-to-a-data-source","Connecting to a data source"] + */ + getAdapters: function getAdapters() { + return this._adapters; + }, + + + /** + * Returns this Mapper's {@link Schema}. + * + * @method Mapper#getSchema + * @returns {Schema} This Mapper's {@link Schema}. + * @see Mapper#schema + * @since 3.0.0 + */ + getSchema: function getSchema() { + return this.schema; + }, + + + /** + * Defines a hasMany relationship. Only useful if you're managing your + * Mappers manually and not using a Container or DataStore component. + * + * @example + * UserMapper.hasMany(PostMapper, { + * // post.user_id points to user.id + * foreignKey: 'user_id' + * // post records will be attached to user records at "user.posts" + * localField: 'posts' + * }); + * + * @method Mapper#hasMany + * @see http://www.js-data.io/v3.0/docs/relations + * @since 3.0.0 + */ + hasMany: function hasMany$$1(relatedMapper, opts) { + return hasMany(relatedMapper, opts)(this); + }, + + + /** + * Defines a hasOne relationship. Only useful if you're managing your Mappers + * manually and not using a {@link Container} or {@link DataStore} component. + * + * @example + * UserMapper.hasOne(ProfileMapper, { + * // profile.user_id points to user.id + * foreignKey: 'user_id' + * // profile records will be attached to user records at "user.profile" + * localField: 'profile' + * }); + * + * @method Mapper#hasOne + * @see http://www.js-data.io/v3.0/docs/relations + * @since 3.0.0 + */ + hasOne: function hasOne$$1(relatedMapper, opts) { + return hasOne(relatedMapper, opts)(this); + }, + + + /** + * Return whether `record` is an instance of this Mapper's recordClass. + * + * @example + * const post = PostMapper.createRecord(); + * + * console.log(PostMapper.is(post)); // true + * // Equivalent to what's above + * console.log(post instanceof PostMapper.recordClass); // true + * + * @method Mapper#is + * @param {Object|Record} record The record to check. + * @returns {boolean} Whether `record` is an instance of this Mapper's + * {@link Mapper#recordClass}. + * @since 3.0.0 + */ + is: function is(record) { + var recordClass = this.recordClass; + return recordClass ? record instanceof recordClass : false; + }, + + + /** + * Register an adapter on this Mapper under the given name. + * + * @method Mapper#registerAdapter + * @param {string} name The name of the adapter to register. + * @param {Adapter} adapter The adapter to register. + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.default=false] Whether to make the adapter the + * default adapter for this Mapper. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/connecting-to-a-data-source","Connecting to a data source"] + */ + registerAdapter: function registerAdapter(name, adapter, opts) { + opts || (opts = {}); + this.getAdapters()[name] = adapter; + // Optionally make it the default adapter for the target. + if (opts === true || opts.default) { + this.defaultAdapter = name; + } + }, + _runHook: function _runHook(hookName) { + for (var _len3 = arguments.length, hookArgs = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + hookArgs[_key3 - 1] = arguments[_key3]; + } + + var defaultValueIndex = hookName.indexOf('after') === 0 ? hookArgs.length - 1 : 0; + + return utils.resolve(this[hookName].apply(this, hookArgs)).then(function (overridenResult) { + return overridenResult === undefined ? hookArgs[defaultValueIndex] : overridenResult; + }); + }, + _invokeAdapterMethod: function _invokeAdapterMethod(method, propsOrRecords, opts) { + var _this7 = this; + + var conversionOptions = { with: opts.pass || [] }; + var object = void 0; + + this.dbg(opts.op, propsOrRecords, opts); + + if (utils.isArray(propsOrRecords)) { + object = propsOrRecords.map(function (record) { + return _this7.toJSON(record, conversionOptions); + }); + } else { + object = this.toJSON(propsOrRecords, conversionOptions); + } + + return this.getAdapter(opts.adapter)[method](this, object, opts); + }, + + + /** + * Select records according to the `query` argument, and aggregate the sum + * value of the property specified by `field`. + * + * {@link Mapper#beforeSum} will be called before calling the adapter. + * {@link Mapper#afterSum} will be called after calling the adapter. + * + * @example + * PurchaseOrderMapper.sum('amount', { status: 'paid' }).then((amountPaid) => { + * console.log(amountPaid); // e.g. 451125.34 + * }); + * + * @method Mapper#sum + * @param {string} field The field to sum. + * @param {object} [query={}] Selection query. See {@link query}. + * @param {object} [query.where] See {@link query.where}. + * @param {number} [query.offset] See {@link query.offset}. + * @param {number} [query.limit] See {@link query.limit}. + * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}. + * @param {object} [opts] Configuration options. Refer to the `sum` method + * of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @returns {Promise} Resolves with the aggregated sum. + * @since 3.0.0 + */ + sum: function sum(field, query, opts) { + return this.crud('sum', field, query, opts); + }, + + + /** + * Return a plain object representation of the given record. Relations can + * be optionally be included. Non-schema properties can be excluded. + * + * @example + * import { Mapper, Schema } from 'js-data'; + * const PersonMapper = new Mapper({ + * name: 'person', + * schema: { + * properties: { + * name: { type: 'string' }, + * id: { type: 'string' } + * } + * } + * }); + * const person = PersonMapper.createRecord({ id: 1, name: 'John', foo: 'bar' }); + * // "foo" is stripped by toJSON() + * console.log(PersonMapper.toJSON(person)); // {"id":1,"name":"John"} + * + * const PersonRelaxedMapper = new Mapper({ + * name: 'personRelaxed', + * schema: { + * properties: { + * name: { type: 'string' }, + * id: { type: 'string' } + * }, + * additionalProperties: true + * } + * }); + * const person2 = PersonRelaxedMapper.createRecord({ id: 1, name: 'John', foo: 'bar' }); + * // "foo" is not stripped by toJSON + * console.log(PersonRelaxedMapper.toJSON(person2)); // {"id":1,"name":"John","foo":"bar"} + * + * @method Mapper#toJSON + * @param {Record|Record[]} records Record or records from which to create a + * POJO representation. + * @param {object} [opts] Configuration options. + * @param {string[]} [opts.with] Array of relation names or relation fields + * to include in the POJO representation. + * @param {boolean} [opts.withAll] Whether to simply include all relations in + * the representation. Overrides `opts.with`. + * @returns {Object|Object[]} POJO representation of the record or records. + * @since 3.0.0 + */ + toJSON: function toJSON(records, opts) { + var _this8 = this; + + var record = void 0; + opts || (opts = {}); + if (utils.isArray(records)) { + return records.map(function (record) { + return _this8.toJSON(record, opts); + }); + } else { + record = records; + } + var relationFields = (this ? this.relationFields : []) || []; + var json = {}; + + // Copy properties defined in the schema + if (this && this.schema) { + json = this.schema.pick(record); + } else { + for (var key in record) { + if (relationFields.indexOf(key) === -1) { + json[key] = utils.plainCopy(record[key]); + } + } + } + + // The user wants to include relations in the resulting plain object representation + if (this && opts.withAll) { + opts.with = relationFields.slice(); + } + if (this && opts.with) { + if (utils.isString(opts.with)) { + opts.with = [opts.with]; + } + utils.forEachRelation(this, opts, function (def, optsCopy) { + var relationData = def.getLocalField(record); + if (relationData) { + // The actual recursion + if (utils.isArray(relationData)) { + def.setLocalField(json, relationData.map(function (item) { + return def.getRelation().toJSON(item, optsCopy); + })); + } else { + def.setLocalField(json, def.getRelation().toJSON(relationData, optsCopy)); + } + } + }); + } + return json; + }, + + + /** + * Fired during {@link Mapper#update}. See + * {@link Mapper~beforeUpdateListener} for how to listen for this event. + * + * @event Mapper#beforeUpdate + * @see Mapper~beforeUpdateListener + * @see Mapper#update + */ + /** + * Callback signature for the {@link Mapper#event:beforeUpdate} event. + * + * @example + * function onBeforeUpdate (id, props, opts) { + * // do something + * } + * store.on('beforeUpdate', onBeforeUpdate); + * + * @callback Mapper~beforeUpdateListener + * @param {string|number} id The `id` argument passed to {@link Mapper#beforeUpdate}. + * @param {object} props The `props` argument passed to {@link Mapper#beforeUpdate}. + * @param {object} opts The `opts` argument passed to {@link Mapper#beforeUpdate}. + * @see Mapper#event:beforeUpdate + * @see Mapper#update + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#update}. See + * {@link Mapper~afterUpdateListener} for how to listen for this event. + * + * @event Mapper#afterUpdate + * @see Mapper~afterUpdateListener + * @see Mapper#update + */ + /** + * Callback signature for the {@link Mapper#event:afterUpdate} event. + * + * @example + * function onAfterUpdate (id, props, opts, result) { + * // do something + * } + * store.on('afterUpdate', onAfterUpdate); + * + * @callback Mapper~afterUpdateListener + * @param {string|number} id The `id` argument passed to {@link Mapper#afterUpdate}. + * @param {object} props The `props` argument passed to {@link Mapper#afterUpdate}. + * @param {object} opts The `opts` argument passed to {@link Mapper#afterUpdate}. + * @param {object} result The `result` argument passed to {@link Mapper#afterUpdate}. + * @see Mapper#event:afterUpdate + * @see Mapper#update + * @since 3.0.0 + */ + /** + * Using an adapter, update the record with the primary key specified by the + * `id` argument. + * + * {@link Mapper#beforeUpdate} will be called before updating the record. + * {@link Mapper#afterUpdate} will be called after updating the record. + * + * @example + * // Update a specific post + * PostMapper.update(1234, { + * status: 'published', + * published_at: new Date() + * }).then((post) => { + * console.log(post); // { id: 1234, status: 'published', ... } + * }); + * + * @fires Mapper#beforeUpdate + * @fires Mapper#afterUpdate + * @method Mapper#update + * @param {(string|number)} id The primary key of the record to update. + * @param {object} props The update to apply to the record. + * @param {object} [opts] Configuration options. Refer to the `update` method + * of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * transaction. + * @returns {Promise} Resolves with the updated record. Rejects if the record + * could not be found. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/saving-data","Saving data"] + */ + update: function update(id, props, opts) { + return this.crud('update', id, props, opts); + }, + + + /** + * Fired during {@link Mapper#updateAll}. See + * {@link Mapper~beforeUpdateAllListener} for how to listen for this event. + * + * @event Mapper#beforeUpdateAll + * @see Mapper~beforeUpdateAllListener + * @see Mapper#updateAll + */ + /** + * Callback signature for the {@link Mapper#event:beforeUpdateAll} event. + * + * @example + * function onBeforeUpdateAll (props, query, opts) { + * // do something + * } + * store.on('beforeUpdateAll', onBeforeUpdateAll); + * + * @callback Mapper~beforeUpdateAllListener + * @param {object} props The `props` argument received by {@link Mapper#beforeUpdateAll}. + * @param {object} query The `query` argument received by {@link Mapper#beforeUpdateAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateAll}. + * @see Mapper#event:beforeUpdateAll + * @see Mapper#updateAll + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#updateAll}. See + * {@link Mapper~afterUpdateAllListener} for how to listen for this event. + * + * @event Mapper#afterUpdateAll + * @see Mapper~afterUpdateAllListener + * @see Mapper#updateAll + */ + /** + * Callback signature for the {@link Mapper#event:afterUpdateAll} event. + * + * @example + * function onAfterUpdateAll (props, query, opts, result) { + * // do something + * } + * store.on('afterUpdateAll', onAfterUpdateAll); + * + * @callback Mapper~afterUpdateAllListener + * @param {object} props The `props` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} query The `query` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} result The `result` argument received by {@link Mapper#afterUpdateAll}. + * @see Mapper#event:afterUpdateAll + * @see Mapper#updateAll + * @since 3.0.0 + */ + /** + * Using the `query` argument, perform the a single updated to the selected + * records. + * + * {@link Mapper#beforeUpdateAll} will be called before making the update. + * {@link Mapper#afterUpdateAll} will be called after making the update. + * + * @example + * // Turn all of John's blog posts into drafts. + * const update = { status: draft: published_at: null }; + * const query = { userId: 1234 }; + * PostMapper.updateAll(update, query).then((posts) => { + * console.log(posts); // [...] + * }); + * + * @fires Mapper#beforeUpdateAll + * @fires Mapper#afterUpdateAll + * @method Mapper#updateAll + * @param {object} props Update to apply to selected records. + * @param {object} [query={}] Selection query. See {@link query}. + * @param {object} [query.where] See {@link query.where}. + * @param {number} [query.offset] See {@link query.offset}. + * @param {number} [query.limit] See {@link query.limit}. + * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}. + * @param {object} [opts] Configuration options. Refer to the `updateAll` + * method of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @returns {Promise} Resolves with the update records, if any. + * @see query + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/saving-data","Saving data"] + */ + updateAll: function updateAll(props, query, opts) { + return this.crud('updateAll', props, query, opts); + }, + + + /** + * Fired during {@link Mapper#updateMany}. See + * {@link Mapper~beforeUpdateManyListener} for how to listen for this event. + * + * @event Mapper#beforeUpdateMany + * @see Mapper~beforeUpdateManyListener + * @see Mapper#updateMany + */ + /** + * Callback signature for the {@link Mapper#event:beforeUpdateMany} event. + * + * @example + * function onBeforeUpdateMany (records, opts) { + * // do something + * } + * store.on('beforeUpdateMany', onBeforeUpdateMany); + * + * @callback Mapper~beforeUpdateManyListener + * @param {object} records The `records` argument received by {@link Mapper#beforeUpdateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateMany}. + * @see Mapper#event:beforeUpdateMany + * @see Mapper#updateMany + * @since 3.0.0 + */ + /** + * Fired during {@link Mapper#updateMany}. See + * {@link Mapper~afterUpdateManyListener} for how to listen for this event. + * + * @event Mapper#afterUpdateMany + * @see Mapper~afterUpdateManyListener + * @see Mapper#updateMany + */ + /** + * Callback signature for the {@link Mapper#event:afterUpdateMany} event. + * + * @example + * function onAfterUpdateMany (records, opts, result) { + * // do something + * } + * store.on('afterUpdateMany', onAfterUpdateMany); + * + * @callback Mapper~afterUpdateManyListener + * @param {object} records The `records` argument received by {@link Mapper#afterUpdateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateMany}. + * @param {object} result The `result` argument received by {@link Mapper#afterUpdateMany}. + * @see Mapper#event:afterUpdateMany + * @see Mapper#updateMany + * @since 3.0.0 + */ + /** + * Given an array of updates, perform each of the updates via an adapter. Each + * "update" is a hash of properties with which to update an record. Each + * update must contain the primary key of the record to be updated. + * + * {@link Mapper#beforeUpdateMany} will be called before making the update. + * {@link Mapper#afterUpdateMany} will be called after making the update. + * + * @example + * PostMapper.updateMany([ + * { id: 1234, status: 'draft' }, + * { id: 2468, status: 'published', published_at: new Date() } + * ]).then((posts) => { + * console.log(posts); // [...] + * }); + * + * @fires Mapper#beforeUpdateMany + * @fires Mapper#afterUpdateMany + * @method Mapper#updateMany + * @param {Record[]} records Array up record updates. + * @param {object} [opts] Configuration options. Refer to the `updateMany` + * method of whatever adapter you're using for more configuration options. + * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the + * adapter to use. + * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}. + * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}. + * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}. + * @returns {Promise} Resolves with the updated records. Rejects if any of the + * records could be found. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/saving-data","Saving data"] + */ + updateMany: function updateMany(records, opts) { + return this.crud('updateMany', records, opts); + }, + + + /** + * Validate the given record or records according to this Mapper's + * {@link Schema}. If there are no validation errors then the return value + * will be `undefined`. + * + * @example + * import {Mapper, Schema} from 'js-data' + * const PersonSchema = new Schema({ + * properties: { + * name: { type: 'string' }, + * id: { type: 'string' } + * } + * }); + * const PersonMapper = new Mapper({ + * name: 'person', + * schema: PersonSchema + * }); + * let errors = PersonMapper.validate({ name: 'John' }); + * console.log(errors); // undefined + * errors = PersonMapper.validate({ name: 123 }); + * console.log(errors); // [{ expected: 'one of (string)', actual: 'number', path: 'name' }] + * + * @method Mapper#validate + * @param {Object|Object[]} record The record or records to validate. + * @param {object} [opts] Configuration options. Passed to + * {@link Schema#validate}. + * @returns {Object[]} Array of errors or `undefined` if no errors. + * @since 3.0.0 + */ + validate: function validate(record, opts) { + opts || (opts = {}); + var schema = this.getSchema(); + if (!schema) { + return; + } + var _opts = utils.pick(opts, ['existingOnly']); + if (utils.isArray(record)) { + var errors = record.map(function (_record) { + return schema.validate(_record, utils.pick(_opts, ['existingOnly'])); + }); + + return errors.some(Boolean) ? errors : undefined; + } + return schema.validate(record, _opts); + }, + + + /** + * Method used to wrap data returned by an adapter with this Mapper's + * {@link Mapper#recordClass}. This method is used by all of a Mapper's CRUD + * methods. The provided implementation of this method assumes that the `data` + * passed to it is a record or records that need to be wrapped with + * {@link Mapper#createRecord}. Override with care. + * + * Provided implementation of {@link Mapper#wrap}: + * + * ``` + * function (data, opts) { + * return this.createRecord(data, opts); + * } + * ``` + * + * @example + * const PostMapper = new Mapper({ + * name: 'post', + * // Override to customize behavior + * wrap (data, opts) { + * const originalWrap = this.constructor.prototype.wrap; + * // Let's say "GET /post" doesn't return JSON quite like JSData expects, + * // but the actual post records are nested under a "posts" field. So, + * // we override Mapper#wrap to handle this special case. + * if (opts.op === 'findAll') { + * return originalWrap.call(this, data.posts, opts); + * } + * // Otherwise perform original behavior + * return originalWrap.call(this, data, opts); + * } + * }); + * + * @method Mapper#wrap + * @param {Object|Object[]} data The record or records to be wrapped. + * @param {object} [opts] Configuration options. Passed to {@link Mapper#createRecord}. + * @returns {Record|Record[]} The wrapped record or records. + * @since 3.0.0 + */ + wrap: function wrap(data, opts) { + return this.createRecord(data, opts); + }, + + + /** + * @ignore + */ + defineRelations: function defineRelations() { + var _this9 = this; + + // Setup the mapper's relations, including generating Mapper#relationList + // and Mapper#relationFields + utils.forOwn(this.relations, function (group, type) { + utils.forOwn(group, function (relations, _name) { + if (utils.isObject(relations)) { + relations = [relations]; + } + relations.forEach(function (def) { + var relatedMapper = _this9.datastore.getMapperByName(_name) || _name; + def.getRelation = function () { + return _this9.datastore.getMapper(_name); + }; + + if (typeof Relation[type] !== 'function') { + throw utils.err(DOMAIN$6, 'defineRelations')(400, 'relation type (hasOne, hasMany, etc)', type, true); + } + + _this9[type](relatedMapper, def); + }); + }); + }); + } +}); + +/** + * Create a subclass of this Mapper: + * + * @example Mapper.extend + * const JSData = require('js-data'); + * const { Mapper } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomMapperClass extends Mapper { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * }; + * const customMapper = new CustomMapperClass(); + * console.log(customMapper.foo()); + * console.log(CustomMapperClass.beep()); + * + * // Extend the class using alternate method. + * const OtherMapperClass = Mapper.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherMapper = new OtherMapperClass(); + * console.log(otherMapper.foo()); + * console.log(OtherMapperClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherMapperClass () { + * Mapper.call(this); + * this.created_at = new Date().getTime(); + * } + * Mapper.extend({ + * constructor: AnotherMapperClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }) + * const anotherMapper = new AnotherMapperClass(); + * console.log(anotherMapper.created_at); + * console.log(anotherMapper.foo()); + * console.log(AnotherMapperClass.beep()); + * + * @method Mapper.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this Mapper class. + * @since 3.0.0 + */ + +var DOMAIN$5 = 'Container'; + +var proxiedMapperMethods = [ +/** + * Wrapper for {@link Mapper#count}. + * + * @example + * // Get the number of published blog posts + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.count('post', { status: 'published' }).then((numPublished) => { + * console.log(numPublished); // e.g. 45 + * }); + * + * @method Container#count + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} [query] See {@link Mapper#count}. + * @param {object} [opts] See {@link Mapper#count}. + * @returns {Promise} See {@link Mapper#count}. + * @see Mapper#count + * @since 3.0.0 + */ +'count', + +/** + * Fired during {@link Container#create}. See + * {@link Container~beforeCreateListener} for how to listen for this event. + * + * @event Container#beforeCreate + * @see Container~beforeCreateListener + * @see Container#create + */ +/** + * Callback signature for the {@link Container#event:beforeCreate} event. + * + * @example + * function onBeforeCreate (mapperName, props, opts) { + * // do something + * } + * store.on('beforeCreate', onBeforeCreate); + * + * @callback Container~beforeCreateListener + * @param {string} name The `name` argument received by {@link Mapper#beforeCreate}. + * @param {object} props The `props` argument received by {@link Mapper#beforeCreate}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreate}. + * @see Container#event:beforeCreate + * @see Container#create + * @since 3.0.0 + */ +/** + * Fired during {@link Container#create}. See + * {@link Container~afterCreateListener} for how to listen for this event. + * + * @event Container#afterCreate + * @see Container~afterCreateListener + * @see Container#create + */ +/** + * Callback signature for the {@link Container#event:afterCreate} event. + * + * @example + * function onAfterCreate (mapperName, props, opts, result) { + * // do something + * } + * store.on('afterCreate', onAfterCreate); + * + * @callback Container~afterCreateListener + * @param {string} name The `name` argument received by {@link Mapper#afterCreate}. + * @param {object} props The `props` argument received by {@link Mapper#afterCreate}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterCreate}. + * @param {object} result The `result` argument received by {@link Mapper#afterCreate}. + * @see Container#event:afterCreate + * @see Container#create + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#create}. + * + * @example + * // Create and save a new blog post + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.create('post', { + * title: 'Modeling your data', + * status: 'draft' + * }).then((post) => { + * console.log(post); // { id: 1234, status: 'draft', ... } + * }); + * + * @fires Container#beforeCreate + * @fires Container#afterCreate + * @method Container#create + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} props See {@link Mapper#create}. + * @param {object} [opts] See {@link Mapper#create}. + * @returns {Promise} See {@link Mapper#create}. + * @see Mapper#create + * @since 3.0.0 + */ +'create', + +/** + * Fired during {@link Container#createMany}. See + * {@link Container~beforeCreateManyListener} for how to listen for this event. + * + * @event Container#beforeCreateMany + * @see Container~beforeCreateManyListener + * @see Container#createMany + */ +/** + * Callback signature for the {@link Container#event:beforeCreateMany} event. + * + * @example + * function onBeforeCreateMany (mapperName, records, opts) { + * // do something + * } + * store.on('beforeCreateMany', onBeforeCreateMany); + * + * @callback Container~beforeCreateManyListener + * @param {string} name The `name` argument received by {@link Mapper#beforeCreateMany}. + * @param {object} records The `records` argument received by {@link Mapper#beforeCreateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreateMany}. + * @see Container#event:beforeCreateMany + * @see Container#createMany + * @since 3.0.0 + */ +/** + * Fired during {@link Container#createMany}. See + * {@link Container~afterCreateManyListener} for how to listen for this event. + * + * @event Container#afterCreateMany + * @see Container~afterCreateManyListener + * @see Container#createMany + */ +/** + * Callback signature for the {@link Container#event:afterCreateMany} event. + * + * @example + * function onAfterCreateMany (mapperName, records, opts, result) { + * // do something + * } + * store.on('afterCreateMany', onAfterCreateMany); + * + * @callback Container~afterCreateManyListener + * @param {string} name The `name` argument received by {@link Mapper#afterCreateMany}. + * @param {object} records The `records` argument received by {@link Mapper#afterCreateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterCreateMany}. + * @param {object} result The `result` argument received by {@link Mapper#afterCreateMany}. + * @see Container#event:afterCreateMany + * @see Container#createMany + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#createMany}. + * + * @example + * // Create and save several new blog posts + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.createMany('post', [{ + * title: 'Modeling your data', + * status: 'draft' + * }, { + * title: 'Reading data', + * status: 'draft' + * }]).then((posts) => { + * console.log(posts[0]); // { id: 1234, status: 'draft', ... } + * console.log(posts[1]); // { id: 1235, status: 'draft', ... } + * }); + * + * @fires Container#beforeCreateMany + * @fires Container#afterCreateMany + * @method Container#createMany + * @param {string} name Name of the {@link Mapper} to target. + * @param {Record[]} records See {@link Mapper#createMany}. + * @param {object} [opts] See {@link Mapper#createMany}. + * @returns {Promise} See {@link Mapper#createMany}. + * @see Mapper#createMany + * @since 3.0.0 + */ +'createMany', + +/** + * Wrapper for {@link Mapper#createRecord}. + * + * __Note:__ This method does __not__ interact with any adapter, and does + * __not__ save any data. It only creates new objects in memory. + * + * @example + * // Create empty unsaved record instance + * import { Container } from 'js-data'; + * const store = new Container(); + * store.defineMapper('post'); + * const post = PostMapper.createRecord(); + * + * @method Container#createRecord + * @param {string} name Name of the {@link Mapper} to target. + * @param {Object|Object[]} props See {@link Mapper#createRecord}. + * @param {object} [opts] See {@link Mapper#createRecord}. + * @returns {Promise} See {@link Mapper#createRecord}. + * @see Mapper#createRecord + * @since 3.0.0 + */ +'createRecord', + +/** + * Fired during {@link Container#destroy}. See + * {@link Container~beforeDestroyListener} for how to listen for this event. + * + * @event Container#beforeDestroy + * @see Container~beforeDestroyListener + * @see Container#destroy + */ +/** + * Callback signature for the {@link Container#event:beforeDestroy} event. + * + * @example + * function onBeforeDestroy (mapperName, id, opts) { + * // do something + * } + * store.on('beforeDestroy', onBeforeDestroy); + * + * @callback Container~beforeDestroyListener + * @param {string} name The `name` argument received by {@link Mapper#beforeDestroy}. + * @param {string|number} id The `id` argument received by {@link Mapper#beforeDestroy}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroy}. + * @see Container#event:beforeDestroy + * @see Container#destroy + * @since 3.0.0 + */ +/** + * Fired during {@link Container#destroy}. See + * {@link Container~afterDestroyListener} for how to listen for this event. + * + * @event Container#afterDestroy + * @see Container~afterDestroyListener + * @see Container#destroy + */ +/** + * Callback signature for the {@link Container#event:afterDestroy} event. + * + * @example + * function onAfterDestroy (mapperName, id, opts, result) { + * // do something + * } + * store.on('afterDestroy', onAfterDestroy); + * + * @callback Container~afterDestroyListener + * @param {string} name The `name` argument received by {@link Mapper#afterDestroy}. + * @param {string|number} id The `id` argument received by {@link Mapper#afterDestroy}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterDestroy}. + * @param {object} result The `result` argument received by {@link Mapper#afterDestroy}. + * @see Container#event:afterDestroy + * @see Container#destroy + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#destroy}. + * + * @example + * // Destroy a specific blog post + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.destroy('post', 1234).then(() => { + * // Blog post #1234 has been destroyed + * }); + * + * @fires Container#beforeDestroy + * @fires Container#afterDestroy + * @method Container#destroy + * @param {string} name Name of the {@link Mapper} to target. + * @param {(string|number)} id See {@link Mapper#destroy}. + * @param {object} [opts] See {@link Mapper#destroy}. + * @returns {Promise} See {@link Mapper#destroy}. + * @see Mapper#destroy + * @since 3.0.0 + */ +'destroy', + +/** + * Fired during {@link Container#destroyAll}. See + * {@link Container~beforeDestroyAllListener} for how to listen for this event. + * + * @event Container#beforeDestroyAll + * @see Container~beforeDestroyAllListener + * @see Container#destroyAll + */ +/** + * Callback signature for the {@link Container#event:beforeDestroyAll} event. + * + * @example + * function onBeforeDestroyAll (mapperName, query, opts) { + * // do something + * } + * store.on('beforeDestroyAll', onBeforeDestroyAll); + * + * @callback Container~beforeDestroyAllListener + * @param {string} name The `name` argument received by {@link Mapper#beforeDestroyAll}. + * @param {object} query The `query` argument received by {@link Mapper#beforeDestroyAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroyAll}. + * @see Container#event:beforeDestroyAll + * @see Container#destroyAll + * @since 3.0.0 + */ +/** + * Fired during {@link Container#destroyAll}. See + * {@link Container~afterDestroyAllListener} for how to listen for this event. + * + * @event Container#afterDestroyAll + * @see Container~afterDestroyAllListener + * @see Container#destroyAll + */ +/** + * Callback signature for the {@link Container#event:afterDestroyAll} event. + * + * @example + * function onAfterDestroyAll (mapperName, query, opts, result) { + * // do something + * } + * store.on('afterDestroyAll', onAfterDestroyAll); + * + * @callback Container~afterDestroyAllListener + * @param {string} name The `name` argument received by {@link Mapper#afterDestroyAll}. + * @param {object} query The `query` argument received by {@link Mapper#afterDestroyAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterDestroyAll}. + * @param {object} result The `result` argument received by {@link Mapper#afterDestroyAll}. + * @see Container#event:afterDestroyAll + * @see Container#destroyAll + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#destroyAll}. + * + * @example + * // Destroy all "draft" blog posts + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.destroyAll('post', { status: 'draft' }).then(() => { + * // All "draft" blog posts have been destroyed + * }); + * + * @fires Container#beforeDestroyAll + * @fires Container#afterDestroyAll + * @method Container#destroyAll + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} [query] See {@link Mapper#destroyAll}. + * @param {object} [opts] See {@link Mapper#destroyAll}. + * @returns {Promise} See {@link Mapper#destroyAll}. + * @see Mapper#destroyAll + * @since 3.0.0 + */ +'destroyAll', + +/** + * Fired during {@link Container#find}. See + * {@link Container~beforeFindListener} for how to listen for this event. + * + * @event Container#beforeFind + * @see Container~beforeFindListener + * @see Container#find + */ +/** + * Callback signature for the {@link Container#event:beforeFind} event. + * + * @example + * function onBeforeFind (mapperName, id, opts) { + * // do something + * } + * store.on('beforeFind', onBeforeFind); + * + * @callback Container~beforeFindListener + * @param {string} name The `name` argument received by {@link Mapper#beforeFind}. + * @param {string|number} id The `id` argument received by {@link Mapper#beforeFind}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeFind}. + * @see Container#event:beforeFind + * @see Container#find + * @since 3.0.0 + */ +/** + * Fired during {@link Container#find}. See + * {@link Container~afterFindListener} for how to listen for this event. + * + * @event Container#afterFind + * @see Container~afterFindListener + * @see Container#find + */ +/** + * Callback signature for the {@link Container#event:afterFind} event. + * + * @example + * function onAfterFind (mapperName, id, opts, result) { + * // do something + * } + * store.on('afterFind', onAfterFind); + * + * @callback Container~afterFindListener + * @param {string} name The `name` argument received by {@link Mapper#afterFind}. + * @param {string|number} id The `id` argument received by {@link Mapper#afterFind}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterFind}. + * @param {object} result The `result` argument received by {@link Mapper#afterFind}. + * @see Container#event:afterFind + * @see Container#find + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#find}. + * + * @example + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.find('post', 1).then((post) => { + * console.log(post) // { id: 1, ...} + * }); + * + * @fires Container#beforeFind + * @fires Container#afterFind + * @method Container#find + * @param {string} name Name of the {@link Mapper} to target. + * @param {(string|number)} id See {@link Mapper#find}. + * @param {object} [opts] See {@link Mapper#find}. + * @returns {Promise} See {@link Mapper#find}. + * @see Mapper#find + * @since 3.0.0 + */ +'find', + +/** + * Fired during {@link Container#findAll}. See + * {@link Container~beforeFindAllListener} for how to listen for this event. + * + * @event Container#beforeFindAll + * @see Container~beforeFindAllListener + * @see Container#findAll + */ +/** + * Callback signature for the {@link Container#event:beforeFindAll} event. + * + * @example + * function onBeforeFindAll (mapperName, query, opts) { + * // do something + * } + * store.on('beforeFindAll', onBeforeFindAll); + * + * @callback Container~beforeFindAllListener + * @param {string} name The `name` argument received by {@link Mapper#beforeFindAll}. + * @param {object} query The `query` argument received by {@link Mapper#beforeFindAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeFindAll}. + * @see Container#event:beforeFindAll + * @see Container#findAll + * @since 3.0.0 + */ +/** + * Fired during {@link Container#findAll}. See + * {@link Container~afterFindAllListener} for how to listen for this event. + * + * @event Container#afterFindAll + * @see Container~afterFindAllListener + * @see Container#findAll + */ +/** + * Callback signature for the {@link Container#event:afterFindAll} event. + * + * @example + * function onAfterFindAll (mapperName, query, opts, result) { + * // do something + * } + * store.on('afterFindAll', onAfterFindAll); + * + * @callback Container~afterFindAllListener + * @param {string} name The `name` argument received by {@link Mapper#afterFindAll}. + * @param {object} query The `query` argument received by {@link Mapper#afterFindAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterFindAll}. + * @param {object} result The `result` argument received by {@link Mapper#afterFindAll}. + * @see Container#event:afterFindAll + * @see Container#findAll + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#createRecord}. + * + * @example + * // Find all "published" blog posts + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.findAll('post', { status: 'published' }).then((posts) => { + * console.log(posts); // [{ id: 1, ...}, ...] + * }); + * + * @fires Container#beforeFindAll + * @fires Container#afterFindAll + * @method Container#findAll + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} [query] See {@link Mapper#findAll}. + * @param {object} [opts] See {@link Mapper#findAll}. + * @returns {Promise} See {@link Mapper#findAll}. + * @see Mapper#findAll + * @since 3.0.0 + */ +'findAll', + +/** + * Wrapper for {@link Mapper#getSchema}. + * + * @method Container#getSchema + * @param {string} name Name of the {@link Mapper} to target. + * @returns {Schema} See {@link Mapper#getSchema}. + * @see Mapper#getSchema + * @since 3.0.0 + */ +'getSchema', + +/** + * Wrapper for {@link Mapper#is}. + * + * @example + * import { Container } from 'js-data'; + * const store = new Container(); + * store.defineMapper('post'); + * const post = store.createRecord(); + * + * console.log(store.is('post', post)); // true + * // Equivalent to what's above + * console.log(post instanceof store.getMapper('post').recordClass); // true + * + * @method Container#is + * @param {string} name Name of the {@link Mapper} to target. + * @param {Object|Record} record See {@link Mapper#is}. + * @returns {boolean} See {@link Mapper#is}. + * @see Mapper#is + * @since 3.0.0 + */ +'is', + +/** + * Wrapper for {@link Mapper#sum}. + * + * @example + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('purchase_order'); + * + * store.sum('purchase_order', 'amount', { status: 'paid' }).then((amountPaid) => { + * console.log(amountPaid); // e.g. 451125.34 + * }); + * + * @method Container#sum + * @param {string} name Name of the {@link Mapper} to target. + * @param {string} field See {@link Mapper#sum}. + * @param {object} [query] See {@link Mapper#sum}. + * @param {object} [opts] See {@link Mapper#sum}. + * @returns {Promise} See {@link Mapper#sum}. + * @see Mapper#sum + * @since 3.0.0 + */ +'sum', + +/** + * Wrapper for {@link Mapper#toJSON}. + * + * @example + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('person', { + * schema: { + * properties: { + * name: { type: 'string' }, + * id: { type: 'string' } + * } + * } + * }); + * const person = store.createRecord('person', { id: 1, name: 'John', foo: 'bar' }); + * // "foo" is stripped by toJSON() + * console.log(store.toJSON('person', person)); // {"id":1,"name":"John"} + * + * store.defineMapper('personRelaxed', { + * schema: { + * properties: { + * name: { type: 'string' }, + * id: { type: 'string' } + * }, + * additionalProperties: true + * } + * }); + * const person2 = store.createRecord('personRelaxed', { id: 1, name: 'John', foo: 'bar' }); + * // "foo" is not stripped by toJSON + * console.log(store.toJSON('personRelaxed', person2)); // {"id":1,"name":"John","foo":"bar"} + * + * @method Container#toJSON + * @param {string} name Name of the {@link Mapper} to target. + * @param {Record|Record[]} records See {@link Mapper#toJSON}. + * @param {object} [opts] See {@link Mapper#toJSON}. + * @returns {Object|Object[]} See {@link Mapper#toJSON}. + * @see Mapper#toJSON + * @since 3.0.0 + */ +'toJSON', + +/** + * Fired during {@link Container#update}. See + * {@link Container~beforeUpdateListener} for how to listen for this event. + * + * @event Container#beforeUpdate + * @see Container~beforeUpdateListener + * @see Container#update + */ +/** + * Callback signature for the {@link Container#event:beforeUpdate} event. + * + * @example + * function onBeforeUpdate (mapperName, id, props, opts) { + * // do something + * } + * store.on('beforeUpdate', onBeforeUpdate); + * + * @callback Container~beforeUpdateListener + * @param {string} name The `name` argument received by {@link Mapper#beforeUpdate}. + * @param {string|number} id The `id` argument received by {@link Mapper#beforeUpdate}. + * @param {object} props The `props` argument received by {@link Mapper#beforeUpdate}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdate}. + * @see Container#event:beforeUpdate + * @see Container#update + * @since 3.0.0 + */ +/** + * Fired during {@link Container#update}. See + * {@link Container~afterUpdateListener} for how to listen for this event. + * + * @event Container#afterUpdate + * @see Container~afterUpdateListener + * @see Container#update + */ +/** + * Callback signature for the {@link Container#event:afterUpdate} event. + * + * @example + * function onAfterUpdate (mapperName, id, props, opts, result) { + * // do something + * } + * store.on('afterUpdate', onAfterUpdate); + * + * @callback Container~afterUpdateListener + * @param {string} name The `name` argument received by {@link Mapper#afterUpdate}. + * @param {string|number} id The `id` argument received by {@link Mapper#afterUpdate}. + * @param {object} props The `props` argument received by {@link Mapper#afterUpdate}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdate}. + * @param {object} result The `result` argument received by {@link Mapper#afterUpdate}. + * @see Container#event:afterUpdate + * @see Container#update + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#update}. + * + * @example + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.update('post', 1234, { + * status: 'published', + * published_at: new Date() + * }).then((post) => { + * console.log(post); // { id: 1234, status: 'published', ... } + * }); + * + * @fires Container#beforeUpdate + * @fires Container#afterUpdate + * @method Container#update + * @param {string} name Name of the {@link Mapper} to target. + * @param {(string|number)} id See {@link Mapper#update}. + * @param {object} record See {@link Mapper#update}. + * @param {object} [opts] See {@link Mapper#update}. + * @returns {Promise} See {@link Mapper#update}. + * @see Mapper#update + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/saving-data","Saving data"] + */ +'update', + +/** + * Fired during {@link Container#updateAll}. See + * {@link Container~beforeUpdateAllListener} for how to listen for this event. + * + * @event Container#beforeUpdateAll + * @see Container~beforeUpdateAllListener + * @see Container#updateAll + */ +/** + * Callback signature for the {@link Container#event:beforeUpdateAll} event. + * + * @example + * function onBeforeUpdateAll (mapperName, props, query, opts) { + * // do something + * } + * store.on('beforeUpdateAll', onBeforeUpdateAll); + * + * @callback Container~beforeUpdateAllListener + * @param {string} name The `name` argument received by {@link Mapper#beforeUpdateAll}. + * @param {object} props The `props` argument received by {@link Mapper#beforeUpdateAll}. + * @param {object} query The `query` argument received by {@link Mapper#beforeUpdateAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateAll}. + * @see Container#event:beforeUpdateAll + * @see Container#updateAll + * @since 3.0.0 + */ +/** + * Fired during {@link Container#updateAll}. See + * {@link Container~afterUpdateAllListener} for how to listen for this event. + * + * @event Container#afterUpdateAll + * @see Container~afterUpdateAllListener + * @see Container#updateAll + */ +/** + * Callback signature for the {@link Container#event:afterUpdateAll} event. + * + * @example + * function onAfterUpdateAll (mapperName, props, query, opts, result) { + * // do something + * } + * store.on('afterUpdateAll', onAfterUpdateAll); + * + * @callback Container~afterUpdateAllListener + * @param {string} name The `name` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} props The `props` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} query The `query` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} result The `result` argument received by {@link Mapper#afterUpdateAll}. + * @see Container#event:afterUpdateAll + * @see Container#updateAll + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#updateAll}. + * + * @example + * // Turn all of John's blog posts into drafts. + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * const update = { status: draft: published_at: null }; + * const query = { userId: 1234 }; + * store.updateAll('post', update, query).then((posts) => { + * console.log(posts); // [...] + * }); + * + * @fires Container#beforeUpdateAll + * @fires Container#afterUpdateAll + * @method Container#updateAll + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} update See {@link Mapper#updateAll}. + * @param {object} [query] See {@link Mapper#updateAll}. + * @param {object} [opts] See {@link Mapper#updateAll}. + * @returns {Promise} See {@link Mapper#updateAll}. + * @see Mapper#updateAll + * @since 3.0.0 + */ +'updateAll', + +/** + * Fired during {@link Container#updateMany}. See + * {@link Container~beforeUpdateManyListener} for how to listen for this event. + * + * @event Container#beforeUpdateMany + * @see Container~beforeUpdateManyListener + * @see Container#updateMany + */ +/** + * Callback signature for the {@link Container#event:beforeUpdateMany} event. + * + * @example + * function onBeforeUpdateMany (mapperName, records, opts) { + * // do something + * } + * store.on('beforeUpdateMany', onBeforeUpdateMany); + * + * @callback Container~beforeUpdateManyListener + * @param {string} name The `name` argument received by {@link Mapper#beforeUpdateMany}. + * @param {object} records The `records` argument received by {@link Mapper#beforeUpdateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateMany}. + * @see Container#event:beforeUpdateMany + * @see Container#updateMany + * @since 3.0.0 + */ +/** + * Fired during {@link Container#updateMany}. See + * {@link Container~afterUpdateManyListener} for how to listen for this event. + * + * @event Container#afterUpdateMany + * @see Container~afterUpdateManyListener + * @see Container#updateMany + */ +/** + * Callback signature for the {@link Container#event:afterUpdateMany} event. + * + * @example + * function onAfterUpdateMany (mapperName, records, opts, result) { + * // do something + * } + * store.on('afterUpdateMany', onAfterUpdateMany); + * + * @callback Container~afterUpdateManyListener + * @param {string} name The `name` argument received by {@link Mapper#afterUpdateMany}. + * @param {object} records The `records` argument received by {@link Mapper#afterUpdateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateMany}. + * @param {object} result The `result` argument received by {@link Mapper#afterUpdateMany}. + * @see Container#event:afterUpdateMany + * @see Container#updateMany + * @since 3.0.0 + */ +/** + * Wrapper for {@link Mapper#updateMany}. + * + * @example + * import { Container } from 'js-data'; + * import RethinkDBAdapter from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * store.defineMapper('post'); + * + * store.updateMany('post', [ + * { id: 1234, status: 'draft' }, + * { id: 2468, status: 'published', published_at: new Date() } + * ]).then((posts) => { + * console.log(posts); // [...] + * }); + * + * @fires Container#beforeUpdateMany + * @fires Container#afterUpdateMany + * @method Container#updateMany + * @param {string} name Name of the {@link Mapper} to target. + * @param {(Object[]|Record[])} records See {@link Mapper#updateMany}. + * @param {object} [opts] See {@link Mapper#updateMany}. + * @returns {Promise} See {@link Mapper#updateMany}. + * @see Mapper#updateMany + * @since 3.0.0 + */ +'updateMany', + +/** + * Wrapper for {@link Mapper#validate}. + * + * @example + * import { Container } from 'js-data'; + * const store = new Container(); + * store.defineMapper('post', { + * schema: { + * properties: { + * name: { type: 'string' }, + * id: { type: 'string' } + * } + * } + * }); + * let errors = store.validate('post', { name: 'John' }); + * console.log(errors); // undefined + * errors = store.validate('post', { name: 123 }); + * console.log(errors); // [{ expected: 'one of (string)', actual: 'number', path: 'name' }] + * + * @method Container#validate + * @param {string} name Name of the {@link Mapper} to target. + * @param {(Object[]|Record[])} records See {@link Mapper#validate}. + * @param {object} [opts] See {@link Mapper#validate}. + * @returns {Promise} See {@link Mapper#validate}. + * @see Mapper#validate + * @since 3.0.0 + */ +'validate']; + +/** + * The `Container` class is a place to define and store {@link Mapper} instances. + * + * `Container` makes it easy to manage your Mappers. Without a container, you + * need to manage Mappers yourself, including resolving circular dependencies + * among relations. All Mappers in a container share the same adapters, so you + * don't have to register adapters for every single Mapper. + * + * @example Container#constructor + * // import { Container } from 'js-data'; + * const JSData = require('js-data'); + * const {Container} = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * + * @class Container + * @extends Component + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.debug=false] See {@link Component#debug}. + * @param {Constructor} [opts.mapperClass] See {@link Container#mapperClass}. + * @param {object} [opts.mapperDefaults] See {@link Container#mapperDefaults}. + * @since 3.0.0 + */ +function Container(opts) { + utils.classCallCheck(this, Container); + Component$1.call(this); + opts || (opts = {}); + + Object.defineProperties(this, { + /** + * The adapters registered with this Container, which are also shared by all + * Mappers in this Container. + * + * @name Container#_adapters + * @see Container#registerAdapter + * @since 3.0.0 + * @type {Object} + */ + _adapters: { + value: {} + }, + + /** + * The the mappers in this container + * + * @name Container#_mappers + * @see Mapper + * @since 3.0.0 + * @type {Object} + */ + _mappers: { + value: {} + }, + + /** + * Constructor function to use in {@link Container#defineMapper} to create new + * {@link Mapper} instances. {@link Container#mapperClass} should extend + * {@link Mapper}. By default {@link Mapper} is used to instantiate Mappers. + * + * @example Container#mapperClass + * // import { Container, Mapper } from 'js-data'; + * const JSData = require('js-data'); + * const { Container, Mapper } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * class MyMapperClass extends Mapper { + * foo () { return 'bar' } + * } + * const store = new Container({ + * mapperClass: MyMapperClass + * }); + * store.defineMapper('user'); + * console.log(store.getMapper('user').foo()); + * + * @name Container#mapperClass + * @see Mapper + * @since 3.0.0 + * @type {Constructor} + */ + mapperClass: { + value: undefined, + writable: true + } + }); + + // Apply options provided by the user + utils.fillIn(this, opts); + + /** + * Defaults options to pass to {@link Container#mapperClass} when creating a + * new {@link Mapper}. + * + * @example Container#mapperDefaults + * // import { Container } from 'js-data'; + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container({ + * mapperDefaults: { + * idAttribute: '_id' + * } + * }); + * store.defineMapper('user'); + * console.log(store.getMapper('user').idAttribute); + * + * @default {} + * @name Container#mapperDefaults + * @since 3.0.0 + * @type {Object} + */ + this.mapperDefaults = this.mapperDefaults || {}; + + // Use the Mapper class if the user didn't provide a mapperClass + this.mapperClass || (this.mapperClass = Mapper$1); +} + +var props = { + constructor: Container, + + /** + * Register a new event listener on this Container. + * + * Proxy for {@link Component#on}. If an event was emitted by a {@link Mapper} + * in the Container, then the name of the {@link Mapper} will be prepended to + * the arugments passed to the listener. + * + * @example Container#on + * // import { Container } from 'js-data'; + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * store.on('foo', function (...args) { console.log(args.join(':')) }); + * store.defineMapper('user'); + * store.emit('foo', 'arg1', 'arg2'); + * store.getMapper('user').emit('foo', 'arg1', 'arg2'); + * + * @method Container#on + * @param {string} event Name of event to subsribe to. + * @param {Function} listener Listener function to handle the event. + * @param {*} [ctx] Optional content in which to invoke the listener. + * @since 3.0.0 + */ + + /** + * Used to bind to events emitted by mappers in this container. + * + * @method Container#_onMapperEvent + * @param {string} name Name of the mapper that emitted the event. + * @param {...*} [args] Args See {@link Mapper#emit}. + * @private + * @since 3.0.0 + */ + _onMapperEvent: function _onMapperEvent(name) { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + var type = args.shift(); + this.emit.apply(this, [type, name].concat(args)); + }, + + + /** + * Return a container scoped to a particular mapper. + * + * @example Container#as + * // import { Container } from 'js-data'; + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * const UserMapper = store.defineMapper('user'); + * const UserStore = store.as('user'); + * + * const user1 = store.createRecord('user', { name: 'John' }); + * const user2 = UserStore.createRecord({ name: 'John' }); + * const user3 = UserMapper.createRecord({ name: 'John' }); + * console.log(user1 === user2); + * console.log(user2 === user3); + * console.log(user1 === user3); + * + * @method Container#as + * @param {string} name Name of the {@link Mapper}. + * @returns {Object} A container scoped to a particular mapper. + * @since 3.0.0 + */ + as: function as(name) { + var props = {}; + var original = this; + proxiedMapperMethods.forEach(function (method) { + props[method] = { + writable: true, + value: function value() { + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + return original[method].apply(original, [name].concat(args)); + } + }; + }); + props.getMapper = { + writable: true, + value: function value() { + return original.getMapper(name); + } + }; + return Object.create(this, props); + }, + + + /** + * Create a new mapper and register it in this container. + * + * @example Container#defineMapper + * // import { Container } from 'js-data'; + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container({ + * mapperDefaults: { foo: 'bar' } + * }); + * // Container#defineMapper returns a direct reference to the newly created + * // Mapper. + * const UserMapper = store.defineMapper('user'); + * console.log(UserMapper === store.getMapper('user')); + * console.log(UserMapper === store.as('user').getMapper()); + * console.log(UserMapper.foo); + * + * @method Container#defineMapper + * @param {string} name Name under which to register the new {@link Mapper}. + * {@link Mapper#name} will be set to this value. + * @param {object} [opts] Configuration options. Passed to + * {@link Container#mapperClass} when creating the new {@link Mapper}. + * @returns {Mapper} The newly created instance of {@link Mapper}. + * @see Container#as + * @since 3.0.0 + */ + defineMapper: function defineMapper(name, opts) { + var _this = this; + + // For backwards compatibility with defineResource + if (utils.isObject(name)) { + opts = name; + name = opts.name; + } + if (!utils.isString(name)) { + throw utils.err(DOMAIN$5 + '#defineMapper', 'name')(400, 'string', name); + } + + // Default values for arguments + opts || (opts = {}); + // Set Mapper#name + opts.name = name; + opts.relations || (opts.relations = {}); + + // Check if the user is overriding the datastore's default mapperClass + var mapperClass = opts.mapperClass || this.mapperClass; + delete opts.mapperClass; + + // Apply the datastore's defaults to the options going into the mapper + utils.fillIn(opts, this.mapperDefaults); + + // Instantiate a mapper + var mapper = this._mappers[name] = new mapperClass(opts); // eslint-disable-line + mapper.relations || (mapper.relations = {}); + // Make sure the mapper's name is set + mapper.name = name; + // All mappers in this datastore will share adapters + mapper._adapters = this.getAdapters(); + + mapper.datastore = this; + + mapper.on('all', function () { + for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + return _this._onMapperEvent.apply(_this, [name].concat(args)); + }); + mapper.defineRelations(); + + return mapper; + }, + defineResource: function defineResource(name, opts) { + console.warn('DEPRECATED: defineResource is deprecated, use defineMapper instead'); + return this.defineMapper(name, opts); + }, + + + /** + * Return the registered adapter with the given name or the default adapter if + * no name is provided. + * + * @method Container#getAdapter + * @param {string} [name] The name of the adapter to retrieve. + * @returns {Adapter} The adapter. + * @since 3.0.0 + */ + getAdapter: function getAdapter(name) { + var adapter = this.getAdapterName(name); + if (!adapter) { + throw utils.err(DOMAIN$5 + '#getAdapter', 'name')(400, 'string', name); + } + return this.getAdapters()[adapter]; + }, + + + /** + * Return the name of a registered adapter based on the given name or options, + * or the name of the default adapter if no name provided. + * + * @method Container#getAdapterName + * @param {(Object|string)} [opts] The name of an adapter or options, if any. + * @returns {string} The name of the adapter. + * @since 3.0.0 + */ + getAdapterName: function getAdapterName(opts) { + opts || (opts = {}); + if (utils.isString(opts)) { + opts = { adapter: opts }; + } + return opts.adapter || this.mapperDefaults.defaultAdapter; + }, + + + /** + * Return the registered adapters of this container. + * + * @method Container#getAdapters + * @returns {Adapter} + * @since 3.0.0 + */ + getAdapters: function getAdapters() { + return this._adapters; + }, + + + /** + * Return the mapper registered under the specified name. + * + * @example Container#getMapper + * // import { Container } from 'js-data'; + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * // Container#defineMapper returns a direct reference to the newly created + * // Mapper. + * const UserMapper = store.defineMapper('user'); + * console.log(UserMapper === store.getMapper('user')); + * console.log(UserMapper === store.as('user').getMapper()); + * store.getMapper('profile'); // throws Error, there is no mapper with name "profile" + * + * @method Container#getMapper + * @param {string} name {@link Mapper#name}. + * @returns {Mapper} + * @since 3.0.0 + */ + getMapper: function getMapper(name) { + var mapper = this.getMapperByName(name); + if (!mapper) { + throw utils.err(DOMAIN$5 + '#getMapper', name)(404, 'mapper'); + } + return mapper; + }, + + + /** + * Return the mapper registered under the specified name. + * Doesn't throw error if mapper doesn't exist. + * + * @example Container#getMapperByName + * // import { Container } from 'js-data'; + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new Container(); + * // Container#defineMapper returns a direct reference to the newly created + * // Mapper. + * const UserMapper = store.defineMapper('user'); + * console.log(UserMapper === store.getMapper('user')); + * console.log(UserMapper === store.as('user').getMapper()); + * console.log(store.getMapper('profile')); // Does NOT throw an error + * + * @method Container#getMapperByName + * @param {string} name {@link Mapper#name}. + * @returns {Mapper} + * @since 3.0.0 + */ + getMapperByName: function getMapperByName(name) { + return this._mappers[name]; + }, + + + /** + * Register an adapter on this container under the given name. Adapters + * registered on a container are shared by all mappers in the container. + * + * @example + * import { Container } from 'js-data'; + * import { RethinkDBAdapter } from 'js-data-rethinkdb'; + * const store = new Container(); + * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true }); + * + * @method Container#registerAdapter + * @param {string} name The name of the adapter to register. + * @param {Adapter} adapter The adapter to register. + * @param {object} [opts] Configuration options. + * @param {boolean} [opts.default=false] Whether to make the adapter the + * default adapter for all Mappers in this container. + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/connecting-to-a-data-source","Connecting to a data source"] + */ + registerAdapter: function registerAdapter(name, adapter, opts) { + opts || (opts = {}); + this.getAdapters()[name] = adapter; + // Optionally make it the default adapter for the target. + if (opts === true || opts.default) { + this.mapperDefaults.defaultAdapter = name; + utils.forOwn(this._mappers, function (mapper) { + mapper.defaultAdapter = name; + }); + } + } +}; + +proxiedMapperMethods.forEach(function (method) { + props[method] = function (name) { + var _getMapper; + + for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + + return (_getMapper = this.getMapper(name))[method].apply(_getMapper, args); + }; +}); + +Component$1.extend(props); + +/** + * Create a subclass of this Container: + * @example Container.extend + * const JSData = require('js-data'); + * const { Container } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomContainerClass extends Container { + * foo () { return 'bar' } + * static beep () { return 'boop' } + * } + * const customContainer = new CustomContainerClass(); + * console.log(customContainer.foo()); + * console.log(CustomContainerClass.beep()); + * + * // Extend the class using alternate method. + * const OtherContainerClass = Container.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherContainer = new OtherContainerClass(); + * console.log(otherContainer.foo()); + * console.log(OtherContainerClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherContainerClass () { + * Container.call(this); + * this.created_at = new Date().getTime(); + * } + * Container.extend({ + * constructor: AnotherContainerClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }) + * const anotherContainer = new AnotherContainerClass(); + * console.log(anotherContainer.created_at); + * console.log(anotherContainer.foo()); + * console.log(AnotherContainerClass.beep()); + * + * @method Container.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this Container class. + * @since 3.0.0 + */ + +var DOMAIN$8 = 'SimpleStore'; +var proxiedCollectionMethods = [ +/** + * Wrapper for {@link Collection#add}. + * + * @example SimpleStore#add + * const JSData = require('js-data'); + * const { SimpleStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new SimpleStore(); + * store.defineMapper('book'); + * + * // Add one book to the in-memory store: + * store.add('book', { id: 1, title: 'Respect your Data' }); + * // Add multiple books to the in-memory store: + * store.add('book', [ + * { id: 2, title: 'Easy data recipes' }, + * { id: 3, title: 'Active Record 101' } + * ]); + * + * @fires SimpleStore#add + * @method SimpleStore#add + * @param {(string|number)} name Name of the {@link Mapper} to target. + * @param {(Object|Object[]|Record|Record[])} data See {@link Collection#add}. + * @param {object} [opts] Configuration options. See {@link Collection#add}. + * @returns {(Object|Object[]|Record|Record[])} See {@link Collection#add}. + * @see Collection#add + * @see Collection#add + * @since 3.0.0 + */ +'add', + +/** + * Wrapper for {@link Collection#between}. + * + * @example + * // Get all users ages 18 to 30 + * const users = store.between('user', 18, 30, { index: 'age' }); + * + * @example + * // Same as above + * const users = store.between('user', [18], [30], { index: 'age' }); + * + * @method SimpleStore#between + * @param {(string|number)} name Name of the {@link Mapper} to target. + * @param {array} leftKeys See {@link Collection#between}. + * @param {array} rightKeys See {@link Collection#between}. + * @param {object} [opts] Configuration options. See {@link Collection#between}. + * @returns {Object[]|Record[]} See {@link Collection#between}. + * @see Collection#between + * @see Collection#between + * @since 3.0.0 + */ +'between', + +/** + * Wrapper for {@link Collection#createIndex}. + * + * @example + * // Index users by age + * store.createIndex('user', 'age'); + * + * @example + * // Index users by status and role + * store.createIndex('user', 'statusAndRole', ['status', 'role']); + * + * @method SimpleStore#createIndex + * @param {(string|number)} name Name of the {@link Mapper} to target. + * @param {string} name See {@link Collection#createIndex}. + * @param {string[]} [fieldList] See {@link Collection#createIndex}. + * @see Collection#createIndex + * @see Collection#createIndex + * @since 3.0.0 + */ +'createIndex', + +/** + * Wrapper for {@link Collection#filter}. + * + * @example SimpleStore#filter + * const JSData = require('js-data'); + * const { SimpleStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new SimpleStore(); + * store.defineMapper('post'); + * store.add('post', [ + * { id: 1, status: 'draft', created_at_timestamp: new Date().getTime() } + * ]); + * + * // Get the draft posts created less than three months ago + * let posts = store.filter('post', { + * where: { + * status: { + * '==': 'draft' + * }, + * created_at_timestamp: { + * '>=': (new Date().getTime() - (1000 \* 60 \* 60 \* 24 \* 30 \* 3)) // 3 months ago + * } + * } + * }); + * console.log(posts); + * + * // Use a custom filter function + * posts = store.filter('post', function (post) { return post.id % 2 === 0 }); + * + * @method SimpleStore#filter + * @param {(string|number)} name Name of the {@link Mapper} to target. + * @param {(Object|Function)} [queryOrFn={}] See {@link Collection#filter}. + * @param {object} [thisArg] See {@link Collection#filter}. + * @returns {Array} See {@link Collection#filter}. + * @see Collection#filter + * @see Collection#filter + * @since 3.0.0 + */ +'filter', + +/** + * Wrapper for {@link Collection#get}. + * + * @example SimpleStore#get + * const JSData = require('js-data'); + * const { SimpleStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new SimpleStore(); + * store.defineMapper('post'); + * store.add('post', [ + * { id: 1, status: 'draft', created_at_timestamp: new Date().getTime() } + * ]); + * + * console.log(store.get('post', 1)); // {...} + * console.log(store.get('post', 2)); // undefined + * + * @method SimpleStore#get + * @param {(string|number)} name Name of the {@link Mapper} to target. + * @param {(string|number)} id See {@link Collection#get}. + * @returns {(Object|Record)} See {@link Collection#get}. + * @see Collection#get + * @see Collection#get + * @since 3.0.0 + */ +'get', + +/** + * Wrapper for {@link Collection#getAll}. + * + * @example + * // Get the posts where "status" is "draft" or "inReview" + * const posts = store.getAll('post', 'draft', 'inReview', { index: 'status' }); + * + * @example + * // Same as above + * const posts = store.getAll('post', ['draft'], ['inReview'], { index: 'status' }); + * + * @method SimpleStore#getAll + * @param {(string|number)} name Name of the {@link Mapper} to target. + * @param {...Array} [keyList] See {@link Collection#getAll}. + * @param {object} [opts] See {@link Collection#getAll}. + * @returns {Array} See {@link Collection#getAll}. + * @see Collection#getAll + * @see Collection#getAll + * @since 3.0.0 + */ +'getAll', + +/** + * Wrapper for {@link Collection#prune}. + * + * @method SimpleStore#prune + * @param {object} [opts] See {@link Collection#prune}. + * @returns {Array} See {@link Collection#prune}. + * @see Collection#prune + * @see Collection#prune + * @since 3.0.0 + */ +'prune', + +/** + * Wrapper for {@link Collection#query}. + * + * @example + * // Grab page 2 of users between ages 18 and 30 + * store.query('user') + * .between(18, 30, { index: 'age' }) // between ages 18 and 30 + * .skip(10) // second page + * .limit(10) // page size + * .run(); + * + * @method SimpleStore#query + * @param {(string|number)} name Name of the {@link Mapper} to target. + * @returns {Query} See {@link Collection#query}. + * @see Collection#query + * @see Collection#query + * @since 3.0.0 + */ +'query', + +/** + * Wrapper for {@link Collection#toJSON}. + * + * @example + * store.defineMapper('post', { + * schema: { + * properties: { + * id: { type: 'number' }, + * title: { type: 'string' } + * } + * } + * }); + * store.add('post', [ + * { id: 1, status: 'published', title: 'Respect your Data' }, + * { id: 2, status: 'draft', title: 'Connecting to a data source' } + * ]); + * console.log(store.toJSON('post')); + * const draftsJSON = store.query('post') + * .filter({ status: 'draft' }) + * .mapCall('toJSON') + * .run(); + * + * @method SimpleStore#toJSON + * @param {(string|number)} name Name of the {@link Mapper} to target. + * @param {object} [opts] See {@link Collection#toJSON}. + * @returns {Array} See {@link Collection#toJSON}. + * @see Collection#toJSON + * @see Collection#toJSON + * @since 3.0.0 + */ +'toJSON', + +/** + * Wrapper for {@link Collection#unsaved}. + * + * @method SimpleStore#unsaved + * @returns {Array} See {@link Collection#unsaved}. + * @see Collection#unsaved + * @see Collection#unsaved + * @since 3.0.0 + */ +'unsaved']; +var ownMethodsForScoping = ['addToCache', 'cachedFind', 'cachedFindAll', 'cacheFind', 'cacheFindAll', 'hashQuery']; + +var cachedFn = function cachedFn(name, hashOrId, opts) { + var cached = this._completedQueries[name][hashOrId]; + if (utils.isFunction(cached)) { + return cached(name, hashOrId, opts); + } + return cached; +}; + +var SIMPLESTORE_DEFAULTS = { + /** + * Whether to use the pending query if a `find` request for the specified + * record is currently underway. Can be set to `true`, `false`, or to a + * function that returns `true` or `false`. + * + * @default true + * @name SimpleStore#usePendingFind + * @since 3.0.0 + * @type {boolean|Function} + */ + usePendingFind: true, + + /** + * Whether to use the pending query if a `findAll` request for the given query + * is currently underway. Can be set to `true`, `false`, or to a function that + * returns `true` or `false`. + * + * @default true + * @name SimpleStore#usePendingFindAll + * @since 3.0.0 + * @type {boolean|Function} + */ + usePendingFindAll: true + + /** + * The `SimpleStore` class is an extension of {@link Container}. Not only does + * `SimpleStore` manage mappers, but also collections. `SimpleStore` implements the + * asynchronous {@link Mapper} methods, such as {@link Mapper#find} and + * {@link Mapper#create}. If you use the asynchronous `SimpleStore` methods + * instead of calling them directly on the mappers, then the results of the + * method calls will be inserted into the store's collections. You can think of + * a `SimpleStore` as an [Identity Map](https://en.wikipedia.org/wiki/Identity_map_pattern) + * for the [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping) + * (the Mappers). + * + * ```javascript + * import { SimpleStore } from 'js-data'; + * ``` + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * const store = new SimpleStore(); + * + * // SimpleStore#defineMapper returns a direct reference to the newly created + * // Mapper. + * const UserMapper = store.defineMapper('user'); + * + * // SimpleStore#as returns the store scoped to a particular Mapper. + * const UserStore = store.as('user'); + * + * // Call "find" on "UserMapper" (Stateless ORM) + * UserMapper.find(1).then((user) => { + * // retrieved a "user" record via the http adapter, but that's it + * + * // Call "find" on "store" targeting "user" (Stateful SimpleStore) + * return store.find('user', 1); // same as "UserStore.find(1)" + * }).then((user) => { + * // not only was a "user" record retrieved, but it was added to the + * // store's "user" collection + * const cachedUser = store.getCollection('user').get(1); + * console.log(user === cachedUser); // true + * }); + * + * @class SimpleStore + * @extends Container + * @param {object} [opts] Configuration options. See {@link Container}. + * @param {boolean} [opts.collectionClass={@link Collection}] See {@link SimpleStore#collectionClass}. + * @param {boolean} [opts.debug=false] See {@link Component#debug}. + * @param {boolean|Function} [opts.usePendingFind=true] See {@link SimpleStore#usePendingFind}. + * @param {boolean|Function} [opts.usePendingFindAll=true] See {@link SimpleStore#usePendingFindAll}. + * @returns {SimpleStore} + * @see Container + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#SimpleStore","Components of JSData: SimpleStore"] + * @tutorial ["http://www.js-data.io/v3.0/docs/working-with-the-SimpleStore","Working with the SimpleStore"] + * @tutorial ["http://www.js-data.io/v3.0/docs/jsdata-and-the-browser","Notes on using JSData in the Browser"] + */ +};function SimpleStore(opts) { + utils.classCallCheck(this, SimpleStore); + + opts || (opts = {}); + // Fill in any missing options with the defaults + utils.fillIn(opts, SIMPLESTORE_DEFAULTS); + Container.call(this, opts); + + this.collectionClass = this.collectionClass || Collection$1; + this._collections = {}; + this._pendingQueries = {}; + this._completedQueries = {}; +} + +var props$2 = { + constructor: SimpleStore, + + /** + * Internal method used to handle Mapper responses. + * + * @method SimpleStore#_end + * @private + * @param {string} name Name of the {@link Collection} to which to + * add the data. + * @param {object} result The result from a Mapper. + * @param {object} [opts] Configuration options. + * @returns {(Object|Array)} Result. + */ + _end: function _end(name, result, opts) { + var data = opts.raw ? result.data : result; + if (data && utils.isFunction(this.addToCache)) { + data = this.addToCache(name, data, opts); + if (opts.raw) { + result.data = data; + } else { + result = data; + } + } + return result; + }, + + + /** + * Register a new event listener on this SimpleStore. + * + * Proxy for {@link Container#on}. If an event was emitted by a Mapper or + * Collection in the SimpleStore, then the name of the Mapper or Collection will + * be prepended to the arugments passed to the provided event handler. + * + * @example + * // Listen for all "afterCreate" events in a SimpleStore + * store.on('afterCreate', (mapperName, props, opts, result) => { + * console.log(mapperName); // "post" + * console.log(props.id); // undefined + * console.log(result.id); // 1234 + * }); + * store.create('post', { title: 'Modeling your data' }).then((post) => { + * console.log(post.id); // 1234 + * }); + * + * @example + * // Listen for the "add" event on a collection + * store.on('add', (mapperName, records) => { + * console.log(records); // [...] + * }); + * + * @example + * // Listen for "change" events on a record + * store.on('change', (mapperName, record, changes) => { + * console.log(changes); // { changed: { title: 'Modeling your data' } } + * }); + * post.title = 'Modeling your data'; + * + * @method SimpleStore#on + * @param {string} event Name of event to subsribe to. + * @param {Function} listener Listener function to handle the event. + * @param {*} [ctx] Optional content in which to invoke the listener. + */ + + /** + * Used to bind to events emitted by collections in this store. + * + * @method SimpleStore#_onCollectionEvent + * @private + * @param {string} name Name of the collection that emitted the event. + * @param {...*} [args] Args passed to {@link Collection#emit}. + */ + _onCollectionEvent: function _onCollectionEvent(name) { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + var type = args.shift(); + this.emit.apply(this, [type, name].concat(args)); + }, + + + /** + * This method takes the data received from {@link SimpleStore#find}, + * {@link SimpleStore#findAll}, {@link SimpleStore#update}, etc., and adds the + * data to the store. _You don't need to call this method directly._ + * + * If you're using the http adapter and your response data is in an unexpected + * format, you may need to override this method so the right data gets added + * to the store. + * + * @example + * const store = new SimpleStore({ + * addToCache (mapperName, data, opts) { + * // Let's say for a particular Resource, response data is in a weird format + * if (name === 'comment') { + * // Re-assign the variable to add the correct records into the stores + * data = data.items; + * } + * // Now perform default behavior + * return SimpleStore.prototype.addToCache.call(this, mapperName, data, opts); + * } + * }); + * + * @example + * // Extend using ES2015 class syntax. + * class MyStore extends SimpleStore { + * addToCache (mapperName, data, opts) { + * // Let's say for a particular Resource, response data is in a weird format + * if (name === 'comment') { + * // Re-assign the variable to add the correct records into the stores + * data = data.items; + * } + * // Now perform default behavior + * return super.addToCache(mapperName, data, opts); + * } + * } + * const store = new MyStore(); + * + * @method SimpleStore#addToCache + * @param {string} name Name of the {@link Mapper} to target. + * @param {*} data Data from which data should be selected for add. + * @param {object} [opts] Configuration options. + */ + addToCache: function addToCache(name, data, opts) { + return this.getCollection(name).add(data, opts); + }, + + + /** + * Return the store scoped to a particular mapper/collection pair. + * + * @example SimpleStore.as + * const JSData = require('js-data'); + * const { SimpleStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new SimpleStore(); + * const UserMapper = store.defineMapper('user'); + * const UserStore = store.as('user'); + * + * const user1 = store.createRecord('user', { name: 'John' }); + * const user2 = UserStore.createRecord({ name: 'John' }); + * const user3 = UserMapper.createRecord({ name: 'John' }); + * console.log(user1 === user2); + * console.log(user2 === user3); + * console.log(user1 === user3); + * + * @method SimpleStore#as + * @param {string} name Name of the {@link Mapper}. + * @returns {Object} The store, scoped to a particular Mapper/Collection pair. + * @since 3.0.0 + */ + as: function as(name) { + var props = {}; + var original = this; + var methods = ownMethodsForScoping.concat(proxiedMapperMethods).concat(proxiedCollectionMethods); + + methods.forEach(function (method) { + props[method] = { + writable: true, + value: function value() { + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + return original[method].apply(original, [name].concat(args)); + } + }; + }); + props.getMapper = { + writable: true, + value: function value() { + return original.getMapper(name); + } + }; + props.getCollection = { + writable: true, + value: function value() { + return original.getCollection(name); + } + }; + return Object.create(this, props); + }, + + + /** + * Retrieve a cached `find` result, if any. This method is called during + * {@link SimpleStore#find} to determine if {@link Mapper#find} needs to be + * called. If this method returns `undefined` then {@link Mapper#find} will + * be called. Otherwise {@link SimpleStore#find} will immediately resolve with + * the return value of this method. + * + * When using {@link SimpleStore} in the browser, you can override this method + * to implement your own cache-busting strategy. + * + * @example + * const store = new SimpleStore({ + * cachedFind (mapperName, id, opts) { + * // Let's say for a particular Resource, we always want to pull fresh from the server + * if (mapperName === 'schedule') { + * // Return undefined to trigger a Mapper#find call + * return; + * } + * // Otherwise perform default behavior + * return SimpleStore.prototype.cachedFind.call(this, mapperName, id, opts); + * } + * }); + * + * @example + * // Extend using ES2015 class syntax. + * class MyStore extends SimpleStore { + * cachedFind (mapperName, id, opts) { + * // Let's say for a particular Resource, we always want to pull fresh from the server + * if (mapperName === 'schedule') { + * // Return undefined to trigger a Mapper#find call + * return; + * } + * // Otherwise perform default behavior + * return super.cachedFind(mapperName, id, opts); + * } + * } + * const store = new MyStore(); + * + * @method SimpleStore#cachedFind + * @param {string} name The `name` argument passed to {@link SimpleStore#find}. + * @param {(string|number)} id The `id` argument passed to {@link SimpleStore#find}. + * @param {object} opts The `opts` argument passed to {@link SimpleStore#find}. + * @since 3.0.0 + */ + cachedFind: cachedFn, + + /** + * Retrieve a cached `findAll` result, if any. This method is called during + * {@link SimpleStore#findAll} to determine if {@link Mapper#findAll} needs to be + * called. If this method returns `undefined` then {@link Mapper#findAll} will + * be called. Otherwise {@link SimpleStore#findAll} will immediately resolve with + * the return value of this method. + * + * When using {@link SimpleStore} in the browser, you can override this method + * to implement your own cache-busting strategy. + * + * @example + * const store = new SimpleStore({ + * cachedFindAll (mapperName, hash, opts) { + * // Let's say for a particular Resource, we always want to pull fresh from the server + * if (mapperName === 'schedule') { + * // Return undefined to trigger a Mapper#findAll call + * return undefined; + * } + * // Otherwise perform default behavior + * return SimpleStore.prototype.cachedFindAll.call(this, mapperName, hash, opts); + * } + * }); + * + * @example + * // Extend using ES2015 class syntax. + * class MyStore extends SimpleStore { + * cachedFindAll (mapperName, hash, opts) { + * // Let's say for a particular Resource, we always want to pull fresh from the server + * if (mapperName === 'schedule') { + * // Return undefined to trigger a Mapper#findAll call + * return undefined; + * } + * // Otherwise perform default behavior + * return super.cachedFindAll(mapperName, hash, opts); + * } + * } + * const store = new MyStore(); + * + * @method SimpleStore#cachedFindAll + * @param {string} name The `name` argument passed to {@link SimpleStore#findAll}. + * @param {string} hash The result of calling {@link SimpleStore#hashQuery} on + * the `query` argument passed to {@link SimpleStore#findAll}. + * @param {object} opts The `opts` argument passed to {@link SimpleStore#findAll}. + * @since 3.0.0 + */ + cachedFindAll: cachedFn, + + /** + * Mark a {@link Mapper#find} result as cached by adding an entry to + * {@link SimpleStore#_completedQueries}. By default, once a `find` entry is + * added it means subsequent calls to the same Resource with the same `id` + * argument will immediately resolve with the result of calling + * {@link SimpleStore#get} instead of delegating to {@link Mapper#find}. + * + * As part of implementing your own caching strategy, you may choose to + * override this method. + * + * @example + * const store = new SimpleStore({ + * cacheFind (mapperName, data, id, opts) { + * // Let's say for a particular Resource, we always want to pull fresh from the server + * if (mapperName === 'schedule') { + * // Return without saving an entry to SimpleStore#_completedQueries + * return; + * } + * // Otherwise perform default behavior + * return SimpleStore.prototype.cacheFind.call(this, mapperName, data, id, opts); + * } + * }); + * + * @example + * // Extend using ES2015 class syntax. + * class MyStore extends SimpleStore { + * cacheFind (mapperName, data, id, opts) { + * // Let's say for a particular Resource, we always want to pull fresh from the server + * if (mapperName === 'schedule') { + * // Return without saving an entry to SimpleStore#_completedQueries + * return; + * } + * // Otherwise perform default behavior + * return super.cacheFind(mapperName, data, id, opts); + * } + * } + * const store = new MyStore(); + * + * @method SimpleStore#cacheFind + * @param {string} name The `name` argument passed to {@link SimpleStore#find}. + * @param {*} data The result to cache. + * @param {(string|number)} id The `id` argument passed to {@link SimpleStore#find}. + * @param {object} opts The `opts` argument passed to {@link SimpleStore#find}. + * @since 3.0.0 + */ + cacheFind: function cacheFind(name, data, id, opts) { + var _this = this; + + this._completedQueries[name][id] = function (name, id, opts) { + return _this.get(name, id); + }; + }, + + + /** + * Mark a {@link Mapper#findAll} result as cached by adding an entry to + * {@link SimpleStore#_completedQueries}. By default, once a `findAll` entry is + * added it means subsequent calls to the same Resource with the same `query` + * argument will immediately resolve with the result of calling + * {@link SimpleStore#filter} instead of delegating to {@link Mapper#findAll}. + * + * As part of implementing your own caching strategy, you may choose to + * override this method. + * + * @example + * const store = new SimpleStore({ + * cachedFindAll (mapperName, data, hash, opts) { + * // Let's say for a particular Resource, we always want to pull fresh from the server + * if (mapperName === 'schedule') { + * // Return without saving an entry to SimpleStore#_completedQueries + * return; + * } + * // Otherwise perform default behavior. + * return SimpleStore.prototype.cachedFindAll.call(this, mapperName, data, hash, opts); + * } + * }); + * + * @example + * // Extend using ES2015 class syntax. + * class MyStore extends SimpleStore { + * cachedFindAll (mapperName, data, hash, opts) { + * // Let's say for a particular Resource, we always want to pull fresh from the server + * if (mapperName === 'schedule') { + * // Return without saving an entry to SimpleStore#_completedQueries + * return; + * } + * // Otherwise perform default behavior. + * return super.cachedFindAll(mapperName, data, hash, opts); + * } + * } + * const store = new MyStore(); + * + * @method SimpleStore#cacheFindAll + * @param {string} name The `name` argument passed to {@link SimpleStore#findAll}. + * @param {*} data The result to cache. + * @param {string} hash The result of calling {@link SimpleStore#hashQuery} on + * the `query` argument passed to {@link SimpleStore#findAll}. + * @param {object} opts The `opts` argument passed to {@link SimpleStore#findAll}. + * @since 3.0.0 + */ + cacheFindAll: function cacheFindAll(name, data, hash, opts) { + var _this2 = this; + + this._completedQueries[name][hash] = function (name, hash, opts) { + return _this2.filter(name, utils.fromJson(hash)); + }; + }, + + + /** + * Remove __all__ records from the in-memory store and reset + * {@link SimpleStore#_completedQueries}. + * + * @method SimpleStore#clear + * @returns {Object} Object containing all records that were in the store. + * @see SimpleStore#remove + * @see SimpleStore#removeAll + * @since 3.0.0 + */ + clear: function clear() { + var _this3 = this; + + var removed = {}; + utils.forOwn(this._collections, function (collection, name) { + removed[name] = collection.removeAll(); + _this3._completedQueries[name] = {}; + }); + return removed; + }, + + + /** + * Fired during {@link SimpleStore#create}. See + * {@link SimpleStore~beforeCreateListener} for how to listen for this event. + * + * @event SimpleStore#beforeCreate + * @see SimpleStore~beforeCreateListener + * @see SimpleStore#create + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeCreate} event. + * + * @example + * function onBeforeCreate (mapperName, props, opts) { + * // do something + * } + * store.on('beforeCreate', onBeforeCreate); + * + * @callback SimpleStore~beforeCreateListener + * @param {string} name The `name` argument received by {@link Mapper#beforeCreate}. + * @param {object} props The `props` argument received by {@link Mapper#beforeCreate}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreate}. + * @see SimpleStore#event:beforeCreate + * @see SimpleStore#create + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#create}. See + * {@link SimpleStore~afterCreateListener} for how to listen for this event. + * + * @event SimpleStore#afterCreate + * @see SimpleStore~afterCreateListener + * @see SimpleStore#create + */ + /** + * Callback signature for the {@link SimpleStore#event:afterCreate} event. + * + * @example + * function onAfterCreate (mapperName, props, opts, result) { + * // do something + * } + * store.on('afterCreate', onAfterCreate); + * + * @callback SimpleStore~afterCreateListener + * @param {string} name The `name` argument received by {@link Mapper#afterCreate}. + * @param {object} props The `props` argument received by {@link Mapper#afterCreate}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterCreate}. + * @param {object} result The `result` argument received by {@link Mapper#afterCreate}. + * @see SimpleStore#event:afterCreate + * @see SimpleStore#create + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#create}. Adds the created record to the store. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('book'); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // POST /book {"author_id":1234,...} + * store.create('book', { + * author_id: 1234, + * edition: 'First Edition', + * title: 'Respect your Data' + * }).then((book) => { + * console.log(book.id); // 120392 + * console.log(book.title); // "Respect your Data" + * }); + * + * @fires SimpleStore#beforeCreate + * @fires SimpleStore#afterCreate + * @fires SimpleStore#add + * @method SimpleStore#create + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} record Passed to {@link Mapper#create}. + * @param {object} [opts] Passed to {@link Mapper#create}. See + * {@link Mapper#create} for more configuration options. + * @returns {Promise} Resolves with the result of the create. + * @since 3.0.0 + */ + create: function create(name, record, opts) { + var _this4 = this; + + opts || (opts = {}); + return Container.prototype.create.call(this, name, record, opts).then(function (result) { + return _this4._end(name, result, opts); + }); + }, + + + /** + * Fired during {@link SimpleStore#createMany}. See + * {@link SimpleStore~beforeCreateManyListener} for how to listen for this event. + * + * @event SimpleStore#beforeCreateMany + * @see SimpleStore~beforeCreateManyListener + * @see SimpleStore#createMany + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeCreateMany} event. + * + * @example + * function onBeforeCreateMany (mapperName, records, opts) { + * // do something + * } + * store.on('beforeCreateMany', onBeforeCreateMany); + * + * @callback SimpleStore~beforeCreateManyListener + * @param {string} name The `name` argument received by {@link Mapper#beforeCreateMany}. + * @param {object} records The `records` argument received by {@link Mapper#beforeCreateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreateMany}. + * @see SimpleStore#event:beforeCreateMany + * @see SimpleStore#createMany + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#createMany}. See + * {@link SimpleStore~afterCreateManyListener} for how to listen for this event. + * + * @event SimpleStore#afterCreateMany + * @see SimpleStore~afterCreateManyListener + * @see SimpleStore#createMany + */ + /** + * Callback signature for the {@link SimpleStore#event:afterCreateMany} event. + * + * @example + * function onAfterCreateMany (mapperName, records, opts, result) { + * // do something + * } + * store.on('afterCreateMany', onAfterCreateMany); + * + * @callback SimpleStore~afterCreateManyListener + * @param {string} name The `name` argument received by {@link Mapper#afterCreateMany}. + * @param {object} records The `records` argument received by {@link Mapper#afterCreateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterCreateMany}. + * @param {object} result The `result` argument received by {@link Mapper#afterCreateMany}. + * @see SimpleStore#event:afterCreateMany + * @see SimpleStore#createMany + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#createMany}. Adds the created records to the + * store. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('book'); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // POST /book [{"author_id":1234,...},{...}] + * store.createMany('book', [{ + * author_id: 1234, + * edition: 'First Edition', + * title: 'Respect your Data' + * }, { + * author_id: 1234, + * edition: 'Second Edition', + * title: 'Respect your Data' + * }]).then((books) => { + * console.log(books[0].id); // 142394 + * console.log(books[0].title); // "Respect your Data" + * }); + * + * @fires SimpleStore#beforeCreateMany + * @fires SimpleStore#afterCreateMany + * @fires SimpleStore#add + * @method SimpleStore#createMany + * @param {string} name Name of the {@link Mapper} to target. + * @param {array} records Passed to {@link Mapper#createMany}. + * @param {object} [opts] Passed to {@link Mapper#createMany}. See + * {@link Mapper#createMany} for more configuration options. + * @returns {Promise} Resolves with the result of the create. + * @since 3.0.0 + */ + createMany: function createMany(name, records, opts) { + var _this5 = this; + + opts || (opts = {}); + return Container.prototype.createMany.call(this, name, records, opts).then(function (result) { + return _this5._end(name, result, opts); + }); + }, + defineMapper: function defineMapper(name, opts) { + var self = this; + var mapper = Container.prototype.defineMapper.call(self, name, opts); + self._pendingQueries[name] = {}; + self._completedQueries[name] = {}; + mapper.relationList || Object.defineProperty(mapper, 'relationList', { value: [] }); + + var collectionOpts = { + // Make sure the collection has somewhere to store "added" timestamps + _added: {}, + // Give the collection a reference to this SimpleStore + datastore: self, + // The mapper tied to the collection + mapper: mapper + }; + + if (opts && 'onConflict' in opts) { + collectionOpts.onConflict = opts.onConflict; + } + + // The SimpleStore uses a subclass of Collection that is "SimpleStore-aware" + var collection = self._collections[name] = new self.collectionClass(null, collectionOpts); // eslint-disable-line + + var schema = mapper.schema || {}; + var properties = schema.properties || {}; + // TODO: Make it possible index nested properties? + utils.forOwn(properties, function (opts, prop) { + if (opts.indexed) { + collection.createIndex(prop); + } + }); + + // Create a secondary index on the "added" timestamps of records in the + // collection + collection.createIndex('addedTimestamps', ['$'], { + fieldGetter: function fieldGetter(obj) { + return collection._added[collection.recordId(obj)]; + } + }); + + collection.on('all', function () { + for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + self._onCollectionEvent.apply(self, [name].concat(args)); + }); + + return mapper; + }, + + + /** + * Fired during {@link SimpleStore#destroy}. See + * {@link SimpleStore~beforeDestroyListener} for how to listen for this event. + * + * @event SimpleStore#beforeDestroy + * @see SimpleStore~beforeDestroyListener + * @see SimpleStore#destroy + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeDestroy} event. + * + * @example + * function onBeforeDestroy (mapperName, id, opts) { + * // do something + * } + * store.on('beforeDestroy', onBeforeDestroy); + * + * @callback SimpleStore~beforeDestroyListener + * @param {string} name The `name` argument received by {@link Mapper#beforeDestroy}. + * @param {string|number} id The `id` argument received by {@link Mapper#beforeDestroy}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroy}. + * @see SimpleStore#event:beforeDestroy + * @see SimpleStore#destroy + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#destroy}. See + * {@link SimpleStore~afterDestroyListener} for how to listen for this event. + * + * @event SimpleStore#afterDestroy + * @see SimpleStore~afterDestroyListener + * @see SimpleStore#destroy + */ + /** + * Callback signature for the {@link SimpleStore#event:afterDestroy} event. + * + * @example + * function onAfterDestroy (mapperName, id, opts, result) { + * // do something + * } + * store.on('afterDestroy', onAfterDestroy); + * + * @callback SimpleStore~afterDestroyListener + * @param {string} name The `name` argument received by {@link Mapper#afterDestroy}. + * @param {string|number} id The `id` argument received by {@link Mapper#afterDestroy}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterDestroy}. + * @param {object} result The `result` argument received by {@link Mapper#afterDestroy}. + * @see SimpleStore#event:afterDestroy + * @see SimpleStore#destroy + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#destroy}. Removes any destroyed record from the + * in-memory store. Clears out any {@link SimpleStore#_completedQueries} entries + * associated with the provided `id`. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('book'); + * + * store.add('book', { id: 1234, title: 'Data Management is Hard' }); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // DELETE /book/1234 + * store.destroy('book', 1234).then(() => { + * // The book record is no longer in the in-memory store + * console.log(store.get('book', 1234)); // undefined + * + * return store.find('book', 1234); + * }).then((book) { + * // The book was deleted from the database too + * console.log(book); // undefined + * }); + * + * @fires SimpleStore#beforeDestroy + * @fires SimpleStore#afterDestroy + * @fires SimpleStore#remove + * @method SimpleStore#destroy + * @param {string} name Name of the {@link Mapper} to target. + * @param {(string|number)} id Passed to {@link Mapper#destroy}. + * @param {object} [opts] Passed to {@link Mapper#destroy}. See + * {@link Mapper#destroy} for more configuration options. + * @returns {Promise} Resolves when the destroy operation completes. + * @since 3.0.0 + */ + destroy: function destroy(name, id, opts) { + var _this6 = this; + + opts || (opts = {}); + return Container.prototype.destroy.call(this, name, id, opts).then(function (result) { + var record = _this6.getCollection(name).remove(id, opts); + + if (opts.raw) { + result.data = record; + } else { + result = record; + } + delete _this6._pendingQueries[name][id]; + delete _this6._completedQueries[name][id]; + return result; + }); + }, + + + /** + * Fired during {@link SimpleStore#destroyAll}. See + * {@link SimpleStore~beforeDestroyAllListener} for how to listen for this event. + * + * @event SimpleStore#beforeDestroyAll + * @see SimpleStore~beforeDestroyAllListener + * @see SimpleStore#destroyAll + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeDestroyAll} event. + * + * @example + * function onBeforeDestroyAll (mapperName, query, opts) { + * // do something + * } + * store.on('beforeDestroyAll', onBeforeDestroyAll); + * + * @callback SimpleStore~beforeDestroyAllListener + * @param {string} name The `name` argument received by {@link Mapper#beforeDestroyAll}. + * @param {object} query The `query` argument received by {@link Mapper#beforeDestroyAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroyAll}. + * @see SimpleStore#event:beforeDestroyAll + * @see SimpleStore#destroyAll + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#destroyAll}. See + * {@link SimpleStore~afterDestroyAllListener} for how to listen for this event. + * + * @event SimpleStore#afterDestroyAll + * @see SimpleStore~afterDestroyAllListener + * @see SimpleStore#destroyAll + */ + /** + * Callback signature for the {@link SimpleStore#event:afterDestroyAll} event. + * + * @example + * function onAfterDestroyAll (mapperName, query, opts, result) { + * // do something + * } + * store.on('afterDestroyAll', onAfterDestroyAll); + * + * @callback SimpleStore~afterDestroyAllListener + * @param {string} name The `name` argument received by {@link Mapper#afterDestroyAll}. + * @param {object} query The `query` argument received by {@link Mapper#afterDestroyAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterDestroyAll}. + * @param {object} result The `result` argument received by {@link Mapper#afterDestroyAll}. + * @see SimpleStore#event:afterDestroyAll + * @see SimpleStore#destroyAll + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#destroyAll}. Removes any destroyed records from + * the in-memory store. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('book'); + * + * store.add('book', { id: 1234, title: 'Data Management is Hard' }); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // DELETE /book/1234 + * store.destroy('book', 1234).then(() => { + * // The book record is gone from the in-memory store + * console.log(store.get('book', 1234)); // undefined + * return store.find('book', 1234); + * }).then((book) { + * // The book was deleted from the database too + * console.log(book); // undefined + * }); + * + * @fires SimpleStore#beforeDestroyAll + * @fires SimpleStore#afterDestroyAll + * @fires SimpleStore#remove + * @method SimpleStore#destroyAll + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} [query] Passed to {@link Mapper#destroyAll}. + * @param {object} [opts] Passed to {@link Mapper#destroyAll}. See + * {@link Mapper#destroyAll} for more configuration options. + * @returns {Promise} Resolves when the delete completes. + * @since 3.0.0 + */ + destroyAll: function destroyAll(name, query, opts) { + var _this7 = this; + + opts || (opts = {}); + return Container.prototype.destroyAll.call(this, name, query, opts).then(function (result) { + var records = _this7.getCollection(name).removeAll(query, opts); + + if (opts.raw) { + result.data = records; + } else { + result = records; + } + var hash = _this7.hashQuery(name, query, opts); + delete _this7._pendingQueries[name][hash]; + delete _this7._completedQueries[name][hash]; + return result; + }); + }, + eject: function eject(name, id, opts) { + console.warn('DEPRECATED: "eject" is deprecated, use "remove" instead'); + return this.remove(name, id, opts); + }, + ejectAll: function ejectAll(name, query, opts) { + console.warn('DEPRECATED: "ejectAll" is deprecated, use "removeAll" instead'); + return this.removeAll(name, query, opts); + }, + + + /** + * Fired during {@link SimpleStore#find}. See + * {@link SimpleStore~beforeFindListener} for how to listen for this event. + * + * @event SimpleStore#beforeFind + * @see SimpleStore~beforeFindListener + * @see SimpleStore#find + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeFind} event. + * + * @example + * function onBeforeFind (mapperName, id, opts) { + * // do something + * } + * store.on('beforeFind', onBeforeFind); + * + * @callback SimpleStore~beforeFindListener + * @param {string} name The `name` argument received by {@link Mapper#beforeFind}. + * @param {string|number} id The `id` argument received by {@link Mapper#beforeFind}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeFind}. + * @see SimpleStore#event:beforeFind + * @see SimpleStore#find + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#find}. See + * {@link SimpleStore~afterFindListener} for how to listen for this event. + * + * @event SimpleStore#afterFind + * @see SimpleStore~afterFindListener + * @see SimpleStore#find + */ + /** + * Callback signature for the {@link SimpleStore#event:afterFind} event. + * + * @example + * function onAfterFind (mapperName, id, opts, result) { + * // do something + * } + * store.on('afterFind', onAfterFind); + * + * @callback SimpleStore~afterFindListener + * @param {string} name The `name` argument received by {@link Mapper#afterFind}. + * @param {string|number} id The `id` argument received by {@link Mapper#afterFind}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterFind}. + * @param {object} result The `result` argument received by {@link Mapper#afterFind}. + * @see SimpleStore#event:afterFind + * @see SimpleStore#find + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#find}. Adds any found record to the store. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('book'); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // GET /book/1234 + * store.find('book', 1234).then((book) => { + * // The book record is now in the in-memory store + * console.log(store.get('book', 1234) === book); // true + * }); + * + * @fires SimpleStore#beforeFind + * @fires SimpleStore#afterFind + * @fires SimpleStore#add + * @method SimpleStore#find + * @param {string} name Name of the {@link Mapper} to target. + * @param {(string|number)} id Passed to {@link Mapper#find}. + * @param {object} [opts] Passed to {@link Mapper#find}. + * @param {boolean} [opts.force] Bypass cacheFind + * @param {boolean|Function} [opts.usePendingFind] See {@link SimpleStore#usePendingFind} + * @returns {Promise} Resolves with the result, if any. + * @since 3.0.0 + */ + find: function find(name, id, opts) { + var _this8 = this; + + opts || (opts = {}); + var mapper = this.getMapper(name); + var pendingQuery = this._pendingQueries[name][id]; + var usePendingFind = opts.usePendingFind === undefined ? this.usePendingFind : opts.usePendingFind; + utils._(opts, mapper); + + if (pendingQuery && (utils.isFunction(usePendingFind) ? usePendingFind.call(this, name, id, opts) : usePendingFind)) { + return pendingQuery; + } + var item = this.cachedFind(name, id, opts); + + if (opts.force || !item) { + var promise = this._pendingQueries[name][id] = Container.prototype.find.call(this, name, id, opts); + return promise.then(function (result) { + delete _this8._pendingQueries[name][id]; + result = _this8._end(name, result, opts); + _this8.cacheFind(name, result, id, opts); + return result; + }, function (err) { + delete _this8._pendingQueries[name][id]; + return utils.reject(err); + }); + } + + return utils.resolve(item); + }, + + + /** + * Fired during {@link SimpleStore#findAll}. See + * {@link SimpleStore~beforeFindAllListener} for how to listen for this event. + * + * @event SimpleStore#beforeFindAll + * @see SimpleStore~beforeFindAllListener + * @see SimpleStore#findAll + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeFindAll} event. + * + * @example + * function onBeforeFindAll (mapperName, query, opts) { + * // do something + * } + * store.on('beforeFindAll', onBeforeFindAll); + * + * @callback SimpleStore~beforeFindAllListener + * @param {string} name The `name` argument received by {@link Mapper#beforeFindAll}. + * @param {object} query The `query` argument received by {@link Mapper#beforeFindAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeFindAll}. + * @see SimpleStore#event:beforeFindAll + * @see SimpleStore#findAll + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#findAll}. See + * {@link SimpleStore~afterFindAllListener} for how to listen for this event. + * + * @event SimpleStore#afterFindAll + * @see SimpleStore~afterFindAllListener + * @see SimpleStore#findAll + */ + /** + * Callback signature for the {@link SimpleStore#event:afterFindAll} event. + * + * @example + * function onAfterFindAll (mapperName, query, opts, result) { + * // do something + * } + * store.on('afterFindAll', onAfterFindAll); + * + * @callback SimpleStore~afterFindAllListener + * @param {string} name The `name` argument received by {@link Mapper#afterFindAll}. + * @param {object} query The `query` argument received by {@link Mapper#afterFindAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterFindAll}. + * @param {object} result The `result` argument received by {@link Mapper#afterFindAll}. + * @see SimpleStore#event:afterFindAll + * @see SimpleStore#findAll + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#findAll}. Adds any found records to the store. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('movie'); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // GET /movie?rating=PG + * store.find('movie', { rating: 'PG' }).then((movies) => { + * // The movie records are now in the in-memory store + * console.log(store.filter('movie')); + * }); + * + * @fires SimpleStore#beforeFindAll + * @fires SimpleStore#afterFindAll + * @fires SimpleStore#add + * @method SimpleStore#findAll + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} [query] Passed to {@link Mapper.findAll}. + * @param {object} [opts] Passed to {@link Mapper.findAll}. + * @param {boolean} [opts.force] Bypass cacheFindAll + * @param {boolean|Function} [opts.usePendingFindAll] See {@link SimpleStore#usePendingFindAll} + * @returns {Promise} Resolves with the result, if any. + * @since 3.0.0 + */ + findAll: function findAll(name, query, opts) { + var _this9 = this; + + opts || (opts = {}); + var mapper = this.getMapper(name); + var hash = this.hashQuery(name, query, opts); + var pendingQuery = this._pendingQueries[name][hash]; + var usePendingFindAll = opts.usePendingFindAll === undefined ? this.usePendingFindAll : opts.usePendingFindAll; + utils._(opts, mapper); + + if (pendingQuery && (utils.isFunction(usePendingFindAll) ? usePendingFindAll.call(this, name, query, opts) : usePendingFindAll)) { + return pendingQuery; + } + + var items = this.cachedFindAll(name, hash, opts); + + if (opts.force || !items) { + var promise = this._pendingQueries[name][hash] = Container.prototype.findAll.call(this, name, query, opts); + return promise.then(function (result) { + delete _this9._pendingQueries[name][hash]; + result = _this9._end(name, result, opts); + _this9.cacheFindAll(name, result, hash, opts); + return result; + }, function (err) { + delete _this9._pendingQueries[name][hash]; + return utils.reject(err); + }); + } + + return utils.resolve(items); + }, + + + /** + * Return the {@link Collection} with the given name, if for some + * reason you need a direct reference to the collection. + * + * @method SimpleStore#getCollection + * @param {string} name Name of the {@link Collection} to retrieve. + * @returns {Collection} + * @since 3.0.0 + * @throws {Error} Thrown if the specified {@link Collection} does not + * exist. + */ + getCollection: function getCollection(name) { + var collection = this._collections[name]; + if (!collection) { + throw utils.err(DOMAIN$8 + '#getCollection', name)(404, 'collection'); + } + return collection; + }, + + + /** + * Hashing function used to cache {@link SimpleStore#find} and + * {@link SimpleStore#findAll} requests. This method simply JSONifies the + * `query` argument passed to {@link SimpleStore#find} or + * {@link SimpleStore#findAll}. + * + * Override this method for custom hashing behavior. + * @method SimpleStore#hashQuery + * @param {string} name The `name` argument passed to {@link SimpleStore#find} + * or {@link SimpleStore#findAll}. + * @param {object} query The `query` argument passed to {@link SimpleStore#find} + * or {@link SimpleStore#findAll}. + * @returns {string} The JSONified `query`. + * @since 3.0.0 + */ + hashQuery: function hashQuery(name, query, opts) { + return utils.toJson(query || {}); + }, + inject: function inject(name, records, opts) { + console.warn('DEPRECATED: "inject" is deprecated, use "add" instead'); + return this.add(name, records, opts); + }, + + + /** + * Wrapper for {@link Collection#remove}. Removes the specified + * {@link Record} from the store. + * + * @example SimpleStore#remove + * const JSData = require('js-data'); + * const { SimpleStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new SimpleStore(); + * store.defineMapper('book'); + * console.log(store.getAll('book').length); + * store.add('book', { id: 1234 }); + * console.log(store.getAll('book').length); + * store.remove('book', 1234); + * console.log(store.getAll('book').length); + * + * @fires SimpleStore#remove + * @method SimpleStore#remove + * @param {string} name The name of the {@link Collection} to target. + * @param {string|number} id The primary key of the {@link Record} to remove. + * @param {object} [opts] Configuration options. + * @param {string[]} [opts.with] Relations of the {@link Record} to also + * remove from the store. + * @returns {Record} The removed {@link Record}, if any. + * @see Collection#add + * @see Collection#add + * @since 3.0.0 + */ + remove: function remove(name, id, opts) { + var record = this.getCollection(name).remove(id, opts); + if (record) { + this.removeRelated(name, [record], opts); + } + return record; + }, + + + /** + * Wrapper for {@link Collection#removeAll}. Removes the selected + * {@link Record}s from the store. + * + * @example SimpleStore#removeAll + * const JSData = require('js-data'); + * const { SimpleStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * const store = new SimpleStore(); + * store.defineMapper('movie'); + * console.log(store.getAll('movie').length); + * store.add('movie', [{ id: 3, rating: 'R' }, { id: 4, rating: 'PG-13' }); + * console.log(store.getAll('movie').length); + * store.removeAll('movie', { rating: 'R' }); + * console.log(store.getAll('movie').length); + * + * @fires SimpleStore#remove + * @method SimpleStore#removeAll + * @param {string} name The name of the {@link Collection} to target. + * @param {object} [query={}] Selection query. See {@link query}. + * @param {object} [query.where] See {@link query.where}. + * @param {number} [query.offset] See {@link query.offset}. + * @param {number} [query.limit] See {@link query.limit}. + * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}. + * @param {object} [opts] Configuration options. + * @param {string[]} [opts.with] Relations of the {@link Record} to also + * remove from the store. + * @returns {Record} The removed {@link Record}s, if any. + * @see Collection#add + * @see Collection#add + * @since 3.0.0 + */ + removeAll: function removeAll(name, query, opts) { + if (!query || !Object.keys(query).length) { + this._completedQueries[name] = {}; + } else { + this._completedQueries[name][this.hashQuery(name, query, opts)] = undefined; + } + var records = this.getCollection(name).removeAll(query, opts); + if (records.length) { + this.removeRelated(name, records, opts); + } + return records; + }, + + + /** + * Remove from the store {@link Record}s that are related to the provided + * {@link Record}(s). + * + * @fires SimpleStore#remove + * @method SimpleStore#removeRelated + * @param {string} name The name of the {@link Collection} to target. + * @param {Record|Record[]} records {@link Record}s whose relations are to be + * removed. + * @param {object} [opts] Configuration options. + * @param {string[]} [opts.with] Relations of the {@link Record}(s) to remove + * from the store. + * @since 3.0.0 + */ + removeRelated: function removeRelated(name, records, opts) { + var _this10 = this; + + if (!utils.isArray(records)) { + records = [records]; + } + utils.forEachRelation(this.getMapper(name), opts, function (def, optsCopy) { + records.forEach(function (record) { + var relatedData = void 0; + var query = void 0; + if (def.foreignKey && (def.type === hasOneType || def.type === hasManyType)) { + query = defineProperty({}, def.foreignKey, def.getForeignKey(record)); + } else if (def.type === hasManyType && def.localKeys) { + query = { + where: defineProperty({}, def.getRelation().idAttribute, { + 'in': utils.get(record, def.localKeys) + }) + }; + } else if (def.type === hasManyType && def.foreignKeys) { + query = { + where: defineProperty({}, def.foreignKeys, { + 'contains': def.getForeignKey(record) + }) + }; + } else if (def.type === belongsToType) { + relatedData = _this10.remove(def.relation, def.getForeignKey(record), optsCopy); + } + if (query) { + relatedData = _this10.removeAll(def.relation, query, optsCopy); + } + if (relatedData) { + if (utils.isArray(relatedData) && !relatedData.length) { + return; + } + if (def.type === hasOneType) { + relatedData = relatedData[0]; + } + def.setLocalField(record, relatedData); + } + }); + }); + }, + + + /** + * Fired during {@link SimpleStore#update}. See + * {@link SimpleStore~beforeUpdateListener} for how to listen for this event. + * + * @event SimpleStore#beforeUpdate + * @see SimpleStore~beforeUpdateListener + * @see SimpleStore#update + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeUpdate} event. + * + * @example + * function onBeforeUpdate (mapperName, id, props, opts) { + * // do something + * } + * store.on('beforeUpdate', onBeforeUpdate); + * + * @callback SimpleStore~beforeUpdateListener + * @param {string} name The `name` argument received by {@link Mapper#beforeUpdate}. + * @param {string|number} id The `id` argument received by {@link Mapper#beforeUpdate}. + * @param {object} props The `props` argument received by {@link Mapper#beforeUpdate}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdate}. + * @see SimpleStore#event:beforeUpdate + * @see SimpleStore#update + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#update}. See + * {@link SimpleStore~afterUpdateListener} for how to listen for this event. + * + * @event SimpleStore#afterUpdate + * @see SimpleStore~afterUpdateListener + * @see SimpleStore#update + */ + /** + * Callback signature for the {@link SimpleStore#event:afterUpdate} event. + * + * @example + * function onAfterUpdate (mapperName, id, props, opts, result) { + * // do something + * } + * store.on('afterUpdate', onAfterUpdate); + * + * @callback SimpleStore~afterUpdateListener + * @param {string} name The `name` argument received by {@link Mapper#afterUpdate}. + * @param {string|number} id The `id` argument received by {@link Mapper#afterUpdate}. + * @param {object} props The `props` argument received by {@link Mapper#afterUpdate}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdate}. + * @param {object} result The `result` argument received by {@link Mapper#afterUpdate}. + * @see SimpleStore#event:afterUpdate + * @see SimpleStore#update + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#update}. Adds the updated {@link Record} to the + * store. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('post'); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // PUT /post/1234 {"status":"published"} + * store.update('post', 1, { status: 'published' }).then((post) => { + * // The post record has also been updated in the in-memory store + * console.log(store.get('post', 1234)); + * }); + * + * @fires SimpleStore#beforeUpdate + * @fires SimpleStore#afterUpdate + * @fires SimpleStore#add + * @method SimpleStore#update + * @param {string} name Name of the {@link Mapper} to target. + * @param {(string|number)} id Passed to {@link Mapper#update}. + * @param {object} record Passed to {@link Mapper#update}. + * @param {object} [opts] Passed to {@link Mapper#update}. See + * {@link Mapper#update} for more configuration options. + * @returns {Promise} Resolves with the result of the update. + * @since 3.0.0 + */ + update: function update(name, id, record, opts) { + var _this11 = this; + + opts || (opts = {}); + return Container.prototype.update.call(this, name, id, record, opts).then(function (result) { + return _this11._end(name, result, opts); + }); + }, + + + /** + * Fired during {@link SimpleStore#updateAll}. See + * {@link SimpleStore~beforeUpdateAllListener} for how to listen for this event. + * + * @event SimpleStore#beforeUpdateAll + * @see SimpleStore~beforeUpdateAllListener + * @see SimpleStore#updateAll + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeUpdateAll} event. + * + * @example + * function onBeforeUpdateAll (mapperName, props, query, opts) { + * // do something + * } + * store.on('beforeUpdateAll', onBeforeUpdateAll); + * + * @callback SimpleStore~beforeUpdateAllListener + * @param {string} name The `name` argument received by {@link Mapper#beforeUpdateAll}. + * @param {object} props The `props` argument received by {@link Mapper#beforeUpdateAll}. + * @param {object} query The `query` argument received by {@link Mapper#beforeUpdateAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateAll}. + * @see SimpleStore#event:beforeUpdateAll + * @see SimpleStore#updateAll + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#updateAll}. See + * {@link SimpleStore~afterUpdateAllListener} for how to listen for this event. + * + * @event SimpleStore#afterUpdateAll + * @see SimpleStore~afterUpdateAllListener + * @see SimpleStore#updateAll + */ + /** + * Callback signature for the {@link SimpleStore#event:afterUpdateAll} event. + * + * @example + * function onAfterUpdateAll (mapperName, props, query, opts, result) { + * // do something + * } + * store.on('afterUpdateAll', onAfterUpdateAll); + * + * @callback SimpleStore~afterUpdateAllListener + * @param {string} name The `name` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} props The `props` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} query The `query` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateAll}. + * @param {object} result The `result` argument received by {@link Mapper#afterUpdateAll}. + * @see SimpleStore#event:afterUpdateAll + * @see SimpleStore#updateAll + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#updateAll}. Adds the updated {@link Record}s to + * the store. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('post'); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // PUT /post?author_id=1234 {"status":"published"} + * store.updateAll('post', { author_id: 1234 }, { status: 'published' }).then((posts) => { + * // The post records have also been updated in the in-memory store + * console.log(store.filter('posts', { author_id: 1234 })); + * }); + * + * @fires SimpleStore#beforeUpdateAll + * @fires SimpleStore#afterUpdateAll + * @fires SimpleStore#add + * @method SimpleStore#updateAll + * @param {string} name Name of the {@link Mapper} to target. + * @param {object} props Passed to {@link Mapper#updateAll}. + * @param {object} [query] Passed to {@link Mapper#updateAll}. + * @param {object} [opts] Passed to {@link Mapper#updateAll}. See + * {@link Mapper#updateAll} for more configuration options. + * @returns {Promise} Resolves with the result of the update. + * @since 3.0.0 + */ + updateAll: function updateAll(name, props, query, opts) { + var _this12 = this; + + opts || (opts = {}); + return Container.prototype.updateAll.call(this, name, props, query, opts).then(function (result) { + return _this12._end(name, result, opts); + }); + }, + + + /** + * Fired during {@link SimpleStore#updateMany}. See + * {@link SimpleStore~beforeUpdateManyListener} for how to listen for this event. + * + * @event SimpleStore#beforeUpdateMany + * @see SimpleStore~beforeUpdateManyListener + * @see SimpleStore#updateMany + */ + /** + * Callback signature for the {@link SimpleStore#event:beforeUpdateMany} event. + * + * @example + * function onBeforeUpdateMany (mapperName, records, opts) { + * // do something + * } + * store.on('beforeUpdateMany', onBeforeUpdateMany); + * + * @callback SimpleStore~beforeUpdateManyListener + * @param {string} name The `name` argument received by {@link Mapper#beforeUpdateMany}. + * @param {object} records The `records` argument received by {@link Mapper#beforeUpdateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateMany}. + * @see SimpleStore#event:beforeUpdateMany + * @see SimpleStore#updateMany + * @since 3.0.0 + */ + /** + * Fired during {@link SimpleStore#updateMany}. See + * {@link SimpleStore~afterUpdateManyListener} for how to listen for this event. + * + * @event SimpleStore#afterUpdateMany + * @see SimpleStore~afterUpdateManyListener + * @see SimpleStore#updateMany + */ + /** + * Callback signature for the {@link SimpleStore#event:afterUpdateMany} event. + * + * @example + * function onAfterUpdateMany (mapperName, records, opts, result) { + * // do something + * } + * store.on('afterUpdateMany', onAfterUpdateMany); + * + * @callback SimpleStore~afterUpdateManyListener + * @param {string} name The `name` argument received by {@link Mapper#afterUpdateMany}. + * @param {object} records The `records` argument received by {@link Mapper#afterUpdateMany}. + * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateMany}. + * @param {object} result The `result` argument received by {@link Mapper#afterUpdateMany}. + * @see SimpleStore#event:afterUpdateMany + * @see SimpleStore#updateMany + * @since 3.0.0 + */ + /** + * Wrapper for {@link Mapper#updateMany}. Adds the updated {@link Record}s to + * the store. + * + * @example + * import { SimpleStore } from 'js-data'; + * import { HttpAdapter } from 'js-data-http'; + * + * const store = new SimpleStore(); + * store.registerAdapter('http', new HttpAdapter(), { default: true }); + * + * store.defineMapper('post'); + * + * // Since this example uses the http adapter, we'll get something like: + * // + * // PUT /post [{"id":3,status":"published"},{"id":4,status":"published"}] + * store.updateMany('post', [ + * { id: 3, status: 'published' }, + * { id: 4, status: 'published' } + * ]).then((posts) => { + * // The post records have also been updated in the in-memory store + * console.log(store.getAll('post', 3, 4)); + * }); + * + * @fires SimpleStore#beforeUpdateMany + * @fires SimpleStore#afterUpdateMany + * @fires SimpleStore#add + * @method SimpleStore#updateMany + * @param {string} name Name of the {@link Mapper} to target. + * @param {(Object[]|Record[])} records Passed to {@link Mapper#updateMany}. + * @param {object} [opts] Passed to {@link Mapper#updateMany}. See + * {@link Mapper#updateMany} for more configuration options. + * @returns {Promise} Resolves with the result of the update. + * @since 3.0.0 + */ + updateMany: function updateMany(name, records, opts) { + var _this13 = this; + + opts || (opts = {}); + return Container.prototype.updateMany.call(this, name, records, opts).then(function (result) { + return _this13._end(name, result, opts); + }); + } +}; + +proxiedCollectionMethods.forEach(function (method) { + props$2[method] = function (name) { + var _getCollection; + + for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + + return (_getCollection = this.getCollection(name))[method].apply(_getCollection, args); + }; +}); + +var SimpleStore$1 = Container.extend(props$2); + +/** + * Fired when a record changes. Only works for records that have tracked fields. + * See {@link SimpleStore~changeListener} on how to listen for this event. + * + * @event SimpleStore#change + * @see SimpleStore~changeListener + */ + +/** + * Callback signature for the {@link SimpleStore#event:change} event. + * + * @example + * function onChange (mapperName, record, changes) { + * // do something + * } + * store.on('change', onChange); + * + * @callback SimpleStore~changeListener + * @param {string} name The name of the associated {@link Mapper}. + * @param {Record} record The Record that changed. + * @param {object} changes The changes. + * @see SimpleStore#event:change + * @since 3.0.0 + */ + +/** + * Fired when one or more records are added to the in-memory store. See + * {@link SimpleStore~addListener} on how to listen for this event. + * + * @event SimpleStore#add + * @see SimpleStore~addListener + * @see SimpleStore#event:add + * @see SimpleStore#add + * @see SimpleStore#create + * @see SimpleStore#createMany + * @see SimpleStore#find + * @see SimpleStore#findAll + * @see SimpleStore#update + * @see SimpleStore#updateAll + * @see SimpleStore#updateMany + */ + +/** + * Callback signature for the {@link SimpleStore#event:add} event. + * + * @example + * function onAdd (mapperName, recordOrRecords) { + * // do something + * } + * store.on('add', onAdd); + * + * @callback SimpleStore~addListener + * @param {string} name The name of the associated {@link Mapper}. + * @param {Record|Record[]} The Record or Records that were added. + * @see SimpleStore#event:add + * @see SimpleStore#add + * @see SimpleStore#create + * @see SimpleStore#createMany + * @see SimpleStore#find + * @see SimpleStore#findAll + * @see SimpleStore#update + * @see SimpleStore#updateAll + * @see SimpleStore#updateMany + * @since 3.0.0 + */ + +/** + * Fired when one or more records are removed from the in-memory store. See + * {@link SimpleStore~removeListener} for how to listen for this event. + * + * @event SimpleStore#remove + * @see SimpleStore~removeListener + * @see SimpleStore#event:remove + * @see SimpleStore#clear + * @see SimpleStore#destroy + * @see SimpleStore#destroyAll + * @see SimpleStore#remove + * @see SimpleStore#removeAll + */ + +/** + * Callback signature for the {@link SimpleStore#event:remove} event. + * + * @example + * function onRemove (mapperName, recordsOrRecords) { + * // do something + * } + * store.on('remove', onRemove); + * + * @callback SimpleStore~removeListener + * @param {string} name The name of the associated {@link Mapper}. + * @param {Record|Record[]} Record or Records that were removed. + * @see SimpleStore#event:remove + * @see SimpleStore#clear + * @see SimpleStore#destroy + * @see SimpleStore#destroyAll + * @see SimpleStore#remove + * @see SimpleStore#removeAll + * @since 3.0.0 + */ + +/** + * Create a subclass of this SimpleStore: + * @example SimpleStore.extend + * const JSData = require('js-data'); + * const { SimpleStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomSimpleStoreClass extends SimpleStore { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customSimpleStore = new CustomSimpleStoreClass(); + * console.log(customSimpleStore.foo()); + * console.log(CustomSimpleStoreClass.beep()); + * + * // Extend the class using alternate method. + * const OtherSimpleStoreClass = SimpleStore.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }) + * const otherSimpleStore = new OtherSimpleStoreClass(); + * console.log(otherSimpleStore.foo()); + * console.log(OtherSimpleStoreClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherSimpleStoreClass () { + * SimpleStore.call(this) + * this.created_at = new Date().getTime() + * } + * SimpleStore.extend({ + * constructor: AnotherSimpleStoreClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }) + * const anotherSimpleStore = new AnotherSimpleStoreClass(); + * console.log(anotherSimpleStore.created_at); + * console.log(anotherSimpleStore.foo()); + * console.log(AnotherSimpleStoreClass.beep()); + * + * @method SimpleStore.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this SimpleStore class. + * @since 3.0.0 + */ + +var DOMAIN$9 = 'LinkedCollection'; + +/** + * Extends {@link Collection}. Used by a {@link DataStore} to implement an + * Identity Map. + * + * ```javascript + * import {LinkedCollection} from 'js-data' + * ``` + * + * @class LinkedCollection + * @extends Collection + * @param {array} [records] Initial set of records to insert into the + * collection. See {@link Collection}. + * @param {object} [opts] Configuration options. See {@link Collection}. + * @returns {Mapper} + */ +function LinkedCollection(records, opts) { + utils.classCallCheck(this, LinkedCollection); + // Make sure this collection has somewhere to store "added" timestamps + Object.defineProperties(this, { + _added: { + value: {} + }, + datastore: { + writable: true, + value: undefined + } + }); + + Collection$1.call(this, records, opts); + + // Make sure this collection has a reference to a datastore + if (!this.datastore) { + throw utils.err('new ' + DOMAIN$9, 'opts.datastore')(400, 'DataStore', this.datastore); + } +} + +var LinkedCollection$1 = Collection$1.extend({ + constructor: LinkedCollection, + + _addMeta: function _addMeta(record, timestamp) { + // Track when this record was added + this._added[this.recordId(record)] = timestamp; + + if (utils.isFunction(record._set)) { + record._set('$', timestamp); + } + }, + _clearMeta: function _clearMeta(record) { + delete this._added[this.recordId(record)]; + if (utils.isFunction(record._set)) { + record._set('$'); // unset + } + }, + _onRecordEvent: function _onRecordEvent() { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + Collection$1.prototype._onRecordEvent.apply(this, args); + var event = args[0]; + // This is a very brute force method + // Lots of room for optimization + if (utils.isString(event) && event.indexOf('change') === 0) { + this.updateIndexes(args[1]); + } + }, + add: function add(records, opts) { + var _this = this; + + var mapper = this.mapper; + var timestamp = new Date().getTime(); + var singular = utils.isObject(records) && !utils.isArray(records); + + if (singular) { + records = [records]; + } + records = Collection$1.prototype.add.call(this, records, opts); + + if (mapper.relationList.length && records.length) { + // Check the currently visited record for relations that need to be + // inserted into their respective collections. + mapper.relationList.forEach(function (def) { + def.addLinkedRecords(records); + }); + } + + records.forEach(function (record) { + return _this._addMeta(record, timestamp); + }); + + return singular ? records[0] : records; + }, + remove: function remove(idOrRecord, opts) { + var mapper = this.mapper; + var record = Collection$1.prototype.remove.call(this, idOrRecord, opts); + if (record) { + this._clearMeta(record); + } + + if (mapper.relationList.length && record) { + mapper.relationList.forEach(function (def) { + def.removeLinkedRecords(mapper, [record]); + }); + } + + return record; + }, + removeAll: function removeAll(query, opts) { + var mapper = this.mapper; + var records = Collection$1.prototype.removeAll.call(this, query, opts); + records.forEach(this._clearMeta, this); + + if (mapper.relationList.length && records.length) { + mapper.relationList.forEach(function (def) { + def.removeLinkedRecords(mapper, records); + }); + } + + return records; + } +}); + +/** + * Create a subclass of this LinkedCollection: + * + * @example LinkedCollection.extend + * const JSData = require('js-data'); + * const { LinkedCollection } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomLinkedCollectionClass extends LinkedCollection { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customLinkedCollection = new CustomLinkedCollectionClass(); + * console.log(customLinkedCollection.foo()); + * console.log(CustomLinkedCollectionClass.beep()); + * + * // Extend the class using alternate method. + * const OtherLinkedCollectionClass = LinkedCollection.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherLinkedCollection = new OtherLinkedCollectionClass(); + * console.log(otherLinkedCollection.foo()); + * console.log(OtherLinkedCollectionClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherLinkedCollectionClass () { + * LinkedCollection.call(this); + * this.created_at = new Date().getTime(); + * } + * LinkedCollection.extend({ + * constructor: AnotherLinkedCollectionClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const anotherLinkedCollection = new AnotherLinkedCollectionClass(); + * console.log(anotherLinkedCollection.created_at); + * console.log(anotherLinkedCollection.foo()); + * console.log(AnotherLinkedCollectionClass.beep()); + * + * @method LinkedCollection.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this LinkedCollection class. + * @since 3.0.0 + */ + +var DATASTORE_DEFAULTS = { + /** + * Whether in-memory relations should be unlinked from records after they are + * destroyed. + * + * @default true + * @name DataStore#unlinkOnDestroy + * @since 3.0.0 + * @type {boolean} + */ + unlinkOnDestroy: true + + /** + * The `DataStore` class is an extension of {@link SimpleStore}. Not only does + * `DataStore` manage mappers and store data in collections, it uses the + * {@link LinkedCollection} class to link related records together in memory. + * + * ```javascript + * import { DataStore } from 'js-data'; + * ``` + * + * @example + * import { DataStore } from 'js-data'; + * import HttpAdapter from 'js-data-http'; + * const store = new DataStore(); + * + * // DataStore#defineMapper returns a direct reference to the newly created + * // Mapper. + * const UserMapper = store.defineMapper('user'); + * + * // DataStore#as returns the store scoped to a particular Mapper. + * const UserStore = store.as('user'); + * + * // Call "find" on "UserMapper" (Stateless ORM) + * UserMapper.find(1).then((user) => { + * // retrieved a "user" record via the http adapter, but that's it + * + * // Call "find" on "store" targeting "user" (Stateful DataStore) + * return store.find('user', 1); // same as "UserStore.find(1)" + * }).then((user) => { + * // not only was a "user" record retrieved, but it was added to the + * // store's "user" collection + * const cachedUser = store.getCollection('user').get(1); + * console.log(user === cachedUser); // true + * }); + * + * @class DataStore + * @extends SimpleStore + * @param {object} [opts] Configuration options. See {@link SimpleStore}. + * @param {boolean} [opts.collectionClass={@link LinkedCollection}] See {@link DataStore#collectionClass}. + * @param {boolean} [opts.debug=false] See {@link Component#debug}. + * @param {boolean} [opts.unlinkOnDestroy=true] See {@link DataStore#unlinkOnDestroy}. + * @param {boolean|Function} [opts.usePendingFind=true] See {@link DataStore#usePendingFind}. + * @param {boolean|Function} [opts.usePendingFindAll=true] See {@link DataStore#usePendingFindAll}. + * @returns {DataStore} + * @see SimpleStore + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#datastore","Components of JSData: DataStore"] + * @tutorial ["http://www.js-data.io/v3.0/docs/working-with-the-datastore","Working with the DataStore"] + * @tutorial ["http://www.js-data.io/v3.0/docs/jsdata-and-the-browser","Notes on using JSData in the Browser"] + */ +};function DataStore(opts) { + utils.classCallCheck(this, DataStore); + + opts || (opts = {}); + // Fill in any missing options with the defaults + utils.fillIn(opts, DATASTORE_DEFAULTS); + opts.collectionClass || (opts.collectionClass = LinkedCollection$1); + SimpleStore$1.call(this, opts); +} + +var props$1 = { + constructor: DataStore, + + defineMapper: function defineMapper(name, opts) { + // Complexity of this method is beyond simply using => functions to bind context + var self = this; + var mapper = SimpleStore$1.prototype.defineMapper.call(self, name, opts); + var idAttribute = mapper.idAttribute; + var collection = this.getCollection(name); + + mapper.relationList.forEach(function (def) { + var relation = def.relation; + var localField = def.localField; + var path = 'links.' + localField; + var foreignKey = def.foreignKey; + var type = def.type; + var updateOpts = { index: foreignKey }; + var descriptor = void 0; + + var getter = function getter() { + return this._get(path); + }; + + if (type === belongsToType) { + if (!collection.indexes[foreignKey]) { + collection.createIndex(foreignKey); + } + + descriptor = { + get: getter, + // e.g. profile.user = someUser + // or comment.post = somePost + set: function set(record) { + // e.g. const otherUser = profile.user + var currentParent = this._get(path); + // e.g. profile.user === someUser + if (record === currentParent) { + return currentParent; + } + var id = utils.get(this, idAttribute); + var inverseDef = def.getInverse(mapper); + + // e.g. profile.user !== someUser + // or comment.post !== somePost + if (currentParent && inverseDef) { + this.removeInverseRelation(currentParent, id, inverseDef, idAttribute); + } + if (record) { + // e.g. profile.user = someUser + var relatedIdAttribute = def.getRelation().idAttribute; + var relatedId = utils.get(record, relatedIdAttribute); + + // Prefer store record + if (relatedId !== undefined && this._get('$')) { + record = self.get(relation, relatedId) || record; + } + + // Set locals + // e.g. profile.user = someUser + // or comment.post = somePost + safeSetLink(this, localField, record); + safeSetProp(this, foreignKey, relatedId); + collection.updateIndex(this, updateOpts); + + if (inverseDef) { + this.setupInverseRelation(record, id, inverseDef, idAttribute); + } + } else { + // Unset in-memory link only + // e.g. profile.user = undefined + // or comment.post = undefined + safeSetLink(this, localField, undefined); + } + return record; + } + }; + + var foreignKeyDescriptor = Object.getOwnPropertyDescriptor(mapper.recordClass.prototype, foreignKey); + if (!foreignKeyDescriptor) { + foreignKeyDescriptor = { + enumerable: true + }; + } + var originalGet = foreignKeyDescriptor.get; + foreignKeyDescriptor.get = function () { + if (originalGet) { + return originalGet.call(this); + } + return this._get('props.' + foreignKey); + }; + var originalSet = foreignKeyDescriptor.set; + foreignKeyDescriptor.set = function (value) { + var _this = this; + + if (originalSet) { + originalSet.call(this, value); + } + var currentParent = utils.get(this, localField); + var id = utils.get(this, idAttribute); + var inverseDef = def.getInverse(mapper); + var currentParentId = currentParent ? utils.get(currentParent, def.getRelation().idAttribute) : undefined; + + if (currentParent && currentParentId !== undefined && currentParentId !== value) { + if (inverseDef.type === hasOneType) { + safeSetLink(currentParent, inverseDef.localField, undefined); + } else if (inverseDef.type === hasManyType) { + var children = utils.get(currentParent, inverseDef.localField); + if (id === undefined) { + utils.remove(children, function (child) { + return child === _this; + }); + } else { + utils.remove(children, function (child) { + return child === _this || id === utils.get(child, idAttribute); + }); + } + } + } + + safeSetProp(this, foreignKey, value); + collection.updateIndex(this, updateOpts); + + if (value === undefined || value === null) { + if (currentParentId !== undefined) { + // Unset locals + utils.set(this, localField, undefined); + } + } else if (this._get('$')) { + var storeRecord = self.get(relation, value); + if (storeRecord) { + utils.set(this, localField, storeRecord); + } + } + }; + Object.defineProperty(mapper.recordClass.prototype, foreignKey, foreignKeyDescriptor); + } else if (type === hasManyType) { + var localKeys = def.localKeys; + var foreignKeys = def.foreignKeys; + + // TODO: Handle case when belongsTo relation isn't ever defined + if (self._collections[relation] && foreignKey && !self.getCollection(relation).indexes[foreignKey]) { + self.getCollection(relation).createIndex(foreignKey); + } + + descriptor = { + get: function get() { + var current = getter.call(this); + if (!current) { + this._set(path, []); + } + return getter.call(this); + }, + + // e.g. post.comments = someComments + // or user.groups = someGroups + // or group.users = someUsers + set: function set(records) { + var _this2 = this; + + if (records && !utils.isArray(records)) { + records = [records]; + } + var id = utils.get(this, idAttribute); + var relatedIdAttribute = def.getRelation().idAttribute; + var inverseDef = def.getInverse(mapper); + var inverseLocalField = inverseDef.localField; + var current = this._get(path) || []; + var toLink = []; + var toLinkIds = {}; + + if (records) { + records.forEach(function (record) { + // e.g. comment.id + var relatedId = utils.get(record, relatedIdAttribute); + var currentParent = utils.get(record, inverseLocalField); + if (currentParent && currentParent !== _this2) { + var currentChildrenOfParent = utils.get(currentParent, localField); + // e.g. somePost.comments.remove(comment) + if (relatedId === undefined) { + utils.remove(currentChildrenOfParent, function (child) { + return child === record; + }); + } else { + utils.remove(currentChildrenOfParent, function (child) { + return child === record || relatedId === utils.get(child, relatedIdAttribute); + }); + } + } + if (relatedId !== undefined) { + if (_this2._get('$')) { + // Prefer store record + record = self.get(relation, relatedId) || record; + } + // e.g. toLinkIds[comment.id] = comment + toLinkIds[relatedId] = record; + } + toLink.push(record); + }); + } + + // e.g. post.comments = someComments + if (foreignKey) { + current.forEach(function (record) { + // e.g. comment.id + var relatedId = utils.get(record, relatedIdAttribute); + if (relatedId === undefined && toLink.indexOf(record) === -1 || relatedId !== undefined && !(relatedId in toLinkIds)) { + // Update (unset) inverse relation + if (records) { + // e.g. comment.post_id = undefined + safeSetProp(record, foreignKey, undefined); + // e.g. CommentCollection.updateIndex(comment, { index: 'post_id' }) + self.getCollection(relation).updateIndex(record, updateOpts); + } + // e.g. comment.post = undefined + safeSetLink(record, inverseLocalField, undefined); + } + }); + toLink.forEach(function (record) { + // Update (set) inverse relation + // e.g. comment.post_id = post.id + safeSetProp(record, foreignKey, id); + // e.g. CommentCollection.updateIndex(comment, { index: 'post_id' }) + self.getCollection(relation).updateIndex(record, updateOpts); + // e.g. comment.post = post + safeSetLink(record, inverseLocalField, _this2); + }); + } else if (localKeys) { + // Update locals + // e.g. group.users = someUsers + // Update (set) inverse relation + var ids = toLink.map(function (child) { + return utils.get(child, relatedIdAttribute); + }).filter(function (id) { + return id !== undefined; + }); + // e.g. group.user_ids = [1,2,3,...] + utils.set(this, localKeys, ids); + // Update (unset) inverse relation + if (inverseDef.foreignKeys) { + current.forEach(function (child) { + var relatedId = utils.get(child, relatedIdAttribute); + if (relatedId === undefined && toLink.indexOf(child) === -1 || relatedId !== undefined && !(relatedId in toLinkIds)) { + // Update inverse relation + // safeSetLink(child, inverseLocalField, undefined) + var parents = utils.get(child, inverseLocalField) || []; + // e.g. someUser.groups.remove(group) + if (id === undefined) { + utils.remove(parents, function (parent) { + return parent === _this2; + }); + } else { + utils.remove(parents, function (parent) { + return parent === _this2 || id === utils.get(parent, idAttribute); + }); + } + } + }); + toLink.forEach(function (child) { + // Update (set) inverse relation + var parents = utils.get(child, inverseLocalField); + // e.g. someUser.groups.push(group) + if (id === undefined) { + utils.noDupeAdd(parents, _this2, function (parent) { + return parent === _this2; + }); + } else { + utils.noDupeAdd(parents, _this2, function (parent) { + return parent === _this2 || id === utils.get(parent, idAttribute); + }); + } + }); + } + } else if (foreignKeys) { + // e.g. user.groups = someGroups + // Update (unset) inverse relation + current.forEach(function (parent) { + var ids = utils.get(parent, foreignKeys) || []; + // e.g. someGroup.user_ids.remove(user.id) + utils.remove(ids, function (_key) { + return id === _key; + }); + var children = utils.get(parent, inverseLocalField); + // e.g. someGroup.users.remove(user) + if (id === undefined) { + utils.remove(children, function (child) { + return child === _this2; + }); + } else { + utils.remove(children, function (child) { + return child === _this2 || id === utils.get(child, idAttribute); + }); + } + }); + // Update (set) inverse relation + toLink.forEach(function (parent) { + var ids = utils.get(parent, foreignKeys) || []; + utils.noDupeAdd(ids, id, function (_key) { + return id === _key; + }); + var children = utils.get(parent, inverseLocalField); + if (id === undefined) { + utils.noDupeAdd(children, _this2, function (child) { + return child === _this2; + }); + } else { + utils.noDupeAdd(children, _this2, function (child) { + return child === _this2 || id === utils.get(child, idAttribute); + }); + } + }); + } + + this._set(path, toLink); + return toLink; + } + }; + } else if (type === hasOneType) { + // TODO: Handle case when belongsTo relation isn't ever defined + if (self._collections[relation] && foreignKey && !self.getCollection(relation).indexes[foreignKey]) { + self.getCollection(relation).createIndex(foreignKey); + } + descriptor = { + get: getter, + // e.g. user.profile = someProfile + set: function set(record) { + var current = this._get(path); + if (record === current) { + return current; + } + var inverseLocalField = def.getInverse(mapper).localField; + // Update (unset) inverse relation + if (current) { + safeSetProp(current, foreignKey, undefined); + self.getCollection(relation).updateIndex(current, updateOpts); + safeSetLink(current, inverseLocalField, undefined); + } + if (record) { + var relatedId = utils.get(record, def.getRelation().idAttribute); + // Prefer store record + if (relatedId !== undefined) { + record = self.get(relation, relatedId) || record; + } + + // Set locals + safeSetLink(this, localField, record); + + // Update (set) inverse relation + safeSetProp(record, foreignKey, utils.get(this, idAttribute)); + self.getCollection(relation).updateIndex(record, updateOpts); + safeSetLink(record, inverseLocalField, this); + } else { + // Unset locals + safeSetLink(this, localField, undefined); + } + return record; + } + }; + } + + if (descriptor) { + descriptor.enumerable = def.enumerable === undefined ? false : def.enumerable; + if (def.get) { + var origGet = descriptor.get; + descriptor.get = function () { + var _this3 = this; + + return def.get(def, this, function () { + for (var _len = arguments.length, args = Array(_len), _key2 = 0; _key2 < _len; _key2++) { + args[_key2] = arguments[_key2]; + } + + return origGet.apply(_this3, args); + }); + }; + } + if (def.set) { + var origSet = descriptor.set; + descriptor.set = function (related) { + var _this4 = this; + + return def.set(def, this, related, function (value) { + return origSet.call(_this4, value === undefined ? related : value); + }); + }; + } + Object.defineProperty(mapper.recordClass.prototype, localField, descriptor); + } + }); + + return mapper; + }, + destroy: function destroy(name, id, opts) { + var _this5 = this; + + opts || (opts = {}); + return SimpleStore$1.prototype.destroy.call(this, name, id, opts).then(function (result) { + var record = void 0; + if (opts.raw) { + record = result.data; + } else { + record = result; + } + + if (record && _this5.unlinkOnDestroy) { + var _opts = utils.plainCopy(opts); + _opts.withAll = true; + utils.forEachRelation(_this5.getMapper(name), _opts, function (def) { + utils.set(record, def.localField, undefined); + }); + } + return result; + }); + }, + destroyAll: function destroyAll(name, query, opts) { + var _this6 = this; + + opts || (opts = {}); + return SimpleStore$1.prototype.destroyAll.call(this, name, query, opts).then(function (result) { + var records = void 0; + if (opts.raw) { + records = result.data; + } else { + records = result; + } + + if (records && records.length && _this6.unlinkOnDestroy) { + var _opts = utils.plainCopy(opts); + _opts.withAll = true; + utils.forEachRelation(_this6.getMapper(name), _opts, function (def) { + records.forEach(function (record) { + utils.set(record, def.localField, undefined); + }); + }); + } + return result; + }); + } +}; + +var DataStore$1 = SimpleStore$1.extend(props$1); + +/** + * Create a subclass of this DataStore: + * @example DataStore.extend + * const JSData = require('js-data'); + * const { DataStore } = JSData; + * console.log('Using JSData v' + JSData.version.full); + * + * // Extend the class using ES2015 class syntax. + * class CustomDataStoreClass extends DataStore { + * foo () { return 'bar'; } + * static beep () { return 'boop'; } + * } + * const customDataStore = new CustomDataStoreClass(); + * console.log(customDataStore.foo()); + * console.log(CustomDataStoreClass.beep()); + * + * // Extend the class using alternate method. + * const OtherDataStoreClass = DataStore.extend({ + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const otherDataStore = new OtherDataStoreClass(); + * console.log(otherDataStore.foo()); + * console.log(OtherDataStoreClass.beep()); + * + * // Extend the class, providing a custom constructor. + * function AnotherDataStoreClass () { + * DataStore.call(this); + * this.created_at = new Date().getTime(); + * } + * DataStore.extend({ + * constructor: AnotherDataStoreClass, + * foo () { return 'bar'; } + * }, { + * beep () { return 'boop'; } + * }); + * const anotherDataStore = new AnotherDataStoreClass(); + * console.log(anotherDataStore.created_at); + * console.log(anotherDataStore.foo()); + * console.log(AnotherDataStoreClass.beep()); + * + * @method DataStore.extend + * @param {object} [props={}] Properties to add to the prototype of the + * subclass. + * @param {object} [props.constructor] Provide a custom constructor function + * to be used as the subclass itself. + * @param {object} [classProps={}] Static properties to add to the subclass. + * @returns {Constructor} Subclass of this DataStore class. + * @since 3.0.0 + */ + +/** + * Registered as `js-data` in NPM and Bower. + * + * Also available from CDN.JS and JSDelivr. + * + * @module js-data + * + * @example Install from NPM + * npm i --save js-data@beta + * @example Install from Bower + * bower i --save js-data@3.0.0-beta.1 + * @example Install from CDN.JS + * + * @example Install from JSDelivr + * + * @example Load into your app via script tag + * + * + * @example Load into your app via CommonJS + * var JSData = require('js-data'); + * @example Load into your app via ES2015 Modules + * import * as JSData from 'js-data'; + * @example Load into your app via AMD + * define('myApp', ['js-data'], function (JSData) { ... }); + */ + +/** + * JSData's utility methods. + * + * @example + * import { utils } from 'js-data'; + * console.log(utils.isString('foo')); // true + * + * @name module:js-data.utils + * @property {Function} Promise See {@link utils.Promise}. + * @see utils + * @since 3.0.0 + * @type {Object} + */ +/** + * JSData's {@link Collection} class. + * + * @example + * import { Collection } from 'js-data'; + * const collection = new Collection(); + * + * @name module:js-data.Collection + * @see Collection + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#collection","Components of JSData: Collection"] + * @type {Constructor} + */ +/** + * JSData's {@link Component} class. Most components in JSData extend this + * class. + * + * @example + * import { Component } from 'js-data'; + * // Make a custom component. + * const MyComponent = Component.extend({ + * myMethod (someArg) { ... } + * }); + * + * @name module:js-data.Component + * @see Component + * @since 3.0.0 + * @type {Constructor} + */ +/** + * JSData's {@link Container} class. Defines and manages {@link Mapper}s. Used + * in Node.js and in the browser, though in the browser you may want to use + * {@link DataStore} instead. + * + * @example + * import { Container } from 'js-data'; + * const store = new Container(); + * + * @name module:js-data.Container + * @see Container + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#container","Components of JSData: Container"] + * @type {Constructor} + */ +/** + * JSData's {@link DataStore} class. Primarily for use in the browser. In + * Node.js you probably want to use {@link Container} instead. + * + * @example + * import { DataStore } from 'js-data'; + * const store = new DataStore(); + * + * @name module:js-data.DataStore + * @see DataStore + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#datastore","Components of JSData: DataStore"] + * @type {Constructor} + */ +/** + * JSData's {@link Index} class, based on [mindex]{@link https://github.com/internalfx/mindex}. + * + * @name module:js-data.Index + * @see Index + * @since 3.0.0 + * @type {Constructor} + */ +/** + * JSData's {@link LinkedCollection} class. Used by the {@link DataStore} + * component. If you need to create a collection manually, you should probably + * use the {@link Collection} class. + * + * @name module:js-data.LinkedCollection + * @see DataStore + * @see LinkedCollection + * @since 3.0.0 + * @type {Constructor} + */ +/** + * JSData's {@link Mapper} class. The core of the ORM. + * + * @example Recommended use + * import { Container } from 'js-data'; + * const store = new Container(); + * store.defineMapper('user'); + * + * @example Create Mapper manually + * import { Mapper } from 'js-data'; + * const UserMapper = new Mapper({ name: 'user' }); + * + * @name module:js-data.Mapper + * @see Container + * @see Mapper + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/modeling-your-data","Modeling your data"] + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#mapper","Components of JSData: Mapper"] + * @type {Constructor} + */ +/** + * JSData's {@link Query} class. Used by the {@link Collection} component. + * + * @name module:js-data.Query + * @see Query + * @since 3.0.0 + * @type {Constructor} + */ +/** + * JSData's {@link Record} class. + * + * @example + * import { Container } from 'js-data'; + * const store = new Container(); + * store.defineMapper('user'); + * const user = store.createRecord('user'); + * + * @name module:js-data.Record + * @see Record + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#record","Components of JSData: Record"] + * @type {Constructor} + */ +/** + * JSData's {@link Schema} class. Implements http://json-schema.org/draft-04. + * + * @example + * import { Container, Schema } from 'js-data'; + * const userSchema = new Schema({ + * properties: { + * id: { type: 'string' }, + * name: { type: 'string' } + * } + * }); + * const store = new Container(); + * store.defineMapper('user', { + * schema: userSchema + * }); + * + * @name module:js-data.Schema + * @see Schema + * @see http://json-schema.org/ + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#schema","Components of JSData: schema"] + * @tutorial ["http://www.js-data.io/v3.0/docs/schemas","JSData's Schema Syntax"] + * @type {Constructor} + */ +/** + * JSData's {@link Settable} class. + * + * @example + * import { Settable } from 'js-data'; + * const obj = new Settable(); + * obj.set('secret', 'value'); + * console.log(JSON.stringify(obj)); // {} + * + * @name module:js-data.Settable + * @see Settable + * @since 3.0.0 + * @type {Constructor} + */ +/** + * JSData's {@link SimpleStore} class. Primarily for use in the browser. In + * Node.js you probably want to use {@link Container} instead. + * + * @example + * import { SimpleStore } from 'js-data'; + * const store = new SimpleStore(); + * + * @name module:js-data.SimpleStore + * @see SimpleStore + * @since 3.0.0 + * @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#SimpleStore","Components of JSData: SimpleStore"] + * @type {Constructor} + */ +/** + * Describes the version of this `JSData` object. + * + * @example + * console.log(JSData.version.full); // "3.0.0-beta.1" + * + * @name version + * @memberof module:js-data + * @property {string} full The full semver value. + * @property {number} major The major version number. + * @property {number} minor The minor version number. + * @property {number} patch The patch version number. + * @property {(string|boolean)} alpha The alpha version value, otherwise `false` + * if the current version is not alpha. + * @property {(string|boolean)} beta The beta version value, otherwise `false` + * if the current version is not beta. + * @since 2.0.0 + * @type {Object} + */ +var version = { + full: '3.0.2', + major: 3, + minor: 0, + patch: 2 +}; + +exports.version = version; +exports.Collection = Collection$1; +exports.Component = Component$1; +exports.Container = Container; +exports.DataStore = DataStore$1; +exports.Index = Index; +exports.LinkedCollection = LinkedCollection$1; +exports.Mapper = Mapper$1; +exports.Query = Query$1; +exports.Record = Record$1; +exports.Schema = Schema$1; +exports.Settable = Settable; +exports.SimpleStore = SimpleStore$1; +exports.utils = utils; +exports.belongsTo = belongsTo; +exports.hasMany = hasMany; +exports.hasOne = hasOne; +exports.belongsToType = belongsToType; +exports.hasManyType = hasManyType; +exports.hasOneType = hasOneType; + +Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=js-data.js.map diff --git a/dist/js-data.js.map b/dist/js-data.js.map new file mode 100644 index 00000000..81a48b0c --- /dev/null +++ b/dist/js-data.js.map @@ -0,0 +1 @@ +{"version":3,"file":"js-data.js","sources":["../src/utils.js","../src/Settable.js","../src/Component.js","../src/Query.js","../src/Relation.js","../src/Relation/BelongsTo.js","../src/Relation/HasMany.js","../src/Relation/HasOne.js","../src/relations.js","../src/decorators.js","../src/Record.js","../lib/mindex/_utils.js","../lib/mindex/index.js","../src/Collection.js","../src/Schema.js","../src/Mapper.js","../src/Container.js","../src/SimpleStore.js","../src/LinkedCollection.js","../src/DataStore.js","../src/index.js"],"sourcesContent":["/**\n * Utility methods used by JSData.\n *\n * @example\n * import { utils } from 'js-data';\n * console.log(utils.isString('foo')); // true\n *\n * @namespace utils\n * @type {Object}\n */\n\nconst DOMAIN = 'utils'\n\nconst INFINITY = 1 / 0\nconst MAX_INTEGER = 1.7976931348623157e+308\nconst BOOL_TAG = '[object Boolean]'\nconst DATE_TAG = '[object Date]'\nconst FUNC_TAG = '[object Function]'\nconst NUMBER_TAG = '[object Number]'\nconst OBJECT_TAG = '[object Object]'\nconst REGEXP_TAG = '[object RegExp]'\nconst STRING_TAG = '[object String]'\nconst objToString = Object.prototype.toString\nconst PATH = /^(.+)\\.(.+)$/\n\nconst ERRORS = {\n '400' () { return `expected: ${arguments[0]}, found: ${arguments[2] ? arguments[1] : typeof arguments[1]}` },\n '404' () { return `${arguments[0]} not found` }\n}\n\nconst toInteger = function (value) {\n if (!value) {\n return 0\n }\n // Coerce to number\n value = +value\n if (value === INFINITY || value === -INFINITY) {\n const sign = (value < 0 ? -1 : 1)\n return sign * MAX_INTEGER\n }\n const remainder = value % 1\n return value === value ? (remainder ? value - remainder : value) : 0 // eslint-disable-line\n}\n\nconst toStr = function (value) {\n return objToString.call(value)\n}\n\nconst isPlainObject = function (value) {\n return (!!value && typeof value === 'object' && value.constructor === Object)\n}\n\nconst mkdirP = function (object, path) {\n if (!path) {\n return object\n }\n const parts = path.split('.')\n parts.forEach(function (key) {\n if (!object[key]) {\n object[key] = {}\n }\n object = object[key]\n })\n return object\n}\n\nconst utils = {\n /**\n * Reference to the Promise constructor used by JSData. Defaults to\n * `window.Promise` or `global.Promise`.\n *\n * @example Make JSData use a different `Promise` constructor\n * import Promise from 'bluebird';\n * import { utils } from 'js-data';\n * utils.Promise = Promise;\n *\n * @name utils.Promise\n * @since 3.0.0\n * @type {Function}\n */\n Promise: Promise,\n\n /**\n * Shallow copy properties that meet the following criteria from `src` to\n * `dest`:\n *\n * - own enumerable\n * - not a function\n * - does not start with \"_\"\n *\n * @method utils._\n * @param {object} dest Destination object.\n * @param {object} src Source object.\n * @private\n * @since 3.0.0\n */\n _ (dest, src) {\n utils.forOwn(src, function (value, key) {\n if (key && dest[key] === undefined && !utils.isFunction(value) && key.indexOf('_') !== 0) {\n dest[key] = value\n }\n })\n },\n\n /**\n * Recursively iterates over relations found in `opts.with`.\n *\n * @method utils._forRelation\n * @param {object} opts Configuration options.\n * @param {Relation} def Relation definition.\n * @param {Function} fn Callback function.\n * @param {*} [thisArg] Execution context for the callback function.\n * @private\n * @since 3.0.0\n */\n _forRelation (opts, def, fn, thisArg) {\n const relationName = def.relation\n let containedName = null\n let index\n opts || (opts = {})\n opts.with || (opts.with = [])\n\n if ((index = utils._getIndex(opts.with, relationName)) >= 0) {\n containedName = relationName\n } else if ((index = utils._getIndex(opts.with, def.localField)) >= 0) {\n containedName = def.localField\n }\n\n if (opts.withAll) {\n fn.call(thisArg, def, {})\n return\n } else if (!containedName) {\n return\n }\n let optsCopy = {}\n utils.fillIn(optsCopy, def.getRelation())\n utils.fillIn(optsCopy, opts)\n optsCopy.with = opts.with.slice()\n optsCopy._activeWith = optsCopy.with.splice(index, 1)[0]\n optsCopy.with.forEach(function (relation, i) {\n if (relation && relation.indexOf(containedName) === 0 && relation.length >= containedName.length && relation[containedName.length] === '.') {\n optsCopy.with[i] = relation.substr(containedName.length + 1)\n } else {\n optsCopy.with[i] = ''\n }\n })\n fn.call(thisArg, def, optsCopy)\n },\n\n /**\n * Find the index of a relation in the given list\n *\n * @method utils._getIndex\n * @param {string[]} list List to search.\n * @param {string} relation Relation to find.\n * @private\n * @returns {number}\n */\n _getIndex (list, relation) {\n let index = -1\n list.forEach(function (_relation, i) {\n if (_relation === relation) {\n index = i\n return false\n } else if (utils.isObject(_relation)) {\n if (_relation.relation === relation) {\n index = i\n return false\n }\n }\n })\n return index\n },\n\n /**\n * Define hidden (non-enumerable), writable properties on `target` from the\n * provided `props`.\n *\n * @example\n * import { utils } from 'js-data';\n * function Cat () {}\n * utils.addHiddenPropsToTarget(Cat.prototype, {\n * say () {\n * console.log('meow');\n * }\n * });\n * const cat = new Cat();\n * cat.say(); // \"meow\"\n *\n * @method utils.addHiddenPropsToTarget\n * @param {object} target That to which `props` should be added.\n * @param {object} props Properties to be added to `target`.\n * @since 3.0.0\n */\n addHiddenPropsToTarget (target, props) {\n const map = {}\n Object.keys(props).forEach(function (propName) {\n const descriptor = Object.getOwnPropertyDescriptor(props, propName)\n\n descriptor.enumerable = false\n map[propName] = descriptor\n })\n Object.defineProperties(target, map)\n },\n\n /**\n * Return whether the two objects are deeply different.\n *\n * @example\n * import { utils } from 'js-data';\n * utils.areDifferent({}, {}); // false\n * utils.areDifferent({ a: 1 }, { a: 1 }); // false\n * utils.areDifferent({ foo: 'bar' }, {}); // true\n *\n * @method utils.areDifferent\n * @param {object} a Base object.\n * @param {object} b Comparison object.\n * @param {object} [opts] Configuration options.\n * @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function.\n * @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore.\n * @returns {boolean} Whether the two objects are deeply different.\n * @see utils.diffObjects\n * @since 3.0.0\n */\n areDifferent (newObject, oldObject, opts) {\n opts || (opts = {})\n const diff = utils.diffObjects(newObject, oldObject, opts)\n const diffCount = Object.keys(diff.added).length +\n Object.keys(diff.removed).length +\n Object.keys(diff.changed).length\n return diffCount > 0\n },\n\n /**\n * Verified that the given constructor is being invoked via `new`, as opposed\n * to just being called like a normal function.\n *\n * @example\n * import { utils } from 'js-data';\n * function Cat () {\n * utils.classCallCheck(this, Cat);\n * }\n * const cat = new Cat(); // this is ok\n * Cat(); // this throws an error\n *\n * @method utils.classCallCheck\n * @param {*} instance Instance that is being constructed.\n * @param {Constructor} ctor Constructor function used to construct the\n * instance.\n * @since 3.0.0\n * @throws {Error} Throws an error if the constructor is being improperly\n * invoked.\n */\n classCallCheck (instance, ctor) {\n if (!(instance instanceof ctor)) {\n throw utils.err(`${ctor.name}`)(500, 'Cannot call a class as a function')\n }\n },\n\n /**\n * Deep copy a value.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { foo: { bar: 'baz' } };\n * const b = utils.copy(a);\n * a === b; // false\n * utils.areDifferent(a, b); // false\n *\n * @param {*} from Value to deep copy.\n * @param {*} [to] Destination object for the copy operation.\n * @param {*} [stackFrom] For internal use.\n * @param {*} [stackTo] For internal use.\n * @param {string[]|RegExp[]} [blacklist] List of strings or RegExp of\n * properties to skip.\n * @param {boolean} [plain] Whether to make a plain copy (don't try to use\n * original prototype).\n * @returns {*} Deep copy of `from`.\n * @since 3.0.0\n */\n copy (from, to, stackFrom, stackTo, blacklist, plain) {\n if (!to) {\n to = from\n if (from) {\n if (utils.isArray(from)) {\n to = utils.copy(from, [], stackFrom, stackTo, blacklist, plain)\n } else if (utils.isDate(from)) {\n to = new Date(from.getTime())\n } else if (utils.isRegExp(from)) {\n to = new RegExp(from.source, from.toString().match(/[^/]*$/)[0])\n to.lastIndex = from.lastIndex\n } else if (utils.isObject(from)) {\n if (plain) {\n to = utils.copy(from, {}, stackFrom, stackTo, blacklist, plain)\n } else {\n to = utils.copy(from, Object.create(Object.getPrototypeOf(from)), stackFrom, stackTo, blacklist, plain)\n }\n }\n }\n } else {\n if (from === to) {\n throw utils.err(`${DOMAIN}.copy`)(500, 'Cannot copy! Source and destination are identical.')\n }\n\n stackFrom = stackFrom || []\n stackTo = stackTo || []\n\n if (utils.isObject(from)) {\n let index = stackFrom.indexOf(from)\n if (index !== -1) {\n return stackTo[index]\n }\n\n stackFrom.push(from)\n stackTo.push(to)\n }\n\n let result\n if (utils.isArray(from)) {\n let i\n to.length = 0\n for (i = 0; i < from.length; i++) {\n result = utils.copy(from[i], null, stackFrom, stackTo, blacklist, plain)\n if (utils.isObject(from[i])) {\n stackFrom.push(from[i])\n stackTo.push(result)\n }\n to.push(result)\n }\n } else {\n if (utils.isArray(to)) {\n to.length = 0\n } else {\n utils.forOwn(to, function (value, key) {\n delete to[key]\n })\n }\n for (var key in from) {\n if (from.hasOwnProperty(key)) {\n if (utils.isBlacklisted(key, blacklist)) {\n continue\n }\n result = utils.copy(from[key], null, stackFrom, stackTo, blacklist, plain)\n if (utils.isObject(from[key])) {\n stackFrom.push(from[key])\n stackTo.push(result)\n }\n to[key] = result\n }\n }\n }\n }\n return to\n },\n\n /**\n * Recursively shallow fill in own enumerable properties from `source` to\n * `dest`.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { foo: { bar: 'baz' }, beep: 'boop' };\n * const b = { beep: 'bip' };\n * utils.deepFillIn(b, a);\n * console.log(b); // {\"foo\":{\"bar\":\"baz\"},\"beep\":\"bip\"}\n *\n * @method utils.deepFillIn\n * @param {object} dest The destination object.\n * @param {object} source The source object.\n * @see utils.fillIn\n * @see utils.deepMixIn\n * @since 3.0.0\n */\n deepFillIn (dest, source) {\n if (source) {\n utils.forOwn(source, function (value, key) {\n const existing = dest[key]\n if (isPlainObject(value) && isPlainObject(existing)) {\n utils.deepFillIn(existing, value)\n } else if (!dest.hasOwnProperty(key) || dest[key] === undefined) {\n dest[key] = value\n }\n })\n }\n return dest\n },\n\n /**\n * Recursively shallow copy enumerable properties from `source` to `dest`.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { foo: { bar: 'baz' }, beep: 'boop' };\n * const b = { beep: 'bip' };\n * utils.deepFillIn(b, a);\n * console.log(b); // {\"foo\":{\"bar\":\"baz\"},\"beep\":\"boop\"}\n *\n * @method utils.deepMixIn\n * @param {object} dest The destination object.\n * @param {object} source The source object.\n * @see utils.fillIn\n * @see utils.deepFillIn\n * @since 3.0.0\n */\n deepMixIn (dest, source) {\n if (source) {\n for (var key in source) {\n const value = source[key]\n const existing = dest[key]\n if (isPlainObject(value) && isPlainObject(existing)) {\n utils.deepMixIn(existing, value)\n } else {\n dest[key] = value\n }\n }\n }\n return dest\n },\n\n /**\n * Return a diff of the base object to the comparison object.\n *\n * @example\n * import { utils } from 'js-data';\n * const oldObject = { foo: 'bar', a: 1234 };\n * const newObject = { beep: 'boop', a: 5678 };\n * const diff = utils.diffObjects(oldObject, newObject);\n * console.log(diff.added); // {\"beep\":\"boop\"}\n * console.log(diff.changed); // {\"a\":5678}\n * console.log(diff.removed); // {\"foo\":undefined}\n *\n * @method utils.diffObjects\n * @param {object} newObject Comparison object.\n * @param {object} oldObject Base object.\n * @param {object} [opts] Configuration options.\n * @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function.\n * @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore.\n * @returns {Object} The diff from the base object to the comparison object.\n * @see utils.areDifferent\n * @since 3.0.0\n */\n diffObjects (newObject, oldObject, opts) {\n opts || (opts = {})\n let equalsFn = opts.equalsFn\n let blacklist = opts.ignore\n const diff = {\n added: {},\n changed: {},\n removed: {}\n }\n if (!utils.isFunction(equalsFn)) {\n equalsFn = utils.deepEqual\n }\n\n const newKeys = Object.keys(newObject).filter(function (key) {\n return !utils.isBlacklisted(key, blacklist)\n })\n const oldKeys = Object.keys(oldObject).filter(function (key) {\n return !utils.isBlacklisted(key, blacklist)\n })\n\n // Check for properties that were added or changed\n newKeys.forEach(function (key) {\n const oldValue = oldObject[key]\n const newValue = newObject[key]\n if (equalsFn(oldValue, newValue)) {\n return\n }\n if (oldValue === undefined) {\n diff.added[key] = newValue\n } else {\n diff.changed[key] = newValue\n }\n })\n\n // Check for properties that were removed\n oldKeys.forEach(function (key) {\n const oldValue = oldObject[key]\n const newValue = newObject[key]\n if (newValue === undefined && oldValue !== undefined) {\n diff.removed[key] = undefined\n }\n })\n\n return diff\n },\n\n /**\n * Return whether the two values are equal according to the `==` operator.\n *\n * @example\n * import { utils } from 'js-data';\n * console.log(utils.equal(1,1)); // true\n * console.log(utils.equal(1,'1')); // true\n * console.log(utils.equal(93, 66)); // false\n *\n * @method utils.equal\n * @param {*} a First value in the comparison.\n * @param {*} b Second value in the comparison.\n * @returns {boolean} Whether the two values are equal according to `==`.\n * @since 3.0.0\n */\n equal (a, b) {\n return a == b // eslint-disable-line\n },\n\n /**\n * Produce a factory function for making Error objects with the provided\n * metadata. Used throughout the various js-data components.\n *\n * @example\n * import { utils } from 'js-data';\n * const errorFactory = utils.err('domain', 'target');\n * const error400 = errorFactory(400, 'expected type', 'actual type');\n * console.log(error400); // [Error: [domain:target] expected: expected type, found: string\nhttp://www.js-data.io/v3.0/docs/errors#400]\n * @method utils.err\n * @param {string} domain Namespace.\n * @param {string} target Target.\n * @returns {Function} Factory function.\n * @since 3.0.0\n */\n err (domain, target) {\n return function (code) {\n const prefix = `[${domain}:${target}] `\n let message = ERRORS[code].apply(null, Array.prototype.slice.call(arguments, 1))\n message = `${prefix}${message}\nhttp://www.js-data.io/v3.0/docs/errors#${code}`\n return new Error(message)\n }\n },\n\n /**\n * Add eventing capabilities into the target object.\n *\n * @example\n * import { utils } from 'js-data';\n * const user = { name: 'John' };\n * utils.eventify(user);\n * user.on('foo', () => console.log(arguments));\n * user.emit('foo', 1, 'bar'); // should log to console values (1, \"bar\")\n *\n * @method utils.eventify\n * @param {object} target Target object.\n * @param {Function} [getter] Custom getter for retrieving the object's event\n * listeners.\n * @param {Function} [setter] Custom setter for setting the object's event\n * listeners.\n * @since 3.0.0\n */\n eventify (target, getter, setter) {\n target = target || this\n let _events = {}\n if (!getter && !setter) {\n getter = function () { return _events }\n setter = function (value) { _events = value }\n }\n Object.defineProperties(target, {\n emit: {\n value (...args) {\n const events = getter.call(this) || {}\n const type = args.shift()\n let listeners = events[type] || []\n let i\n for (i = 0; i < listeners.length; i++) {\n listeners[i].f.apply(listeners[i].c, args)\n }\n listeners = events.all || []\n args.unshift(type)\n for (i = 0; i < listeners.length; i++) {\n listeners[i].f.apply(listeners[i].c, args)\n }\n }\n },\n off: {\n value (type, func) {\n const events = getter.call(this)\n const listeners = events[type]\n if (!listeners) {\n setter.call(this, {})\n } else if (func) {\n for (let i = 0; i < listeners.length; i++) {\n if (listeners[i].f === func) {\n listeners.splice(i, 1)\n break\n }\n }\n } else {\n listeners.splice(0, listeners.length)\n }\n }\n },\n on: {\n value (type, func, thisArg) {\n if (!getter.call(this)) {\n setter.call(this, {})\n }\n const events = getter.call(this)\n events[type] = events[type] || []\n events[type].push({\n c: thisArg,\n f: func\n })\n }\n }\n })\n },\n\n /**\n * Used for sublcassing. Invoke this method in the context of a superclass to\n * to produce a subclass based on `props` and `classProps`.\n *\n * @example\n * import { utils } from 'js-data';\n * function Animal () {}\n * Animal.extend = utils.extend;\n * const Cat = Animal.extend({\n * say () {\n * console.log('meow');\n * }\n * });\n * const cat = new Cat();\n * cat instanceof Animal; // true\n * cat instanceof Cat; // true\n * cat.say(); // \"meow\"\n *\n * @method utils.extend\n * @param {object} props Instance properties for the subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to use as the subclass.\n * @param {object} props Static properties for the subclass.\n * @returns {Constructor} A new subclass.\n * @since 3.0.0\n */\n extend (props, classProps) {\n const superClass = this\n let subClass\n\n props || (props = {})\n classProps || (classProps = {})\n\n if (props.hasOwnProperty('constructor')) {\n subClass = props.constructor\n delete props.constructor\n } else {\n subClass = function (...args) {\n utils.classCallCheck(this, subClass)\n superClass.apply(this, args)\n }\n }\n\n // Setup inheritance of instance members\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n configurable: true,\n enumerable: false,\n value: subClass,\n writable: true\n }\n })\n\n const obj = Object\n // Setup inheritance of static members\n if (obj.setPrototypeOf) {\n obj.setPrototypeOf(subClass, superClass)\n } else if (classProps.strictEs6Class) {\n subClass.__proto__ = superClass // eslint-disable-line\n } else {\n utils.forOwn(superClass, function (value, key) {\n subClass[key] = value\n })\n }\n if (!subClass.hasOwnProperty('__super__')) {\n Object.defineProperty(subClass, '__super__', {\n configurable: true,\n value: superClass\n })\n }\n\n utils.addHiddenPropsToTarget(subClass.prototype, props)\n utils.fillIn(subClass, classProps)\n\n return subClass\n },\n\n /**\n * Shallow copy own enumerable properties from `src` to `dest` that are on\n * `src` but are missing from `dest.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { foo: 'bar', beep: 'boop' };\n * const b = { beep: 'bip' };\n * utils.fillIn(b, a);\n * console.log(b); // {\"foo\":\"bar\",\"beep\":\"bip\"}\n *\n * @method utils.fillIn\n * @param {object} dest The destination object.\n * @param {object} source The source object.\n * @see utils.deepFillIn\n * @see utils.deepMixIn\n * @since 3.0.0\n */\n fillIn (dest, src) {\n utils.forOwn(src, function (value, key) {\n if (!dest.hasOwnProperty(key) || dest[key] === undefined) {\n dest[key] = value\n }\n })\n },\n\n /**\n * Find the last index of an item in an array according to the given checker function.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * const john = { name: 'John', age: 20 };\n * const sara = { name: 'Sara', age: 25 };\n * const dan = { name: 'Dan', age: 20 };\n * const users = [john, sara, dan];\n *\n * console.log(utils.findIndex(users, (user) => user.age === 25)); // 1\n * console.log(utils.findIndex(users, (user) => user.age > 19)); // 2\n * console.log(utils.findIndex(users, (user) => user.name === 'John')); // 0\n * console.log(utils.findIndex(users, (user) => user.name === 'Jimmy')); // -1\n *\n * @method utils.findIndex\n * @param {array} array The array to search.\n * @param {Function} fn Checker function.\n * @returns {number} Index if found or -1 if not found.\n * @since 3.0.0\n */\n findIndex (array, fn) {\n let index = -1\n if (!array) {\n return index\n }\n array.forEach(function (record, i) {\n if (fn(record)) {\n index = i\n return false\n }\n })\n return index\n },\n\n /**\n * Recursively iterate over a {@link Mapper}'s relations according to\n * `opts.with`.\n *\n * @method utils.forEachRelation\n * @param {Mapper} mapper Mapper.\n * @param {object} opts Configuration options.\n * @param {Function} fn Callback function.\n * @param {*} thisArg Execution context for the callback function.\n * @since 3.0.0\n */\n forEachRelation (mapper, opts, fn, thisArg) {\n const relationList = mapper.relationList || []\n if (!relationList.length) {\n return\n }\n relationList.forEach(function (def) {\n utils._forRelation(opts, def, fn, thisArg)\n })\n },\n\n /**\n * Iterate over an object's own enumerable properties.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { b: 1, c: 4 };\n * let sum = 0;\n * utils.forOwn(a, function (value, key) {\n * sum += value;\n * });\n * console.log(sum); // 5\n *\n * @method utils.forOwn\n * @param {object} object The object whose properties are to be enumerated.\n * @param {Function} fn Iteration function.\n * @param {object} [thisArg] Content to which to bind `fn`.\n * @since 3.0.0\n */\n forOwn (obj, fn, thisArg) {\n const keys = Object.keys(obj)\n const len = keys.length\n let i\n for (i = 0; i < len; i++) {\n if (fn.call(thisArg, obj[keys[i]], keys[i], obj) === false) {\n break\n }\n }\n },\n\n /**\n * Proxy for `JSON.parse`.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * const a = utils.fromJson('{\"name\" : \"John\"}');\n * console.log(a); // { name: 'John' }\n *\n * @method utils.fromJson\n * @param {string} json JSON to parse.\n * @returns {Object} Parsed object.\n * @see utils.toJson\n * @since 3.0.0\n */\n fromJson (json) {\n return utils.isString(json) ? JSON.parse(json) : json\n },\n\n /**\n * Retrieve the specified property from the given object. Supports retrieving\n * nested properties.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { foo: { bar: 'baz' }, beep: 'boop' };\n * console.log(utils.get(a, 'beep')); // \"boop\"\n * console.log(utils.get(a, 'foo.bar')); // \"baz\"\n *\n * @method utils.get\n * @param {object} object Object from which to retrieve a property's value.\n * @param {string} prop Property to retrieve.\n * @returns {*} Value of the specified property.\n * @see utils.set\n * @since 3.0.0\n */\n 'get': function (object, prop) {\n if (!prop) {\n return\n }\n const parts = prop.split('.')\n const last = parts.pop()\n\n while (prop = parts.shift()) { // eslint-disable-line\n object = object[prop]\n if (object == null) { // eslint-disable-line\n return\n }\n }\n\n return object[last]\n },\n\n /**\n * Return the superclass for the given instance or subclass. If an instance is\n * provided, then finds the parent class of the instance's constructor.\n *\n * @example\n * import { utils } from 'js-data';\n * // using ES2015 classes\n * class Foo {}\n * class Bar extends Foo {}\n * const barInstance = new Bar();\n * let baseType = utils.getSuper(barInstance);\n * console.log(Foo === baseType); // true\n *\n * // using Function constructor with utils.extend\n * function Foo () {}\n * Foo.extend = utils.extend;\n * const Bar = Foo.extend();\n * const barInstance = new Bar();\n * let baseType = utils.getSuper(barInstance);\n * console.log(Foo === baseType); // true\n *\n * @method utils.getSuper\n * @param {Object|Function} instance Instance or constructor.\n * @param {boolean} [isCtor=false] Whether `instance` is a constructor.\n * @returns {Constructor} The superclass (grandparent constructor).\n * @since 3.0.0\n */\n getSuper (instance, isCtor) {\n const ctor = isCtor ? instance : instance.constructor\n if (ctor.hasOwnProperty('__super__')) {\n return ctor.__super__\n }\n return Object.getPrototypeOf(ctor) || ctor.__proto__ // eslint-disable-line\n },\n\n /**\n * Return the intersection of two arrays.\n *\n * @example\n * import { utils } from 'js-data';\n * const arrA = ['green', 'red', 'blue', 'red'];\n * const arrB = ['green', 'yellow', 'red'];\n * const intersected = utils.intersection(arrA, arrB);\n *\n * console.log(intersected); // ['green', 'red'])\n *\n * @method utils.intersection\n * @param {array} array1 First array.\n * @param {array} array2 Second array.\n * @returns {Array} Array of elements common to both arrays.\n * @since 3.0.0\n */\n intersection (array1, array2) {\n if (!array1 || !array2) {\n return []\n }\n const result = []\n let item\n let i\n const len = array1.length\n for (i = 0; i < len; i++) {\n item = array1[i]\n if (result.indexOf(item) !== -1) {\n continue\n }\n if (array2.indexOf(item) !== -1) {\n result.push(item)\n }\n }\n return result\n },\n\n /**\n * Proxy for `Array.isArray`.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = [1,2,3,4,5];\n * const b = { foo: \"bar\" };\n * console.log(utils.isArray(a)); // true\n * console.log(utils.isArray(b)); // false\n *\n * @method utils.isArray\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is an array.\n * @since 3.0.0\n */\n isArray: Array.isArray,\n\n /**\n * Return whether `prop` is matched by any string or regular expression in\n * `blacklist`.\n *\n * @example\n * import { utils } from 'js-data';\n * const blacklist = [/^\\$hashKey/g, /^_/g, 'id'];\n * console.log(utils.isBlacklisted(\"$hashKey\", blacklist)); // true\n * console.log(utils.isBlacklisted(\"id\", blacklist)); // true\n * console.log(utils.isBlacklisted(\"_myProp\", blacklist)); // true\n * console.log(utils.isBlacklisted(\"my_id\", blacklist)); // false\n *\n * @method utils.isBlacklisted\n * @param {string} prop The name of a property to check.\n * @param {array} blacklist Array of strings and regular expressions.\n * @returns {boolean} Whether `prop` was matched.\n * @since 3.0.0\n */\n isBlacklisted (prop, blacklist) {\n if (!blacklist || !blacklist.length) {\n return false\n }\n let matches\n for (var i = 0; i < blacklist.length; i++) {\n if ((toStr(blacklist[i]) === REGEXP_TAG && blacklist[i].test(prop)) || blacklist[i] === prop) {\n matches = prop\n return !!matches\n }\n }\n return !!matches\n },\n\n /**\n * Return whether the provided value is a boolean.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = true;\n * const b = { foo: \"bar\" };\n * console.log(utils.isBoolean(a)); // true\n * console.log(utils.isBoolean(b)); // false\n *\n * @method utils.isBoolean\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is a boolean.\n * @since 3.0.0\n */\n isBoolean (value) {\n return toStr(value) === BOOL_TAG\n },\n\n /**\n * Return whether the provided value is a date.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = new Date();\n * const b = { foo: \"bar\" };\n * console.log(utils.isDate(a)); // true\n * console.log(utils.isDate(b)); // false\n *\n * @method utils.isDate\n * @param {*} value The value to test.\n * @returns {Date} Whether the provided value is a date.\n * @since 3.0.0\n */\n isDate (value) {\n return (value && typeof value === 'object' && toStr(value) === DATE_TAG)\n },\n\n /**\n * Return whether the provided value is a function.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = function () { console.log('foo bar'); };\n * const b = { foo: \"bar\" };\n * console.log(utils.isFunction(a)); // true\n * console.log(utils.isFunction(b)); // false\n *\n * @method utils.isFunction\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is a function.\n * @since 3.0.0\n */\n isFunction (value) {\n return typeof value === 'function' || (value && toStr(value) === FUNC_TAG)\n },\n\n /**\n * Return whether the provided value is an integer.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = 1;\n * const b = 1.25;\n * const c = '1';\n * console.log(utils.isInteger(a)); // true\n * console.log(utils.isInteger(b)); // false\n * console.log(utils.isInteger(c)); // false\n *\n * @method utils.isInteger\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is an integer.\n * @since 3.0.0\n */\n isInteger (value) {\n return toStr(value) === NUMBER_TAG && value == toInteger(value) // eslint-disable-line\n },\n\n /**\n * Return whether the provided value is `null`.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = null;\n * const b = { foo: \"bar\" };\n * console.log(utils.isNull(a)); // true\n * console.log(utils.isNull(b)); // false\n *\n * @method utils.isNull\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is `null`.\n * @since 3.0.0\n */\n isNull (value) {\n return value === null\n },\n\n /**\n * Return whether the provided value is a number.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = 1;\n * const b = -1.25;\n * const c = '1';\n * console.log(utils.isNumber(a)); // true\n * console.log(utils.isNumber(b)); // true\n * console.log(utils.isNumber(c)); // false\n *\n * @method utils.isNumber\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is a number.\n * @since 3.0.0\n */\n isNumber (value) {\n const type = typeof value\n return type === 'number' || (value && type === 'object' && toStr(value) === NUMBER_TAG)\n },\n\n /**\n * Return whether the provided value is an object.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { foo: \"bar\" };\n * const b = 'foo bar';\n * console.log(utils.isObject(a)); // true\n * console.log(utils.isObject(b)); // false\n *\n * @method utils.isObject\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is an object.\n * @since 3.0.0\n */\n isObject (value) {\n return toStr(value) === OBJECT_TAG\n },\n\n /**\n * Return whether the provided value is a regular expression.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = /^\\$.+$/ig;\n * const b = new RegExp('^\\$.+$', 'ig');\n * const c = { foo: \"bar\" };\n * console.log(utils.isRegExp(a)); // true\n * console.log(utils.isRegExp(b)); // true\n * console.log(utils.isRegExp(c)); // false\n *\n * @method utils.isRegExp\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is a regular expression.\n * @since 3.0.0\n */\n isRegExp (value) {\n return toStr(value) === REGEXP_TAG\n },\n\n /**\n * Return whether the provided value is a string or a number.\n *\n * @example\n * import { utils } from 'js-data';\n * console.log(utils.isSorN('')); // true\n * console.log(utils.isSorN(-1.65)); // true\n * console.log(utils.isSorN('my string')); // true\n * console.log(utils.isSorN({})); // false\n * console.log(utils.isSorN([1,2,4])); // false\n *\n * @method utils.isSorN\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is a string or a number.\n * @since 3.0.0\n */\n isSorN (value) {\n return utils.isString(value) || utils.isNumber(value)\n },\n\n /**\n * Return whether the provided value is a string.\n *\n * @example\n * import { utils } from 'js-data';\n * console.log(utils.isString('')); // true\n * console.log(utils.isString('my string')); // true\n * console.log(utils.isString(100)); // false\n * console.log(utils.isString([1,2,4])); // false\n *\n * @method utils.isString\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is a string.\n * @since 3.0.0\n */\n isString (value) {\n return typeof value === 'string' || (value && typeof value === 'object' && toStr(value) === STRING_TAG)\n },\n\n /**\n * Return whether the provided value is a `undefined`.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = undefined;\n * const b = { foo: \"bar\"};\n * console.log(utils.isUndefined(a)); // true\n * console.log(utils.isUndefined(b.baz)); // true\n * console.log(utils.isUndefined(b)); // false\n * console.log(utils.isUndefined(b.foo)); // false\n *\n * @method utils.isUndefined\n * @param {*} value The value to test.\n * @returns {boolean} Whether the provided value is a `undefined`.\n * @since 3.0.0\n */\n isUndefined (value) {\n return value === undefined\n },\n\n /**\n * Mix in logging capabilities to the target.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { foo: \"bar\"};\n *\n * // Add standard logging to an object\n * utils.logify(a);\n * a.log('info', 'test log info'); // output 'test log info' to console.\n *\n * // Toggle debug output of an object\n * a.dbg('test debug output'); // does not output because debug is off.\n * a.debug = true;\n * a.dbg('test debug output'); // output 'test debug output' to console.\n *\n * @method utils.logify\n * @param {*} target The target.\n * @since 3.0.0\n */\n logify (target) {\n utils.addHiddenPropsToTarget(target, {\n dbg (...args) {\n if (utils.isFunction(this.log)) {\n this.log('debug', ...args)\n }\n },\n log (level, ...args) {\n if (level && !args.length) {\n args.push(level)\n level = 'debug'\n }\n if (level === 'debug' && !this.debug) {\n return\n }\n const prefix = `${level.toUpperCase()}: (${this.name || this.constructor.name})`\n if (utils.isFunction(console[level])) {\n console[level](prefix, ...args)\n } else {\n console.log(prefix, ...args)\n }\n }\n })\n },\n\n /**\n * Adds the given record to the provided array only if it's not already in the\n * array.\n *\n * @example\n * import { utils } from 'js-data';\n * const colors = ['red', 'green', 'yellow'];\n *\n * console.log(colors.length); // 3\n * utils.noDupeAdd(colors, 'red');\n * console.log(colors.length); // 3, red already exists\n *\n * utils.noDupeAdd(colors, 'blue');\n * console.log(colors.length); // 4, blue was added\n *\n * @method utils.noDupeAdd\n * @param {array} array The array.\n * @param {*} record The value to add.\n * @param {Function} fn Callback function passed to {@link utils.findIndex}.\n * @since 3.0.0\n */\n noDupeAdd (array, record, fn) {\n if (!array) {\n return\n }\n const index = this.findIndex(array, fn)\n if (index < 0) {\n array.push(record)\n }\n },\n\n /**\n * Return a shallow copy of the provided object, minus the properties\n * specified in `keys`.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { name: 'John', $hashKey: 1214910 };\n *\n * let b = utils.omit(a, ['$hashKey']);\n * console.log(b); // { name: 'John' }\n *\n * @method utils.omit\n * @param {object} props The object to copy.\n * @param {string[]} keys Array of strings, representing properties to skip.\n * @returns {Object} Shallow copy of `props`, minus `keys`.\n * @since 3.0.0\n */\n omit (props, keys) {\n const _props = {}\n utils.forOwn(props, function (value, key) {\n if (keys.indexOf(key) === -1) {\n _props[key] = value\n }\n })\n return _props\n },\n\n /**\n * Return a shallow copy of the provided object, but only include the\n * properties specified in `keys`.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { name: 'John', $hashKey: 1214910 };\n *\n * let b = utils.pick(a, ['$hashKey']);\n * console.log(b); // { $hashKey: 1214910 }\n *\n * @method utils.pick\n * @param {object} props The object to copy.\n * @param {string[]} keys Array of strings, representing properties to keep.\n * @returns {Object} Shallow copy of `props`, but only including `keys`.\n * @since 3.0.0\n */\n pick (props, keys) {\n return keys.reduce((map, key) => {\n map[key] = props[key]\n return map\n }, {})\n },\n\n /**\n * Return a plain copy of the given value.\n *\n * @example\n * import { utils } from 'js-data';\n * const a = { name: 'John' };\n * let b = utils.plainCopy(a);\n * console.log(a === b); // false\n *\n * @method utils.plainCopy\n * @param {*} value The value to copy.\n * @returns {*} Plain copy of `value`.\n * @see utils.copy\n * @since 3.0.0\n */\n plainCopy (value) {\n return utils.copy(value, undefined, undefined, undefined, undefined, true)\n },\n\n /**\n * Shortcut for `utils.Promise.reject(value)`.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * utils.reject(\"Testing static reject\").then(function (data) {\n * // not called\n * }).catch(function (reason) {\n * console.log(reason); // \"Testing static reject\"\n * });\n *\n * @method utils.reject\n * @param {*} [value] Value with which to reject the Promise.\n * @returns {Promise} Promise reject with `value`.\n * @see utils.Promise\n * @since 3.0.0\n */\n reject (value) {\n return utils.Promise.reject(value)\n },\n\n /**\n * Remove the last item found in array according to the given checker function.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * const colors = ['red', 'green', 'yellow', 'red'];\n * utils.remove(colors, (color) => color === 'red');\n * console.log(colors); // ['red', 'green', 'yellow']\n *\n * @method utils.remove\n * @param {array} array The array to search.\n * @param {Function} fn Checker function.\n */\n remove (array, fn) {\n if (!array || !array.length) {\n return\n }\n const index = this.findIndex(array, fn)\n if (index >= 0) {\n array.splice(index, 1) // todo should this be recursive?\n }\n },\n\n /**\n * Shortcut for `utils.Promise.resolve(value)`.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * utils.resolve(\"Testing static resolve\").then(function (data) {\n * console.log(data); // \"Testing static resolve\"\n * }).catch(function (reason) {\n * // not called\n * });\n *\n * @param {*} [value] Value with which to resolve the Promise.\n * @returns {Promise} Promise resolved with `value`.\n * @see utils.Promise\n * @since 3.0.0\n */\n resolve (value) {\n return utils.Promise.resolve(value)\n },\n\n /**\n * Set the value at the provided key or path.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * const john = {\n * name: 'John',\n * age: 25,\n * parent: {\n * name: 'John's Mom',\n * age: 50\n * }\n * };\n * // set value by key\n * utils.set(john, 'id', 98);\n * console.log(john.id); // 98\n *\n * // set value by path\n * utils.set(john, 'parent.id', 20);\n * console.log(john.parent.id); // 20\n *\n * // set value by path/value map\n * utils.set(john, {\n * 'id': 1098,\n * 'parent': { id: 1020 },\n * 'parent.age': '55'\n * });\n * console.log(john.id); // 1098\n * console.log(john.parent.id); // 1020\n * console.log(john.parent.age); // 55\n *\n * @method utils.set\n * @param {object} object The object on which to set a property.\n * @param {(string|Object)} path The key or path to the property. Can also\n * pass in an object of path/value pairs, which will all be set on the target\n * object.\n * @param {*} [value] The value to set.\n */\n set: function (object, path, value) {\n if (utils.isObject(path)) {\n utils.forOwn(path, function (value, _path) {\n utils.set(object, _path, value)\n })\n } else {\n const parts = PATH.exec(path)\n if (parts) {\n mkdirP(object, parts[1])[parts[2]] = value\n } else {\n object[path] = value\n }\n }\n },\n\n /**\n * Check whether the two provided objects are deeply equal.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * const objA = {\n * name: 'John',\n * id: 27,\n * nested: {\n * item: 'item 1',\n * colors: ['red', 'green', 'blue']\n * }\n * };\n *\n * const objB = {\n * name: 'John',\n * id: 27,\n * nested: {\n * item: 'item 1',\n * colors: ['red', 'green', 'blue']\n * }\n * };\n *\n * console.log(utils.deepEqual(a,b)); // true\n * objB.nested.colors.add('yellow'); // make a change to a nested object's array\n * console.log(utils.deepEqual(a,b)); // false\n *\n * @method utils.deepEqual\n * @param {object} a First object in the comparison.\n * @param {object} b Second object in the comparison.\n * @returns {boolean} Whether the two provided objects are deeply equal.\n * @see utils.equal\n * @since 3.0.0\n */\n deepEqual (a, b) {\n if (a === b) {\n return true\n }\n let _equal = true\n if (utils.isArray(a) && utils.isArray(b)) {\n if (a.length !== b.length) {\n return false\n }\n for (let i = a.length; i--;) {\n if (!utils.deepEqual(a[i], b[i])) {\n // Exit loop early\n return false\n }\n }\n } else if (utils.isObject(a) && utils.isObject(b)) {\n utils.forOwn(a, function (value, key) {\n if (!(_equal = utils.deepEqual(value, b[key]))) {\n // Exit loop early\n return false\n }\n })\n if (_equal) {\n utils.forOwn(b, function (value, key) {\n if (!(_equal = utils.deepEqual(value, a[key]))) {\n // Exit loop early\n return false\n }\n })\n }\n } else {\n return false\n }\n return _equal\n },\n\n /**\n * Proxy for `JSON.stringify`.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * const a = { name: 'John' };\n * let jsonVal = utils.toJson(a);\n * console.log(jsonVal); // '{\"name\" : \"John\"}'\n *\n * @method utils.toJson\n * @param {*} value Value to serialize to JSON.\n * @returns {string} JSON string.\n * @see utils.fromJson\n * @since 3.0.0\n */\n toJson: JSON.stringify,\n\n /**\n * Unset the value at the provided key or path.\n *\n * @example\n * import { utils } from 'js-data';\n *\n * const john = {\n * name: 'John',\n * age: 25,\n * parent: {\n * name: 'John's Mom',\n * age: 50\n * }\n * };\n *\n * utils.unset(john, age);\n * utils.unset(john, parent.age);\n *\n * console.log(john.age); // null\n * console.log(john.parent.age); // null\n *\n * @method utils.unset\n * @param {object} object The object from which to delete the property.\n * @param {string} path The key or path to the property.\n * @see utils.set\n * @since 3.0.0\n */\n unset (object, path) {\n const parts = path.split('.')\n const last = parts.pop()\n\n while (path = parts.shift()) { // eslint-disable-line\n object = object[path]\n if (object == null) { // eslint-disable-line\n return\n }\n }\n\n object[last] = undefined\n }\n}\n\nexport const safeSetProp = function (record, field, value) {\n if (record && record._set) {\n record._set(`props.${field}`, value)\n } else {\n utils.set(record, field, value)\n }\n}\n\nexport const safeSetLink = function (record, field, value) {\n if (record && record._set) {\n record._set(`links.${field}`, value)\n } else {\n utils.set(record, field, value)\n }\n}\n\nexport default utils\n","import utils from './utils'\n\n/**\n * A base class which gives instances private properties.\n *\n * Typically you won't instantiate this class directly, but you may find it\n * useful as an abstract class for your own components.\n *\n * See {@link Settable.extend} for an example of using {@link Settable} as a\n * base class.\n *\n *```javascript\n * import {Settable} from 'js-data'\n * ```\n *\n * @class Settable\n * @returns {Settable} A new {@link Settable} instance.\n * @since 3.0.0\n */\nexport default function Settable () {\n const _props = {}\n Object.defineProperties(this, {\n /**\n * Get a private property of this instance.\n *\n * __Don't use the method unless you know what you're doing.__\n *\n * @method Settable#_get\n * @param {string} key The property to retrieve.\n * @returns {*} The value of the property.\n * @since 3.0.0\n */\n _get: { value (key) { return utils.get(_props, key) } },\n\n /**\n * Set a private property of this instance.\n *\n * __Don't use the method unless you know what you're doing.__\n *\n * @method __Don't use the method unless you know what you're doing.__#_set\n * @param {(string|Object)} key The key or path to the property. Can also\n * pass in an object of key/value pairs, which will all be set on the instance.\n * @param {*} [value] The value to set.\n * @since 3.0.0\n */\n _set: { value (key, value) { return utils.set(_props, key, value) } },\n\n /**\n * Unset a private property of this instance.\n *\n * __Don't use the method unless you know what you're doing.__\n *\n * @method __Don't use the method unless you know what you're doing.__#_unset\n * @param {string} key The property to unset.\n * @since 3.0.0\n */\n _unset: { value (key) { return utils.unset(_props, key) } }\n })\n}\n\n/**\n * Create a subclass of this Settable:\n *\n * @example Settable.extend\n * const JSData = require('js-data');\n * const { Settable } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomSettableClass extends Settable {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customSettable = new CustomSettableClass();\n * console.log(customSettable.foo());\n * console.log(CustomSettableClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherSettableClass = Settable.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherSettable = new OtherSettableClass();\n * console.log(otherSettable.foo());\n * console.log(OtherSettableClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherSettableClass () {\n * Settable.call(this);\n * this.created_at = new Date().getTime();\n * }\n * Settable.extend({\n * constructor: AnotherSettableClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * })\n * const anotherSettable = new AnotherSettableClass();\n * console.log(anotherSettable.created_at);\n * console.log(anotherSettable.foo());\n * console.log(AnotherSettableClass.beep());\n *\n * @method Settable.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this Settable class.\n * @since 3.0.0\n */\nSettable.extend = utils.extend\n","import utils from './utils'\nimport Settable from './Settable'\n\n/**\n * The base class from which all JSData components inherit some basic\n * functionality.\n *\n * Typically you won't instantiate this class directly, but you may find it\n * useful as an abstract class for your own components.\n *\n * See {@link Component.extend} for an example of using {@link Component} as a\n * base class.\n *\n *```javascript\n * import {Component} from 'js-data'\n * ```\n *\n * @class Component\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.debug=false] See {@link Component#debug}.\n * @returns {Component} A new {@link Component} instance.\n * @since 3.0.0\n */\nfunction Component (opts) {\n Settable.call(this)\n opts || (opts = {})\n\n /**\n * Whether to enable debug-level logs for this component. Anything that\n * extends `Component` inherits this option and the corresponding logging\n * functionality.\n *\n * @example Component#debug\n * const JSData = require('js-data');\n * const { Component } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const component = new Component();\n * component.log('debug', 'some message'); // nothing gets logged\n * // Display debug logs:\n * component.debug = true;\n * component.log('debug', 'other message'); // this DOES get logged\n *\n * @default false\n * @name Component#debug\n * @since 3.0.0\n * @type {boolean}\n */\n this.debug = opts.hasOwnProperty('debug') ? !!opts.debug : false\n\n /**\n * Event listeners attached to this Component. __Do not modify.__ Use\n * {@link Component#on} and {@link Component#off} instead.\n *\n * @name Component#_listeners\n * @private\n * @instance\n * @since 3.0.0\n * @type {Object}\n */\n Object.defineProperty(this, '_listeners', { value: {}, writable: true })\n}\n\nexport default Settable.extend({\n constructor: Component\n})\n\n/**\n * Create a subclass of this Component:\n *\n * @example Component.extend\n * const JSData = require('js-data');\n * const { Component } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomComponentClass extends Component {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customComponent = new CustomComponentClass();\n * console.log(customComponent.foo());\n * console.log(CustomComponentClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherComponentClass = Component.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherComponent = new OtherComponentClass();\n * console.log(otherComponent.foo());\n * console.log(OtherComponentClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherComponentClass () {\n * Component.call(this);\n * this.created_at = new Date().getTime();\n * }\n * Component.extend({\n * constructor: AnotherComponentClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * })\n * const anotherComponent = new AnotherComponentClass();\n * console.log(anotherComponent.created_at);\n * console.log(anotherComponent.foo());\n * console.log(AnotherComponentClass.beep());\n *\n * @method Component.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this Component class.\n * @since 3.0.0\n */\nComponent.extend = utils.extend\n\n/**\n * Log the provided values at the \"debug\" level. Debug-level logs are only\n * logged if {@link Component#debug} is `true`.\n *\n * `.dbg(...)` is shorthand for `.log('debug', ...)`.\n *\n * @method Component#dbg\n * @param {...*} [args] Values to log.\n * @since 3.0.0\n */\n/**\n * Log the provided values. By default sends values to `console[level]`.\n * Debug-level logs are only logged if {@link Component#debug} is `true`.\n *\n * Will attempt to use appropriate `console` methods if they are available.\n *\n * @method Component#log\n * @param {string} level Log level.\n * @param {...*} [args] Values to log.\n * @since 3.0.0\n */\nutils.logify(Component.prototype)\n\n/**\n * Register a new event listener on this Component.\n *\n * @example\n * // Listen for all \"afterCreate\" events in a DataStore\n * store.on('afterCreate', (mapperName, props, opts, result) => {\n * console.log(mapperName); // \"post\"\n * console.log(props.id); // undefined\n * console.log(result.id); // 1234\n * });\n * store.create('post', { title: 'Modeling your data' }).then((post) => {\n * console.log(post.id); // 1234\n * });\n *\n * @example\n * // Listen for the \"add\" event on a collection\n * collection.on('add', (records) => {\n * console.log(records); // [...]\n * });\n *\n * @example\n * // Listen for \"change\" events on a record\n * post.on('change', (record, changes) => {\n * console.log(changes); // { changed: { title: 'Modeling your data' } }\n * });\n * post.title = 'Modeling your data';\n *\n * @method Component#on\n * @param {string} event Name of event to subsribe to.\n * @param {Function} listener Listener function to handle the event.\n * @param {*} [ctx] Optional content in which to invoke the listener.\n * @since 3.0.0\n */\n/**\n * Remove an event listener from this Component. If no listener is provided,\n * then all listeners for the specified event will be removed. If no event is\n * specified then all listeners for all events will be removed.\n *\n * @example\n * // Remove a particular listener for a particular event\n * collection.off('add', handler);\n *\n * @example\n * // Remove all listeners for a particular event\n * record.off('change');\n *\n * @example\n * // Remove all listeners to all events\n * store.off();\n *\n * @method Component#off\n * @param {string} [event] Name of event to unsubsribe to.\n * @param {Function} [listener] Listener to remove.\n * @since 3.0.0\n */\n/**\n * Trigger an event on this Component.\n *\n * @example Component#emit\n * // import { Collection, DataStore } from 'js-data';\n * const JSData = require('js-data');\n * const { Collection, DataStore } = JSData;\n *\n * const collection = new Collection();\n * collection.on('foo', function (msg) {\n * console.log(msg);\n * });\n * collection.emit('foo', 'bar');\n *\n * const store = new DataStore();\n * store.on('beep', function (msg) {\n * console.log(msg);\n * });\n * store.emit('beep', 'boop');\n *\n * @method Component#emit\n * @param {string} event Name of event to emit.\n * @param {...*} [args] Arguments to pass to any listeners.\n * @since 3.0.0\n */\nutils.eventify(\n Component.prototype,\n function () {\n return this._listeners\n },\n function (value) {\n this._listeners = value\n }\n)\n","import utils from './utils'\nimport Component from './Component'\n\nconst DOMAIN = 'Query'\nconst INDEX_ERR = 'Index inaccessible after first operation'\n\n// Reserved words used by JSData's Query Syntax\nconst reserved = {\n limit: '',\n offset: '',\n orderBy: '',\n skip: '',\n sort: '',\n where: ''\n}\n\n// Used by our JavaScript implementation of the LIKE operator\nconst escapeRegExp = /([.*+?^=!:${}()|[\\]/\\\\])/g\nconst percentRegExp = /%/g\nconst underscoreRegExp = /_/g\nconst escape = function (pattern) {\n return pattern.replace(escapeRegExp, '\\\\$1')\n}\n\n/**\n * A class used by the {@link Collection} class to build queries to be executed\n * against the collection's data. An instance of `Query` is returned by\n * {@link Collection#query}. Query instances are typically short-lived, and you\n * shouldn't have to create them yourself. Just use {@link Collection#query}.\n *\n * ```javascript\n * import { Query } from 'js-data';\n * ```\n *\n * @example Query intro\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'draft', id: 2 },\n * { author: 'Mike', age: 32, status: 'draft', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'draft', id: 5 }\n * ]\n * store.add('post', posts);\n * const drafts = store.query('post').filter({ status: 'draft' }).limit(2).run();\n * console.log(drafts);\n *\n * @class Query\n * @extends Component\n * @param {Collection} collection The collection on which this query operates.\n * @since 3.0.0\n */\nfunction Query (collection) {\n utils.classCallCheck(this, Query)\n\n /**\n * The {@link Collection} on which this query operates.\n *\n * @name Query#collection\n * @since 3.0.0\n * @type {Collection}\n */\n this.collection = collection\n\n /**\n * The current data result of this query.\n *\n * @name Query#data\n * @since 3.0.0\n * @type {Array}\n */\n this.data = null\n}\n\nexport default Component.extend({\n constructor: Query,\n\n _applyWhereFromObject (where) {\n const fields = []\n const ops = []\n const predicates = []\n utils.forOwn(where, (clause, field) => {\n if (!utils.isObject(clause)) {\n clause = {\n '==': clause\n }\n }\n utils.forOwn(clause, (expr, op) => {\n fields.push(field)\n ops.push(op)\n predicates.push(expr)\n })\n })\n return {\n fields,\n ops,\n predicates\n }\n },\n\n _applyWhereFromArray (where) {\n const groups = []\n where.forEach((_where, i) => {\n if (utils.isString(_where)) {\n return\n }\n const prev = where[i - 1]\n const parser = utils.isArray(_where) ? this._applyWhereFromArray : this._applyWhereFromObject\n const group = parser.call(this, _where)\n if (prev === 'or') {\n group.isOr = true\n }\n groups.push(group)\n })\n groups.isArray = true\n return groups\n },\n\n _testObjectGroup (keep, first, group, item) {\n let i\n const fields = group.fields\n const ops = group.ops\n const predicates = group.predicates\n const len = ops.length\n for (i = 0; i < len; i++) {\n let op = ops[i]\n const isOr = op.charAt(0) === '|'\n op = isOr ? op.substr(1) : op\n const expr = this.evaluate(utils.get(item, fields[i]), op, predicates[i])\n if (expr !== undefined) {\n keep = first ? expr : (isOr ? keep || expr : keep && expr)\n }\n first = false\n }\n return { keep, first }\n },\n\n _testArrayGroup (keep, first, groups, item) {\n let i\n const len = groups.length\n for (i = 0; i < len; i++) {\n const group = groups[i]\n const parser = group.isArray ? this._testArrayGroup : this._testObjectGroup\n const result = parser.call(this, true, true, group, item)\n if (groups[i - 1]) {\n if (group.isOr) {\n keep = keep || result.keep\n } else {\n keep = keep && result.keep\n }\n } else {\n keep = result.keep\n }\n first = result.first\n }\n return { keep, first }\n },\n\n /**\n * Find all entities between two boundaries.\n *\n * @example Get the users ages 18 to 30.\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('user');\n * const users = [\n * { name: 'Peter', age: 25, id: 1 },\n * { name: 'Jim', age: 19, id: 2 },\n * { name: 'Mike', age: 17, id: 3 },\n * { name: 'Alan', age: 29, id: 4 },\n * { name: 'Katie', age: 33, id: 5 }\n * ];\n * store.add('user', users)\n * const filteredUsers = store\n * .query('user')\n * .between(18, 30, { index: 'age' })\n * .run();\n * console.log(filteredUsers);\n *\n * @example Same as above.\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('user');\n * const users = [\n * { name: 'Peter', age: 25, id: 1 },\n * { name: 'Jim', age: 19, id: 2 },\n * { name: 'Mike', age: 17, id: 3 },\n * { name: 'Alan', age: 29, id: 4 },\n * { name: 'Katie', age: 33, id: 5 }\n * ];\n * store.add('user', users)\n * const filteredUsers = store\n * .query('user')\n * .between([18], [30], { index: 'age' })\n * .run();\n * console.log(filteredUsers);\n *\n * @method Query#between\n * @param {array} leftKeys Keys defining the left boundary.\n * @param {array} rightKeys Keys defining the right boundary.\n * @param {object} [opts] Configuration options.\n * @param {string} [opts.index] Name of the secondary index to use in the\n * query. If no index is specified, the main index is used.\n * @param {boolean} [opts.leftInclusive=true] Whether to include entities\n * on the left boundary.\n * @param {boolean} [opts.rightInclusive=false] Whether to include entities\n * on the left boundary.\n * @param {boolean} [opts.limit] Limit the result to a certain number.\n * @param {boolean} [opts.offset] The number of resulting entities to skip.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n between (leftKeys, rightKeys, opts) {\n opts || (opts = {})\n if (this.data) {\n throw utils.err(`${DOMAIN}#between`)(500, 'Cannot access index')\n }\n this.data = this.collection.getIndex(opts.index).between(leftKeys, rightKeys, opts)\n return this\n },\n\n /**\n * The comparison function used by the {@link Query} class.\n *\n * @method Query#compare\n * @param {array} orderBy An orderBy clause used for sorting and sub-sorting.\n * @param {number} index The index of the current orderBy clause being used.\n * @param {*} a The first item in the comparison.\n * @param {*} b The second item in the comparison.\n * @returns {number} -1 if `b` should preceed `a`. 0 if `a` and `b` are equal.\n * 1 if `a` should preceed `b`.\n * @since 3.0.0\n */\n compare (orderBy, index, a, b) {\n const def = orderBy[index]\n let cA = utils.get(a, def[0])\n let cB = utils.get(b, def[0])\n if (cA && utils.isString(cA)) {\n cA = cA.toUpperCase()\n }\n if (cB && utils.isString(cB)) {\n cB = cB.toUpperCase()\n }\n if (a === undefined) {\n a = null\n }\n if (b === undefined) {\n b = null\n }\n if (def[1].toUpperCase() === 'DESC') {\n const temp = cB\n cB = cA\n cA = temp\n }\n if (cA < cB) {\n return -1\n } else if (cA > cB) {\n return 1\n } else {\n if (index < orderBy.length - 1) {\n return this.compare(orderBy, index + 1, a, b)\n } else {\n return 0\n }\n }\n },\n\n /**\n * Predicate evaluation function used by the {@link Query} class.\n *\n * @method Query#evaluate\n * @param {*} value The value to evaluate.\n * @param {string} op The operator to use in this evaluation.\n * @param {*} predicate The predicate to use in this evaluation.\n * @returns {boolean} Whether the value passed the evaluation or not.\n * @since 3.0.0\n */\n evaluate (value, op, predicate) {\n const ops = this.constructor.ops\n if (ops[op]) {\n return ops[op](value, predicate)\n }\n if (op.indexOf('like') === 0) {\n return this.like(predicate, op.substr(4)).exec(value) !== null\n } else if (op.indexOf('notLike') === 0) {\n return this.like(predicate, op.substr(7)).exec(value) === null\n }\n },\n\n /**\n * Find the record or records that match the provided query or are accepted by\n * the provided filter function.\n *\n * @example Get the draft posts by authors younger than 30\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post')\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'published', id: 2 },\n * { author: 'Mike', age: 32, status: 'draft', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'published', id: 5 }\n * { author: 'Peter', age: 25, status: 'deleted', id: 6 },\n * { author: 'Sally', age: 21, status: 'draft', id: 7 },\n * { author: 'Jim', age: 27, status: 'draft', id: 8 },\n * { author: 'Jim', age: 27, status: 'published', id: 9 },\n * { author: 'Jason', age: 55, status: 'published', id: 10 }\n * ];\n * store.add('post', posts);\n * const results = store\n * .query('post')\n * .filter({\n * where: {\n * status: {\n * '==': 'draft'\n * },\n * age: {\n * '<': 30\n * }\n * }\n * })\n * .run();\n * console.log(results);\n *\n * @example Use a custom filter function\n * const posts = query\n * .filter(function (post) {\n * return post.isReady();\n * })\n * .run();\n *\n * @method Query#filter\n * @param {(Object|Function)} [queryOrFn={}] Selection query or filter\n * function.\n * @param {Function} [thisArg] Context to which to bind `queryOrFn` if\n * `queryOrFn` is a function.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n filter (query, thisArg) {\n /**\n * Selection query as defined by JSData's [Query Syntax][querysyntax].\n *\n * [querysyntax]: http://www.js-data.io/v3.0/docs/query-syntax\n *\n * @example Empty \"findAll\" query\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post')\n * store.findAll('post').then((posts) => {\n * console.log(posts); // [...]\n * });\n *\n * @example Empty \"filter\" query\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n * const posts = store.filter('post');\n * console.log(posts); // [...]\n *\n * @example Complex \"filter\" query\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * const PAGE_SIZE = 2;\n * let currentPage = 3;\n *\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'published', id: 2 },\n * { author: 'Mike', age: 32, status: 'draft', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'published', id: 5 }\n * { author: 'Peter', age: 25, status: 'deleted', id: 6 },\n * { author: 'Sally', age: 21, status: 'draft', id: 7 },\n * { author: 'Jim', age: 27, status: 'draft', id: 8 },\n * { author: 'Jim', age: 27, status: 'published', id: 9 },\n * { author: 'Jason', age: 55, status: 'published', id: 10 }\n * ];\n * store.add('post', posts);\n * // Retrieve a filtered page of blog posts\n * // Would typically replace filter with findAll\n * const results = store.filter('post', {\n * where: {\n * status: {\n * // WHERE status = 'published'\n * '==': 'published'\n * },\n * author: {\n * // AND author IN ('bob', 'alice')\n * 'in': ['bob', 'alice'],\n * // OR author IN ('karen')\n * '|in': ['karen']\n * }\n * },\n * orderBy: [\n * // ORDER BY date_published DESC,\n * ['date_published', 'DESC'],\n * // ORDER BY title ASC\n * ['title', 'ASC']\n * ],\n * // LIMIT 2\n * limit: PAGE_SIZE,\n * // SKIP 4\n * offset: PAGE_SIZE * (currentPage - 1)\n * });\n * console.log(results);\n *\n * @namespace query\n * @property {number} [limit] See {@link query.limit}.\n * @property {number} [offset] See {@link query.offset}.\n * @property {string|Array[]} [orderBy] See {@link query.orderBy}.\n * @property {number} [skip] Alias for {@link query.offset}.\n * @property {string|Array[]} [sort] Alias for {@link query.orderBy}.\n * @property {Object} [where] See {@link query.where}.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/query-syntax\",\"JSData's Query Syntax\"]\n */\n query || (query = {})\n this.getData()\n if (utils.isObject(query)) {\n let where = {}\n\n /**\n * Filtering criteria. Records that do not meet this criteria will be exluded\n * from the result.\n *\n * @example Return posts where author is at least 32 years old\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post')\n * const posts = [\n * { author: 'John', age: 30, id: 5 },\n * { author: 'Sally', age: 31, id: 6 },\n * { author: 'Mike', age: 32, id: 7 },\n * { author: 'Adam', age: 33, id: 8 },\n * { author: 'Adam', age: 33, id: 9 }\n * ];\n * store.add('post', posts);\n * const results = store.filter('post', {\n * where: {\n * age: {\n * '>=': 30\n * }\n * }\n * });\n * console.log(results);\n *\n * @name query.where\n * @type {Object}\n * @see http://www.js-data.io/v3.0/docs/query-syntax\n * @since 3.0.0\n */\n if (utils.isObject(query.where) || utils.isArray(query.where)) {\n where = query.where\n }\n utils.forOwn(query, function (value, key) {\n if (!(key in reserved) && !(key in where)) {\n where[key] = {\n '==': value\n }\n }\n })\n let groups\n\n // Apply filter for each field\n if (utils.isObject(where) && Object.keys(where).length !== 0) {\n groups = this._applyWhereFromArray([where])\n } else if (utils.isArray(where)) {\n groups = this._applyWhereFromArray(where)\n }\n\n if (groups) {\n this.data = this.data.filter((item, i) => this._testArrayGroup(true, true, groups, item).keep)\n }\n\n // Sort\n let orderBy = query.orderBy || query.sort\n\n if (utils.isString(orderBy)) {\n orderBy = [\n [orderBy, 'ASC']\n ]\n }\n if (!utils.isArray(orderBy)) {\n orderBy = null\n }\n\n /**\n * Determines how records should be ordered in the result.\n *\n * @example Order posts by `author` then by `id` descending \n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post')\n * const posts = [\n * { author: 'John', age: 30, id: 5 },\n * { author: 'Sally', age: 31, id: 6 },\n * { author: 'Mike', age: 32, id: 7 },\n * { author: 'Adam', age: 33, id: 8 },\n * { author: 'Adam', age: 33, id: 9 }\n * ];\n * store.add('post', posts);\n * const results = store.filter('post', {\n * orderBy:[['author','ASC'],['id','DESC']]\n * });\n * console.log(results);\n *\n * @name query.orderBy\n * @type {string|Array[]}\n * @see http://www.js-data.io/v3.0/docs/query-syntax\n * @since 3.0.0\n */\n if (orderBy) {\n let index = 0\n orderBy.forEach(function (def, i) {\n if (utils.isString(def)) {\n orderBy[i] = [def, 'ASC']\n }\n })\n this.data.sort((a, b) => this.compare(orderBy, index, a, b))\n }\n\n /**\n * Number of records to skip.\n *\n * @example Retrieve the first \"page\" of blog posts using findAll\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n * const PAGE_SIZE = 10;\n * let currentPage = 1;\n * store.findAll('post', {\n * offset: PAGE_SIZE * (currentPage 1)\n * limit: PAGE_SIZE\n * });\n *\n * @example Retrieve the last \"page\" of blog posts using filter\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n *\n * const PAGE_SIZE = 5;\n * let currentPage = 2;\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, id: 1 },\n * { author: 'Sally', age: 31, id: 2 },\n * { author: 'Mike', age: 32, id: 3 },\n * { author: 'Adam', age: 33, id: 4 },\n * { author: 'Adam', age: 33, id: 5 },\n * { author: 'Peter', age: 25, id: 6 },\n * { author: 'Sally', age: 21, id: 7 },\n * { author: 'Jim', age: 27, id: 8 },\n * { author: 'Jim', age: 27, id: 9 },\n * { author: 'Jason', age: 55, id: 10 }\n * ];\n * store.add('post', posts);\n * const results = store.filter('post', {\n * offset: PAGE_SIZE * (currentPage 1)\n * limit: PAGE_SIZE\n * });\n * console.log(results)\n *\n * @name query.offset\n * @type {number}\n * @see http://www.js-data.io/v3.0/docs/query-syntax\n * @since 3.0.0\n */\n if (utils.isNumber(query.skip)) {\n this.skip(query.skip)\n } else if (utils.isNumber(query.offset)) {\n this.skip(query.offset)\n }\n\n /**\n * Maximum number of records to retrieve.\n *\n * @example Retrieve the first \"page\" of blog posts using findAll\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n *\n * const PAGE_SIZE = 10\n * let currentPage = 1\n * store.findAll('post', {\n * offset: PAGE_SIZE * (currentPage 1)\n * limit: PAGE_SIZE\n * });\n *\n * @example Retrieve the last \"page\" of blog posts using filter\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n *\n * const PAGE_SIZE = 5\n * let currentPage = 2\n * store.defineMapper('post')\n * const posts = [\n * { author: 'John', age: 30, id: 1 },\n * { author: 'Sally', age: 31, id: 2 },\n * { author: 'Mike', age: 32, id: 3 },\n * { author: 'Adam', age: 33, id: 4 },\n * { author: 'Adam', age: 33, id: 5 },\n * { author: 'Peter', age: 25, id: 6 },\n * { author: 'Sally', age: 21, id: 7 },\n * { author: 'Jim', age: 27, id: 8 },\n * { author: 'Jim', age: 27, id: 9 },\n * { author: 'Jason', age: 55, id: 10 }\n * ];\n * store.add('post', posts);\n * const results = store.filter('post', {\n * offset: PAGE_SIZE * (currentPage 1)\n * limit: PAGE_SIZE\n * });\n * console.log(results)\n *\n * @name query.limit\n * @type {number}\n * @see http://www.js-data.io/v3.0/docs/query-syntax\n * @since 3.0.0\n */\n if (utils.isNumber(query.limit)) {\n this.limit(query.limit)\n }\n } else if (utils.isFunction(query)) {\n this.data = this.data.filter(query, thisArg)\n }\n return this\n },\n\n /**\n * Iterate over all entities.\n *\n * @method Query#forEach\n * @param {Function} forEachFn Iteration function.\n * @param {*} [thisArg] Context to which to bind `forEachFn`.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n forEach (forEachFn, thisArg) {\n this.getData().forEach(forEachFn, thisArg)\n return this\n },\n\n /**\n * Find the entity or entities that match the provided key.\n *\n * @example Get the entity whose primary key is 25.\n * const entities = query.get(25).run();\n *\n * @example Same as above.\n * const entities = query.get([25]).run();\n *\n * @example Get all users who are active and have the \"admin\" role.\n * const activeAdmins = query.get(['active', 'admin'], {\n * index: 'activityAndRoles'\n * }).run();\n *\n * @example Get all entities that match a certain weather condition.\n * const niceDays = query.get(['sunny', 'humid', 'calm'], {\n * index: 'weatherConditions'\n * }).run();\n *\n * @method Query#get\n * @param {array} keyList Key(s) defining the entity to retrieve. If\n * `keyList` is not an array (i.e. for a single-value key), it will be\n * wrapped in an array.\n * @param {object} [opts] Configuration options.\n * @param {string} [opts.string] Name of the secondary index to use in the\n * query. If no index is specified, the main index is used.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n get (keyList, opts) {\n keyList || (keyList = [])\n opts || (opts = {})\n if (this.data) {\n throw utils.err(`${DOMAIN}#get`)(500, INDEX_ERR)\n }\n if (keyList && !utils.isArray(keyList)) {\n keyList = [keyList]\n }\n if (!keyList.length) {\n this.getData()\n return this\n }\n this.data = this.collection.getIndex(opts.index).get(keyList)\n return this\n },\n\n /**\n * Find the entity or entities that match the provided keyLists.\n *\n * @example Get the posts where \"status\" is \"draft\" or \"inReview\".\n * const posts = query.getAll('draft', 'inReview', { index: 'status' }).run();\n *\n * @example Same as above.\n * const posts = query.getAll(['draft'], ['inReview'], { index: 'status' }).run();\n *\n * @method Query#getAll\n * @param {...Array} [keyList] Provide one or more keyLists, and all\n * entities matching each keyList will be retrieved. If no keyLists are\n * provided, all entities will be returned.\n * @param {object} [opts] Configuration options.\n * @param {string} [opts.index] Name of the secondary index to use in the\n * query. If no index is specified, the main index is used.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n getAll (...args) {\n let opts = {}\n if (this.data) {\n throw utils.err(`${DOMAIN}#getAll`)(500, INDEX_ERR)\n }\n if (!args.length || (args.length === 1 && utils.isObject(args[0]))) {\n this.getData()\n return this\n } else if (args.length && utils.isObject(args[args.length - 1])) {\n opts = args[args.length - 1]\n args.pop()\n }\n const collection = this.collection\n const index = collection.getIndex(opts.index)\n this.data = []\n args.forEach((keyList) => {\n this.data = this.data.concat(index.get(keyList))\n })\n return this\n },\n\n /**\n * Return the current data result of this query.\n *\n * @method Query#getData\n * @returns {Array} The data in this query.\n * @since 3.0.0\n */\n getData () {\n if (!this.data) {\n this.data = this.collection.index.getAll()\n }\n return this.data\n },\n\n /**\n * Implementation used by the `like` operator. Takes a pattern and flags and\n * returns a `RegExp` instance that can test strings.\n *\n * @method Query#like\n * @param {string} pattern Testing pattern.\n * @param {string} flags Flags for the regular expression.\n * @returns {RegExp} Regular expression for testing strings.\n * @since 3.0.0\n */\n like (pattern, flags) {\n return new RegExp(`^${(escape(pattern).replace(percentRegExp, '.*').replace(underscoreRegExp, '.'))}$`, flags)\n },\n\n /**\n * Limit the result.\n *\n * @example Get only the first 2 posts.\n * const store = new JSData.DataStore();\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'draft', id: 2 },\n * { author: 'Mike', age: 32, status: 'draft', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'draft', id: 5 }\n * ];\n * store.add('post', posts);\n * const results = store.query('post').limit(2).run();\n * console.log(results);\n *\n * @method Query#limit\n * @param {number} num The maximum number of entities to keep in the result.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n limit (num) {\n if (!utils.isNumber(num)) {\n throw utils.err(`${DOMAIN}#limit`, 'num')(400, 'number', num)\n }\n const data = this.getData()\n this.data = data.slice(0, Math.min(data.length, num))\n return this\n },\n\n /**\n * Apply a mapping function to the result data.\n *\n * @example\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('user');\n * const users = [\n * { name: 'Peter', age: 25, id: 1 },\n * { name: 'Jim', age: 19, id: 2 },\n * { name: 'Mike', age: 17, id: 3 },\n * { name: 'Alan', age: 29, id: 4 },\n * { name: 'Katie', age: 33, id: 5 }\n * ];\n * store.add('user', users);\n * const ages = store\n * .query('user')\n * .map(function (user) {\n * return user.age;\n * })\n * .run();\n * console.log(ages);\n *\n * @method Query#map\n * @param {Function} mapFn Mapping function.\n * @param {*} [thisArg] Context to which to bind `mapFn`.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n map (mapFn, thisArg) {\n this.data = this.getData().map(mapFn, thisArg)\n return this\n },\n\n /**\n * Return the result of calling the specified function on each item in this\n * collection's main index.\n *\n * @example\n * const stringAges = UserCollection.query().mapCall('toString').run();\n *\n * @method Query#mapCall\n * @param {string} funcName Name of function to call\n * @parama {...*} [args] Remaining arguments to be passed to the function.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n mapCall (funcName, ...args) {\n this.data = this.getData().map(function (item) {\n return item[funcName](...args)\n })\n return this\n },\n\n /**\n * Complete the execution of the query and return the resulting data.\n *\n * @method Query#run\n * @returns {Array} The result of executing this query.\n * @since 3.0.0\n */\n run () {\n const data = this.data\n this.data = null\n return data\n },\n\n /**\n * Skip a number of results.\n *\n * @example Get all but the first 2 posts.\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'draft', id: 2 },\n * { author: 'Mike', age: 32, status: 'draft', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'draft', id: 5 }\n * ];\n * store.add('post', posts);\n * const results = store.query('post').skip(2).run();\n * console.log(results);\n *\n * @method Query#skip\n * @param {number} num The number of entities to skip.\n * @returns {Query} A reference to itself for chaining.\n * @since 3.0.0\n */\n skip (num) {\n if (!utils.isNumber(num)) {\n throw utils.err(`${DOMAIN}#skip`, 'num')(400, 'number', num)\n }\n const data = this.getData()\n if (num < data.length) {\n this.data = data.slice(num)\n } else {\n this.data = []\n }\n return this\n }\n}, {\n /**\n * The filtering operators supported by {@link Query#filter}, and which are\n * implemented by adapters (for the most part).\n *\n * @example Variant 1\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'published', id: 2 },\n * { author: 'Mike', age: 32, status: 'published', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'published', id: 5 }\n * ];\n * store.add('post', posts);\n * const publishedPosts = store.filter('post', {\n * status: 'published',\n * limit: 2\n * });\n * console.log(publishedPosts);\n *\n *\n * @example Variant 2\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post')\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'published', id: 2 },\n * { author: 'Mike', age: 32, status: 'published', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'published', id: 5 }\n * ];\n * store.add('post', posts);\n * const publishedPosts = store.filter('post', {\n * where: {\n * status: {\n * '==': 'published'\n * }\n * },\n * limit: 2\n * });\n * console.log(publishedPosts);\n *\n * @example Variant 3\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'published', id: 2 },\n * { author: 'Mike', age: 32, status: 'published', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'published', id: 5 }\n * ];\n * store.add('post', posts);\n * const publishedPosts = store\n * .query('post')\n * .filter({ status: 'published' })\n * .limit(2)\n * .run();\n * console.log(publishedPosts);\n *\n * @example Variant 4\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'published', id: 2 },\n * { author: 'Mike', age: 32, status: 'published', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'published', id: 5 }\n * ];\n * store.add('post', posts);\n * const publishedPosts = store\n * .query('post')\n * .filter({\n * where: {\n * status: {\n * '==': 'published'\n * }\n * }\n * })\n * .limit(2)\n * .run();\n * console.log(publishedPosts);\n *\n * @example Multiple operators\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new DataStore();\n * store.defineMapper('post');\n * const posts = [\n * { author: 'John', age: 30, status: 'published', id: 1 },\n * { author: 'Sally', age: 31, status: 'published', id: 2 },\n * { author: 'Mike', age: 32, status: 'published', id: 3 },\n * { author: 'Adam', age: 33, status: 'deleted', id: 4 },\n * { author: 'Adam', age: 33, status: 'published', id: 5 }\n * ];\n * store.add('post', posts);\n *\n * const myPublishedPosts = store.filter('post', {\n * where: {\n * status: {\n * '==': 'published'\n * },\n * user_id: {\n * '==': currentUser.id\n * }\n * }\n * });\n *\n * console.log(myPublishedPosts);\n *\n * @name Query.ops\n * @property {Function} == Equality operator.\n * @property {Function} != Inequality operator.\n * @property {Function} > Greater than operator.\n * @property {Function} >= Greater than (inclusive) operator.\n * @property {Function} < Less than operator.\n * @property {Function} <= Less than (inclusive) operator.\n * @property {Function} isectEmpty Operator that asserts that the intersection\n * between two arrays is empty.\n * @property {Function} isectNotEmpty Operator that asserts that the\n * intersection between two arrays is __not__ empty.\n * @property {Function} in Operator that asserts whether a value is in an\n * array.\n * @property {Function} notIn Operator that asserts whether a value is __not__\n * in an array.\n * @property {Function} contains Operator that asserts whether an array\n * contains a value.\n * @property {Function} notContains Operator that asserts whether an array\n * does __not__ contain a value.\n * @since 3.0.0\n * @type {Object}\n */\n ops: {\n '=': function (value, predicate) {\n return value == predicate // eslint-disable-line\n },\n '==': function (value, predicate) {\n return value == predicate // eslint-disable-line\n },\n '===': function (value, predicate) {\n return value === predicate\n },\n '!=': function (value, predicate) {\n return value != predicate // eslint-disable-line\n },\n '!==': function (value, predicate) {\n return value !== predicate\n },\n '>': function (value, predicate) {\n return value > predicate\n },\n '>=': function (value, predicate) {\n return value >= predicate\n },\n '<': function (value, predicate) {\n return value < predicate\n },\n '<=': function (value, predicate) {\n return value <= predicate\n },\n 'isectEmpty': function (value, predicate) {\n return !utils.intersection((value || []), (predicate || [])).length\n },\n 'isectNotEmpty': function (value, predicate) {\n return utils.intersection((value || []), (predicate || [])).length\n },\n 'in': function (value, predicate) {\n return predicate.indexOf(value) !== -1\n },\n 'notIn': function (value, predicate) {\n return predicate.indexOf(value) === -1\n },\n 'contains': function (value, predicate) {\n return (value || []).indexOf(predicate) !== -1\n },\n 'notContains': function (value, predicate) {\n return (value || []).indexOf(predicate) === -1\n }\n }\n})\n\n/**\n * Create a subclass of this Query:\n * @example Query.extend\n * const JSData = require('js-data');\n * const { Query } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomQueryClass extends Query {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customQuery = new CustomQueryClass();\n * console.log(customQuery.foo());\n * console.log(CustomQueryClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherQueryClass = Query.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherQuery = new OtherQueryClass();\n * console.log(otherQuery.foo());\n * console.log(OtherQueryClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherQueryClass (collection) {\n * Query.call(this, collection);\n * this.created_at = new Date().getTime();\n * }\n * Query.extend({\n * constructor: AnotherQueryClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const anotherQuery = new AnotherQueryClass();\n * console.log(anotherQuery.created_at);\n * console.log(anotherQuery.foo());\n * console.log(AnotherQueryClass.beep());\n *\n * @method Query.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this Query class.\n * @since 3.0.0\n */\n","import utils from './utils'\n\n// TODO: remove this when the rest of the project is cleaned\nexport const belongsToType = 'belongsTo'\nexport const hasManyType = 'hasMany'\nexport const hasOneType = 'hasOne'\n\nconst DOMAIN = 'Relation'\n\nexport function Relation (relatedMapper, options = {}) {\n utils.classCallCheck(this, Relation)\n\n options.type = this.constructor.TYPE_NAME\n this.validateOptions(relatedMapper, options)\n\n if (typeof relatedMapper === 'object') {\n Object.defineProperty(this, 'relatedMapper', { value: relatedMapper })\n }\n\n Object.defineProperty(this, 'inverse', { writable: true })\n utils.fillIn(this, options)\n}\n\nRelation.extend = utils.extend\n\nutils.addHiddenPropsToTarget(Relation.prototype, {\n get canAutoAddLinks () {\n return this.add === undefined || !!this.add\n },\n\n get relatedCollection () {\n return this.mapper.datastore.getCollection(this.relation)\n },\n\n validateOptions (related, opts) {\n const DOMAIN_ERR = `new ${DOMAIN}`\n\n const localField = opts.localField\n if (!localField) {\n throw utils.err(DOMAIN_ERR, 'opts.localField')(400, 'string', localField)\n }\n\n const foreignKey = opts.foreignKey = opts.foreignKey || opts.localKey\n if (!foreignKey && (opts.type === belongsToType || opts.type === hasOneType)) {\n throw utils.err(DOMAIN_ERR, 'opts.foreignKey')(400, 'string', foreignKey)\n }\n\n if (utils.isString(related)) {\n opts.relation = related\n if (!utils.isFunction(opts.getRelation)) {\n throw utils.err(DOMAIN_ERR, 'opts.getRelation')(400, 'function', opts.getRelation)\n }\n } else if (related) {\n opts.relation = related.name\n } else {\n throw utils.err(DOMAIN_ERR, 'related')(400, 'Mapper or string', related)\n }\n },\n\n assignTo (mapper) {\n this.name = mapper.name\n Object.defineProperty(this, 'mapper', { value: mapper })\n\n mapper.relationList || Object.defineProperty(mapper, 'relationList', { value: [] })\n mapper.relationFields || Object.defineProperty(mapper, 'relationFields', { value: [] })\n mapper.relationList.push(this)\n mapper.relationFields.push(this.localField)\n },\n\n canFindLinkFor () {\n return !!(this.foreignKey || this.localKey)\n },\n\n getRelation () {\n return this.relatedMapper\n },\n\n getForeignKey (record) {\n return utils.get(record, this.mapper.idAttribute)\n },\n\n setForeignKey (record, relatedRecord) {\n if (!record || !relatedRecord) {\n return\n }\n\n this._setForeignKey(record, relatedRecord)\n },\n\n _setForeignKey (record, relatedRecords) {\n const idAttribute = this.mapper.idAttribute\n\n if (!utils.isArray(relatedRecords)) {\n relatedRecords = [relatedRecords]\n }\n\n relatedRecords.forEach((relatedRecord) => {\n utils.set(relatedRecord, this.foreignKey, utils.get(record, idAttribute))\n })\n },\n\n getLocalField (record) {\n return utils.get(record, this.localField)\n },\n\n setLocalField (record, relatedData) {\n return utils.set(record, this.localField, relatedData)\n },\n\n getInverse (mapper) {\n if (!this.inverse) {\n this.findInverseRelation(mapper)\n }\n\n return this.inverse\n },\n\n findInverseRelation (mapper) {\n this.getRelation().relationList.forEach((def) => {\n if (def.getRelation() === mapper && this.isInversedTo(def) && this !== def) {\n this.inverse = def\n return true\n }\n })\n },\n\n isInversedTo (def) {\n return !def.foreignKey || def.foreignKey === this.foreignKey\n },\n\n addLinkedRecords (records) {\n const datastore = this.mapper.datastore\n\n records.forEach((record) => {\n let relatedData = this.getLocalField(record)\n\n if (utils.isFunction(this.add)) {\n relatedData = this.add(datastore, this, record)\n } else if (relatedData) {\n relatedData = this.linkRecord(record, relatedData)\n }\n\n const isEmptyLinks = !relatedData || (utils.isArray(relatedData) && !relatedData.length)\n\n if (isEmptyLinks && this.canFindLinkFor(record)) {\n relatedData = this.findExistingLinksFor(record)\n }\n\n if (relatedData) {\n this.setLocalField(record, relatedData)\n }\n })\n },\n\n removeLinkedRecords (relatedMapper, records) {\n const localField = this.localField\n records.forEach((record) => {\n utils.set(record, localField, undefined)\n })\n },\n\n linkRecord (record, relatedRecord) {\n const relatedId = utils.get(relatedRecord, this.mapper.idAttribute)\n\n if (relatedId === undefined) {\n const unsaved = this.relatedCollection.unsaved()\n if (unsaved.indexOf(relatedRecord) === -1) {\n if (this.canAutoAddLinks) {\n relatedRecord = this.relatedCollection.add(relatedRecord)\n }\n }\n } else {\n if (relatedRecord !== this.relatedCollection.get(relatedId)) {\n this.setForeignKey(record, relatedRecord)\n\n if (this.canAutoAddLinks) {\n relatedRecord = this.relatedCollection.add(relatedRecord)\n }\n }\n }\n\n return relatedRecord\n },\n\n // e.g. user hasMany post via \"foreignKey\", so find all posts of user\n findExistingLinksByForeignKey (id) {\n if (id === undefined || id === null) {\n return\n }\n return this.relatedCollection.filter({\n [this.foreignKey]: id\n })\n },\n\n ensureLinkedDataHasProperType (props, opts) {\n const relatedMapper = this.getRelation()\n const relationData = this.getLocalField(props)\n\n if (utils.isArray(relationData) && (!relationData.length || relatedMapper.is(relationData[0]))) {\n return\n }\n\n if (relationData && !relatedMapper.is(relationData)) {\n utils.set(props, this.localField, relatedMapper.createRecord(relationData, opts))\n }\n },\n\n isRequiresParentId () {\n return false\n },\n\n isRequiresChildId () {\n return false\n },\n\n createChildRecord (props, relationData, opts) {\n this.setForeignKey(props, relationData)\n\n return this.createLinked(relationData, opts).then((result) => {\n this.setLocalField(props, result)\n })\n },\n\n createLinked (props, opts) {\n const create = utils.isArray(props) ? 'createMany' : 'create'\n\n return this.getRelation()[create](props, opts)\n }\n})\n","import utils from '../utils'\nimport { Relation } from '../Relation'\n\nexport const BelongsToRelation = Relation.extend({\n getForeignKey (record) {\n return utils.get(record, this.foreignKey)\n },\n\n _setForeignKey (record, relatedRecord) {\n utils.set(record, this.foreignKey, utils.get(relatedRecord, this.getRelation().idAttribute))\n },\n\n findExistingLinksFor (record) {\n // console.log('\\tBelongsTo#findExistingLinksFor', record)\n if (!record) {\n return\n }\n const relatedId = utils.get(record, this.foreignKey)\n if (relatedId !== undefined && relatedId !== null) {\n return this.relatedCollection.get(relatedId)\n }\n },\n\n isRequiresParentId () {\n return true\n },\n\n createParentRecord (props, opts) {\n const relationData = this.getLocalField(props)\n\n return this.createLinked(relationData, opts).then((record) => {\n this.setForeignKey(props, record)\n })\n },\n\n createChildRecord () {\n throw new Error('\"BelongsTo\" relation does not support child creation as it cannot have children.')\n }\n}, {\n TYPE_NAME: 'belongsTo'\n})\n","import utils from '../utils'\nimport { Relation } from '../Relation'\n\nexport const HasManyRelation = Relation.extend({\n validateOptions (related, opts) {\n Relation.prototype.validateOptions.call(this, related, opts)\n\n const { localKeys, foreignKeys, foreignKey } = opts\n\n if (!foreignKey && !localKeys && !foreignKeys) {\n throw utils.err('new Relation', 'opts.')(400, 'string', foreignKey)\n }\n },\n\n canFindLinkFor (record) {\n const hasForeignKeys = this.foreignKey || this.foreignKeys\n return !!(hasForeignKeys || (this.localKeys && utils.get(record, this.localKeys)))\n },\n\n linkRecord (record, relatedRecords) {\n const relatedCollection = this.relatedCollection\n const canAutoAddLinks = this.canAutoAddLinks\n const foreignKey = this.foreignKey\n const unsaved = this.relatedCollection.unsaved()\n\n return relatedRecords.map((relatedRecord) => {\n const relatedId = relatedCollection.recordId(relatedRecord)\n\n if ((relatedId === undefined && unsaved.indexOf(relatedRecord) === -1) || relatedRecord !== relatedCollection.get(relatedId)) {\n if (foreignKey) {\n // TODO: slow, could be optimized? But user loses hook\n this.setForeignKey(record, relatedRecord)\n }\n if (canAutoAddLinks) {\n relatedRecord = relatedCollection.add(relatedRecord)\n }\n }\n\n return relatedRecord\n })\n },\n\n findExistingLinksFor (record) {\n const id = utils.get(record, this.mapper.idAttribute)\n const ids = this.localKeys ? utils.get(record, this.localKeys) : null\n let records\n\n if (id !== undefined && this.foreignKey) {\n records = this.findExistingLinksByForeignKey(id)\n } else if (this.localKeys && ids) {\n records = this.findExistingLinksByLocalKeys(ids)\n } else if (id !== undefined && this.foreignKeys) {\n records = this.findExistingLinksByForeignKeys(id)\n }\n\n if (records && records.length) {\n return records\n }\n },\n\n // e.g. user hasMany group via \"foreignKeys\", so find all users of a group\n findExistingLinksByLocalKeys (ids) {\n return this.relatedCollection.filter({\n where: {\n [this.mapper.idAttribute]: {\n 'in': ids\n }\n }\n })\n },\n\n // e.g. group hasMany user via \"localKeys\", so find all groups that own a user\n findExistingLinksByForeignKeys (id) {\n return this.relatedCollection.filter({\n where: {\n [this.foreignKeys]: {\n 'contains': id\n }\n }\n })\n },\n\n isRequiresParentId () {\n return !!this.localKeys && this.localKeys.length > 0\n },\n\n isRequiresChildId () {\n return !!this.foreignKey\n },\n\n createParentRecord (props, opts) {\n const relationData = this.getLocalField(props)\n const foreignIdField = this.getRelation().idAttribute\n\n return this.createLinked(relationData, opts).then((records) => {\n utils.set(props, this.localKeys, records.map((record) => utils.get(record, foreignIdField)))\n })\n },\n\n createLinked (props, opts) {\n return this.getRelation().createMany(props, opts)\n }\n}, {\n TYPE_NAME: 'hasMany'\n})\n","import utils from '../utils'\nimport { Relation } from '../Relation'\n\nexport const HasOneRelation = Relation.extend({\n findExistingLinksFor (relatedMapper, record) {\n const recordId = utils.get(record, relatedMapper.idAttribute)\n const records = this.findExistingLinksByForeignKey(recordId)\n\n if (records && records.length) {\n return records[0]\n }\n },\n\n isRequiresChildId () {\n return true\n }\n}, {\n TYPE_NAME: 'hasOne'\n})\n","import { Relation } from './Relation'\nimport { BelongsToRelation } from './Relation/BelongsTo'\nimport { HasManyRelation } from './Relation/HasMany'\nimport { HasOneRelation } from './Relation/HasOne'\n\n[BelongsToRelation, HasManyRelation, HasOneRelation].forEach(function (RelationType) {\n Relation[RelationType.TYPE_NAME] = function (related, options) {\n return new RelationType(related, options)\n }\n})\n\nexport { belongsToType, hasManyType, hasOneType, Relation } from './Relation'\n","import { Relation } from './relations'\n\nexport { belongsToType, hasManyType, hasOneType } from './relations'\n/**\n * BelongsTo relation decorator. You probably won't use this directly.\n *\n * @name module:js-data.belongsTo\n * @method\n * @param {Mapper} related The relation the target belongs to.\n * @param {object} opts Configuration options.\n * @param {string} opts.foreignKey The field that holds the primary key of the\n * related record.\n * @param {string} opts.localField The field that holds a reference to the\n * related record object.\n * @returns {Function} Invocation function, which accepts the target as the only\n * parameter.\n */\nexport const belongsTo = function (related, opts) {\n return function (mapper) {\n Relation.belongsTo(related, opts).assignTo(mapper)\n }\n}\n\n/**\n * HasMany relation decorator. You probably won't use this directly.\n *\n * @name module:js-data.hasMany\n * @method\n * @param {Mapper} related The relation of which the target has many.\n * @param {object} opts Configuration options.\n * @param {string} [opts.foreignKey] The field that holds the primary key of the\n * related record.\n * @param {string} opts.localField The field that holds a reference to the\n * related record object.\n * @returns {Function} Invocation function, which accepts the target as the only\n * parameter.\n */\nexport const hasMany = function (related, opts) {\n return function (mapper) {\n Relation.hasMany(related, opts).assignTo(mapper)\n }\n}\n\n/**\n * HasOne relation decorator. You probably won't use this directly.\n *\n * @name module:js-data.hasOne\n * @method\n * @param {Mapper} related The relation of which the target has one.\n * @param {object} opts Configuration options.\n * @param {string} [opts.foreignKey] The field that holds the primary key of the\n * related record.\n * @param {string} opts.localField The field that holds a reference to the\n * related record object.\n * @returns {Function} Invocation function, which accepts the target as the only\n * parameter.\n */\nexport const hasOne = function (related, opts) {\n return function (mapper) {\n Relation.hasOne(related, opts).assignTo(mapper)\n }\n}\n","import utils, { safeSetLink } from './utils'\nimport Component from './Component'\nimport Settable from './Settable'\nimport {\n hasManyType,\n hasOneType\n} from './decorators'\n\nconst DOMAIN = 'Record'\n\nconst superMethod = function (mapper, name) {\n const store = mapper.datastore\n if (store && store[name]) {\n return function (...args) {\n return store[name](mapper.name, ...args)\n }\n }\n return mapper[name].bind(mapper)\n}\n\n// Cache these strings\nconst creatingPath = 'creating'\nconst noValidatePath = 'noValidate'\nconst keepChangeHistoryPath = 'keepChangeHistory'\nconst previousPath = 'previous'\n\n/**\n * js-data's Record class. An instance of `Record` corresponds to an in-memory\n * representation of a single row or document in a database, Firebase,\n * localstorage, etc. Basically, a `Record` instance represents whatever kind of\n * entity in your persistence layer that has a primary key.\n *\n * ```javascript\n * import {Record} from 'js-data'\n * ```\n *\n * @example Record#constructor\n * const JSData = require('js-data');\n * const { Record } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Instantiate a plain record\n * let record = new Record();\n * console.log('record: ' + JSON.stringify(record));\n *\n * // You can supply properties on instantiation\n * record = new Record({ name: 'John' });\n * console.log('record: ' + JSON.stringify(record));\n *\n * @example Record#constructor2\n * const JSData = require('js-data');\n * const { Mapper } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Instantiate a record that's associated with a Mapper:\n * const UserMapper = new Mapper({ name: 'user' });\n * const User = UserMapper.recordClass;\n * const user = UserMapper.createRecord({ name: 'John' });\n * const user2 = new User({ name: 'Sally' });\n * console.log('user: ' + JSON.stringify(user));\n * console.log('user2: ' + JSON.stringify(user2));\n *\n * @example Record#constructor3\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * store.defineMapper('user');\n *\n * // Instantiate a record that's associated with a store's Mapper\n * const user = store.createRecord('user', { name: 'John' });\n * console.log('user: ' + JSON.stringify(user));\n *\n * @example Record#constructor4\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * store.defineMapper('user', {\n * schema: {\n * properties: {\n * name: { type: 'string' }\n * }\n * }\n * });\n *\n * // Validate on instantiation\n * const user = store.createRecord('user', { name: 1234 });\n * console.log('user: ' + JSON.stringify(user));\n *\n * @example Record#constructor5\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * store.defineMapper('user', {\n * schema: {\n * properties: {\n * name: { type: 'string' }\n * }\n * }\n * });\n *\n * // Skip validation on instantiation\n * const user = store.createRecord('user', { name: 1234 }, { noValidate: true });\n * console.log('user: ' + JSON.stringify(user));\n * console.log('user.isValid(): ' + user.isValid());\n *\n * @class Record\n * @extends Component\n * @param {object} [props] The initial properties of the new Record instance.\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.noValidate=false] Whether to skip validation on the\n * initial properties.\n * @param {boolean} [opts.validateOnSet=true] Whether to enable setter\n * validation on properties after the Record has been initialized.\n * @since 3.0.0\n */\nfunction Record (props, opts) {\n utils.classCallCheck(this, Record)\n Settable.call(this)\n props || (props = {})\n opts || (opts = {})\n const _set = this._set\n const mapper = this.constructor.mapper\n\n _set(creatingPath, true)\n _set(noValidatePath, !!opts.noValidate)\n _set(keepChangeHistoryPath, opts.keepChangeHistory === undefined ? (mapper ? mapper.keepChangeHistory : true) : opts.keepChangeHistory)\n\n // Set the idAttribute value first, if it exists.\n const id = mapper ? utils.get(props, mapper.idAttribute) : undefined\n if (id !== undefined) {\n utils.set(this, mapper.idAttribute, id)\n }\n\n utils.fillIn(this, props)\n _set(creatingPath, false)\n if (opts.validateOnSet !== undefined) {\n _set(noValidatePath, !opts.validateOnSet)\n } else if (mapper && mapper.validateOnSet !== undefined) {\n _set(noValidatePath, !mapper.validateOnSet)\n } else {\n _set(noValidatePath, false)\n }\n _set(previousPath, mapper ? mapper.toJSON(props) : utils.plainCopy(props))\n}\n\nexport default Component.extend({\n constructor: Record,\n\n /**\n * Returns the {@link Mapper} paired with this record's class, if any.\n *\n * @method Record#_mapper\n * @returns {Mapper} The {@link Mapper} paired with this record's class, if any.\n * @since 3.0.0\n */\n _mapper () {\n const mapper = this.constructor.mapper\n if (!mapper) {\n throw utils.err(`${DOMAIN}#_mapper`, '')(404, 'mapper')\n }\n return mapper\n },\n\n /**\n * Lifecycle hook.\n *\n * @method Record#afterLoadRelations\n * @param {string[]} relations The `relations` argument passed to {@link Record#loadRelations}.\n * @param {object} opts The `opts` argument passed to {@link Record#loadRelations}.\n * @since 3.0.0\n */\n afterLoadRelations () {},\n\n /**\n * Lifecycle hook.\n *\n * @method Record#beforeLoadRelations\n * @param {string[]} relations The `relations` argument passed to {@link Record#loadRelations}.\n * @param {object} opts The `opts` argument passed to {@link Record#loadRelations}.\n * @since 3.0.0\n */\n beforeLoadRelations () {},\n\n /**\n * Return the change history of this record since it was instantiated or\n * {@link Record#commit} was called.\n *\n * @method Record#changeHistory\n * @since 3.0.0\n */\n changeHistory () {\n return (this._get('history') || []).slice()\n },\n\n /**\n * Return changes to this record since it was instantiated or\n * {@link Record#commit} was called.\n *\n * @example Record#changes\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * store.defineMapper('user');\n * const user = store.createRecord('user');\n * console.log('user changes: ' + JSON.stringify(user.changes()));\n * user.name = 'John';\n * console.log('user changes: ' + JSON.stringify(user.changes()));\n *\n * @method Record#changes\n * @param [opts] Configuration options.\n * @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function.\n * @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore.\n * @returns {Object} Object describing the changes to this record since it was\n * instantiated or its {@link Record#commit} method was last called.\n * @since 3.0.0\n */\n changes (opts) {\n opts || (opts = {})\n return utils.diffObjects(typeof this.toJSON === 'function' ? this.toJSON(opts) : this, this._get('previous'), opts)\n },\n\n /**\n * Make the record's current in-memory state it's only state, with any\n * previous property values being set to current values.\n *\n * @example Record#commit\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * store.defineMapper('user');\n * const user = store.createRecord('user');\n * console.log('user hasChanges: ' + user.hasChanges());\n * user.name = 'John';\n * console.log('user hasChanges: ' + user.hasChanges());\n * user.commit();\n * console.log('user hasChanges: ' + user.hasChanges());\n *\n * @method Record#commit\n * @param {object} [opts] Configuration options. Passed to {@link Record#toJSON}.\n * @since 3.0.0\n */\n commit (opts) {\n this._set('changed') // unset\n this._set('changing', false)\n this._set('history', []) // clear history\n this._set('previous', this.toJSON(opts))\n },\n\n /**\n * Call {@link Mapper#destroy} using this record's primary key.\n *\n * @example\n * import { Container } from 'js-data';\n * import { RethinkDBAdapter } from 'js-data-rethinkdb';\n *\n * const store = new Container();\n * store.registerAdapter('rethink', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('user');\n * store.find('user', 1234).then((user) => {\n * console.log(user.id); // 1234\n *\n * // Destroy this user from the database\n * return user.destroy();\n * });\n *\n * @method Record#destroy\n * @param {object} [opts] Configuration options passed to {@link Mapper#destroy}.\n * @returns {Promise} The result of calling {@link Mapper#destroy} with the\n * primary key of this record.\n * @since 3.0.0\n */\n destroy (opts) {\n opts || (opts = {})\n const mapper = this._mapper()\n return superMethod(mapper, 'destroy')(utils.get(this, mapper.idAttribute), opts)\n },\n\n /**\n * Return the value at the given path for this instance.\n *\n * @example Record#get\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user');\n *\n * const user = store.createRecord('user', { name: 'Bob' });\n * console.log('user.get(\"name\"): ' + user.get('name'));\n *\n * @method Record#get\n * @param {string} key Path of value to retrieve.\n * @returns {*} Value at path.\n * @since 3.0.0\n */\n 'get' (key) {\n return utils.get(this, key)\n },\n\n /**\n * Return whether this record has changed since it was instantiated or\n * {@link Record#commit} was called.\n *\n * @example Record#hasChanges\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user');\n * const user = store.createRecord('user');\n * console.log('user hasChanges: ' + user.hasChanges());\n * user.name = 'John';\n * console.log('user hasChanges: ' + user.hasChanges());\n * user.commit();\n * console.log('user hasChanges: ' + user.hasChanges());\n *\n * @method Record#hasChanges\n * @param [opts] Configuration options.\n * @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function.\n * @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore.\n * @returns {boolean} Return whether the record has changed since it was\n * instantiated or since its {@link Record#commit} method was called.\n * @since 3.0.0\n */\n hasChanges (opts) {\n const quickHasChanges = !!(this._get('changed') || []).length\n return quickHasChanges || utils.areDifferent(typeof this.toJSON === 'function' ? this.toJSON(opts) : this, this._get('previous'), opts)\n },\n\n /**\n * Return whether the record is unsaved. Records that have primary keys are\n * considered \"saved\". Records without primary keys are considered \"unsaved\".\n *\n * @example Record#isNew\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user');\n * const user = store.createRecord('user', {\n * id: 1234\n * });\n * const user2 = store.createRecord('user');\n * console.log('user isNew: ' + user.isNew()); // false\n * console.log('user2 isNew: ' + user2.isNew()); // true\n *\n * @method Record#isNew\n * @returns {boolean} Whether the record is unsaved.\n * @since 3.0.0\n */\n isNew (opts) {\n return utils.get(this, this._mapper().idAttribute) === undefined\n },\n\n /**\n * Return whether the record in its current state passes validation.\n *\n * @example Record#isValid\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user', {\n * schema: {\n * properties: {\n * name: { type: 'string' }\n * }\n * }\n * });\n * const user = store.createRecord('user', {\n * name: 1234\n * }, {\n * noValidate: true // this allows us to put the record into an invalid state\n * });\n * console.log('user isValid: ' + user.isValid());\n * user.name = 'John';\n * console.log('user isValid: ' + user.isValid());\n *\n * @method Record#isValid\n * @param {object} [opts] Configuration options. Passed to {@link Mapper#validate}.\n * @returns {boolean} Whether the record in its current state passes\n * validation.\n * @since 3.0.0\n */\n isValid (opts) {\n return !this._mapper().validate(this, opts)\n },\n\n removeInverseRelation (currentParent, id, inverseDef, idAttribute) {\n if (inverseDef.type === hasOneType) {\n safeSetLink(currentParent, inverseDef.localField, undefined)\n } else if (inverseDef.type === hasManyType) {\n // e.g. remove comment from otherPost.comments\n const children = utils.get(currentParent, inverseDef.localField)\n if (id === undefined) {\n utils.remove(children, (child) => child === this)\n } else {\n utils.remove(children, (child) => child === this || id === utils.get(child, idAttribute))\n }\n }\n },\n\n setupInverseRelation (record, id, inverseDef, idAttribute) {\n // Update (set) inverse relation\n if (inverseDef.type === hasOneType) {\n // e.g. someUser.profile = profile\n safeSetLink(record, inverseDef.localField, this)\n } else if (inverseDef.type === hasManyType) {\n // e.g. add comment to somePost.comments\n const children = utils.get(record, inverseDef.localField)\n if (id === undefined) {\n utils.noDupeAdd(children, this, (child) => child === this)\n } else {\n utils.noDupeAdd(children, this, (child) => child === this || id === utils.get(child, idAttribute))\n }\n }\n },\n\n /**\n * Lazy load relations of this record, to be attached to the record once their\n * loaded.\n *\n * @example\n * import { Container } from 'js-data';\n * import { RethinkDBAdapter } from 'js-data-rethinkdb';\n *\n * const store = new Container();\n * store.registerAdapter('rethink', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('user', {\n * relations: {\n * hasMany: {\n * post: {\n * localField: 'posts',\n * foreignKey: 'user_id'\n * }\n * }\n * }\n * });\n * store.defineMapper('post', {\n * relations: {\n * belongsTo: {\n * user: {\n * localField: 'user',\n * foreignKey: 'user_id'\n * }\n * }\n * }\n * });\n * store.find('user', 1234).then((user) => {\n * console.log(user.id); // 1234\n *\n * // Load the user's post relations\n * return user.loadRelations(['post']);\n * }).then((user) => {\n * console.log(user.posts); // [{...}, {...}, ...]\n * });\n *\n * @method Record#loadRelations\n * @param {string[]} [relations] List of relations to load. Can use localField\n * names or Mapper names to pick relations.\n * @param {object} [opts] Configuration options.\n * @returns {Promise} Resolves with the record, with the loaded relations now\n * attached.\n * @since 3.0.0\n */\n loadRelations (relations, opts) {\n let op\n const mapper = this._mapper()\n\n // Default values for arguments\n relations || (relations = [])\n if (utils.isString(relations)) {\n relations = [relations]\n }\n opts || (opts = {})\n opts.with = relations\n\n // Fill in \"opts\" with the Model's configuration\n utils._(opts, mapper)\n opts.adapter = mapper.getAdapterName(opts)\n\n // beforeLoadRelations lifecycle hook\n op = opts.op = 'beforeLoadRelations'\n return utils.resolve(this[op](relations, opts)).then(() => {\n // Now delegate to the adapter\n op = opts.op = 'loadRelations'\n mapper.dbg(op, this, relations, opts)\n let tasks = []\n let task\n utils.forEachRelation(mapper, opts, (def, optsCopy) => {\n const relatedMapper = def.getRelation()\n optsCopy.raw = false\n if (utils.isFunction(def.load)) {\n task = def.load(mapper, def, this, opts)\n } else if (def.type === 'hasMany' || def.type === 'hasOne') {\n if (def.foreignKey) {\n task = superMethod(relatedMapper, 'findAll')({\n [def.foreignKey]: utils.get(this, mapper.idAttribute)\n }, optsCopy).then(function (relatedData) {\n if (def.type === 'hasOne') {\n return relatedData.length ? relatedData[0] : undefined\n }\n return relatedData\n })\n } else if (def.localKeys) {\n task = superMethod(relatedMapper, 'findAll')({\n where: {\n [relatedMapper.idAttribute]: {\n 'in': utils.get(this, def.localKeys)\n }\n }\n })\n } else if (def.foreignKeys) {\n task = superMethod(relatedMapper, 'findAll')({\n where: {\n [def.foreignKeys]: {\n 'contains': utils.get(this, mapper.idAttribute)\n }\n }\n }, opts)\n }\n } else if (def.type === 'belongsTo') {\n const key = utils.get(this, def.foreignKey)\n if (utils.isSorN(key)) {\n task = superMethod(relatedMapper, 'find')(key, optsCopy)\n }\n }\n if (task) {\n task = task.then((relatedData) => {\n def.setLocalField(this, relatedData)\n })\n tasks.push(task)\n }\n })\n return Promise.all(tasks)\n }).then(() => {\n // afterLoadRelations lifecycle hook\n op = opts.op = 'afterLoadRelations'\n return utils.resolve(this[op](relations, opts)).then(() => this)\n })\n },\n\n /**\n * Return the properties with which this record was instantiated.\n *\n * @example Record#previous\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user');\n * const user = store.createRecord('user', {\n * name: 'William'\n * });\n * console.log('user previous: ' + JSON.stringify(user.previous()));\n * user.name = 'Bob';\n * console.log('user previous: ' + JSON.stringify(user.previous()));\n * user.commit();\n * console.log('user previous: ' + JSON.stringify(user.previous()));\n *\n * @method Record#previous\n * @param {string} [key] If specified, return just the initial value of the\n * given key.\n * @returns {Object} The initial properties of this record.\n * @since 3.0.0\n */\n previous (key) {\n if (key) {\n return this._get(`previous.${key}`)\n }\n return this._get('previous')\n },\n\n /**\n * Revert changes to this record back to the properties it had when it was\n * instantiated.\n *\n * @example Record#revert\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user');\n * const user = store.createRecord('user', {\n * name: 'William'\n * });\n * console.log('user: ' + JSON.stringify(user));\n * user.name = 'Bob';\n * console.log('user: ' + JSON.stringify(user));\n * user.revert();\n * console.log('user: ' + JSON.stringify(user));\n *\n * @method Record#revert\n * @param {object} [opts] Configuration options.\n * @param {string[]} [opts.preserve] Array of strings or Regular Expressions\n * denoting properties that should not be reverted.\n * @since 3.0.0\n */\n revert (opts) {\n const previous = this._get('previous')\n opts || (opts = {})\n opts.preserve || (opts.preserve = [])\n utils.forOwn(this, (value, key) => {\n if (key !== this._mapper().idAttribute && !previous.hasOwnProperty(key) && this.hasOwnProperty(key) && opts.preserve.indexOf(key) === -1) {\n delete this[key]\n }\n })\n utils.forOwn(previous, (value, key) => {\n if (opts.preserve.indexOf(key) === -1) {\n this[key] = value\n }\n })\n this.commit()\n },\n\n /**\n * Delegates to {@link Mapper#create} or {@link Mapper#update}.\n *\n * @example\n * import { Container } from 'js-data';\n * import { RethinkDBAdapter } from 'js-data-rethinkdb';\n *\n * const store = new Container();\n * store.registerAdapter('rethink', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('session');\n * const session = store.createRecord('session', { topic: 'Node.js' });\n *\n * // Create a new record in the database\n * session.save().then(() => {\n * console.log(session.id); // 1234\n *\n * session.skill_level = 'beginner';\n *\n * // Update the record in the database\n * return session.save();\n * });\n *\n * @method Record#save\n * @param {object} [opts] Configuration options. See {@link Mapper#create} and\n * {@link Mapper#update}.\n * @param {boolean} [opts.changesOnly] Equality function. Default uses `===`.\n * @param {Function} [opts.equalsFn] Passed to {@link Record#changes} when\n * `opts.changesOnly` is `true`.\n * @param {array} [opts.ignore] Passed to {@link Record#changes} when\n * `opts.changesOnly` is `true`.\n * @returns {Promise} The result of calling {@link Mapper#create} or\n * {@link Mapper#update}.\n * @since 3.0.0\n */\n save (opts) {\n opts || (opts = {})\n const mapper = this._mapper()\n const id = utils.get(this, mapper.idAttribute)\n let props = this\n\n const postProcess = (result) => {\n const record = opts.raw ? result.data : result\n if (record) {\n utils.deepMixIn(this, record)\n this.commit()\n }\n return result\n }\n\n if (id === undefined) {\n return superMethod(mapper, 'create')(props, opts).then(postProcess)\n }\n if (opts.changesOnly) {\n const changes = this.changes(opts)\n props = {}\n utils.fillIn(props, changes.added)\n utils.fillIn(props, changes.changed)\n }\n return superMethod(mapper, 'update')(id, props, opts).then(postProcess)\n },\n\n /**\n * Set the value for a given key, or the values for the given keys if \"key\" is\n * an object. Triggers change events on those properties that have `track: true`\n * in {@link Mapper#schema}.\n *\n * @example Record#set\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user');\n *\n * const user = store.createRecord('user');\n * console.log('user: ' + JSON.stringify(user));\n *\n * user.set('name', 'Bob');\n * console.log('user: ' + JSON.stringify(user));\n *\n * user.set({ age: 30, role: 'admin' });\n * console.log('user: ' + JSON.stringify(user));\n *\n * @fires Record#change\n * @method Record#set\n * @param {(string|Object)} key Key to set or hash of key-value pairs to set.\n * @param {*} [value] Value to set for the given key.\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.silent=false] Whether to trigger change events.\n * @since 3.0.0\n */\n 'set' (key, value, opts) {\n if (utils.isObject(key)) {\n opts = value\n }\n opts || (opts = {})\n if (opts.silent) {\n this._set('silent', true)\n }\n utils.set(this, key, value)\n if (!this._get('eventId')) {\n this._set('silent') // unset\n }\n },\n\n /**\n * Return a plain object representation of this record. If the class from\n * which this record was created has a Mapper, then {@link Mapper#toJSON} will\n * be called with this record instead.\n *\n * @example Record#toJSON\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user', {\n * schema: {\n * properties: {\n * name: { type: 'string' }\n * }\n * }\n * });\n *\n * const user = store.createRecord('user', {\n * name: 'John',\n * $$hashKey: '1234'\n * });\n * console.log('user: ' + JSON.stringify(user.toJSON()));\n *\n * @method Record#toJSON\n * @param {object} [opts] Configuration options.\n * @param {string[]} [opts.with] Array of relation names or relation fields\n * to include in the representation. Only available as an option if the class\n * from which this record was created has a Mapper and this record resides in\n * an instance of {@link DataStore}.\n * @returns {Object} Plain object representation of this record.\n * @since 3.0.0\n */\n toJSON (opts) {\n const mapper = this.constructor.mapper\n if (mapper) {\n return mapper.toJSON(this, opts)\n } else {\n const json = {}\n utils.forOwn(this, (prop, key) => {\n json[key] = utils.plainCopy(prop)\n })\n return json\n }\n },\n\n /**\n * Unset the value for a given key. Triggers change events on those properties\n * that have `track: true` in {@link Mapper#schema}.\n *\n * @example Record#unset\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user');\n *\n * const user = store.createRecord('user', {\n * name: 'John'\n * });\n * console.log('user: ' + JSON.stringify(user));\n *\n * user.unset('name');\n * console.log('user: ' + JSON.stringify(user));\n *\n * @method Record#unset\n * @param {string} key Key to unset.\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.silent=false] Whether to trigger change events.\n * @since 3.0.0\n */\n unset (key, opts) {\n this.set(key, undefined, opts)\n },\n\n /**\n * Validate this record based on its current properties.\n *\n * @example Record#validate\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n * const store = new Container();\n * store.defineMapper('user', {\n * schema: {\n * properties: {\n * name: { type: 'string' }\n * }\n * }\n * });\n * const user = store.createRecord('user', {\n * name: 1234\n * }, {\n * noValidate: true // this allows us to put the record into an invalid state\n * });\n * console.log('user validation: ' + JSON.stringify(user.validate()));\n * user.name = 'John';\n * console.log('user validation: ' + user.validate());\n *\n * @method Record#validate\n * @param {object} [opts] Configuration options. Passed to {@link Mapper#validate}.\n * @returns {*} Array of errors or `undefined` if no errors.\n * @since 3.0.0\n */\n validate (opts) {\n return this._mapper().validate(this, opts)\n }\n}, {\n creatingPath,\n noValidatePath,\n keepChangeHistoryPath,\n previousPath\n})\n\n/**\n * Allow records to emit events.\n *\n * An record's registered listeners are stored in the record's private data.\n */\nutils.eventify(\n Record.prototype,\n function () {\n return this._get('events')\n },\n function (value) {\n this._set('events', value)\n }\n)\n\n/**\n * Fired when a record changes. Only works for records that have tracked fields.\n * See {@link Record~changeListener} on how to listen for this event.\n *\n * @event Record#change\n * @see Record~changeListener\n */\n\n/**\n * Callback signature for the {@link Record#event:change} event.\n *\n * @example\n * function onChange (record, changes) {\n * // do something\n * }\n * record.on('change', onChange);\n *\n * @callback Record~changeListener\n * @param {Record} The Record that changed.\n * @param {object} The changes.\n * @see Record#event:change\n * @since 3.0.0\n */\n\n/**\n * Create a subclass of this Record:\n * @example Record.extend\n * const JSData = require('js-data');\n * const { Record } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomRecordClass extends Record {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customRecord = new CustomRecordClass();\n * console.log(customRecord.foo());\n * console.log(CustomRecordClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherRecordClass = Record.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherRecord = new OtherRecordClass();\n * console.log(otherRecord.foo());\n * console.log(OtherRecordClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherRecordClass () {\n * Record.call(this);\n * this.created_at = new Date().getTime();\n * }\n * Record.extend({\n * constructor: AnotherRecordClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const anotherRecord = new AnotherRecordClass();\n * console.log(anotherRecord.created_at);\n * console.log(anotherRecord.foo());\n * console.log(AnotherRecordClass.beep());\n *\n * @method Record.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this Record class.\n * @since 3.0.0\n */\n","export function sort (a, b, hashCode) {\n // Short-circuit comparison if a and b are strictly equal\n // This is absolutely necessary for indexed objects that\n // don't have the idAttribute field\n if (a === b) {\n return 0\n }\n if (hashCode) {\n a = hashCode(a)\n b = hashCode(b)\n }\n if ((a === null && b === null) || (a === undefined && b === undefined)) {\n return -1\n }\n\n if (a === null || a === undefined) {\n return -1\n }\n\n if (b === null || b === undefined) {\n return 1\n }\n\n if (a < b) {\n return -1\n }\n\n if (a > b) {\n return 1\n }\n\n return 0\n}\n\nexport function insertAt (array, index, value) {\n array.splice(index, 0, value)\n return array\n}\n\nexport function removeAt (array, index) {\n array.splice(index, 1)\n return array\n}\n\nexport function binarySearch (array, value, field) {\n let lo = 0\n let hi = array.length\n let compared\n let mid\n\n while (lo < hi) {\n mid = ((lo + hi) / 2) | 0\n compared = sort(value, array[mid], field)\n if (compared === 0) {\n return {\n found: true,\n index: mid\n }\n } else if (compared < 0) {\n hi = mid\n } else {\n lo = mid + 1\n }\n }\n\n return {\n found: false,\n index: hi\n }\n}\n","// Copyright (c) 2015, InternalFX.\n\n// Permission to use, copy, modify, and/or distribute this software for any purpose with or\n// without fee is hereby granted, provided that the above copyright notice and this permission\n// notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO\n// THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT\n// SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR\n// ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION\n// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE\n// USE OR PERFORMANCE OF THIS SOFTWARE.\n\n// Modifications\n// Copyright 2015-2016 Jason Dobry\n//\n// Summary of modifications:\n// Reworked dependencies so as to re-use code already in js-data\n// Removed unused code\nimport utils from '../../src/utils'\nimport {binarySearch, insertAt, removeAt} from './_utils'\n\nexport default function Index (fieldList, opts) {\n utils.classCallCheck(this, Index)\n fieldList || (fieldList = [])\n\n if (!utils.isArray(fieldList)) {\n throw new Error('fieldList must be an array.')\n }\n\n opts || (opts = {})\n this.fieldList = fieldList\n this.fieldGetter = opts.fieldGetter\n this.hashCode = opts.hashCode\n this.isIndex = true\n this.keys = []\n this.values = []\n}\n\nutils.addHiddenPropsToTarget(Index.prototype, {\n 'set' (keyList, value) {\n if (!utils.isArray(keyList)) {\n keyList = [keyList]\n }\n\n let key = keyList.shift() || undefined\n let pos = binarySearch(this.keys, key)\n\n if (keyList.length === 0) {\n if (pos.found) {\n let dataLocation = binarySearch(this.values[pos.index], value, this.hashCode)\n if (!dataLocation.found) {\n insertAt(this.values[pos.index], dataLocation.index, value)\n }\n } else {\n insertAt(this.keys, pos.index, key)\n insertAt(this.values, pos.index, [value])\n }\n } else {\n if (pos.found) {\n this.values[pos.index].set(keyList, value)\n } else {\n insertAt(this.keys, pos.index, key)\n let newIndex = new Index([], { hashCode: this.hashCode })\n newIndex.set(keyList, value)\n insertAt(this.values, pos.index, newIndex)\n }\n }\n },\n\n 'get' (keyList) {\n if (!utils.isArray(keyList)) {\n keyList = [keyList]\n }\n\n let key = keyList.shift() || undefined\n let pos = binarySearch(this.keys, key)\n\n if (keyList.length === 0) {\n if (pos.found) {\n if (this.values[pos.index].isIndex) {\n return this.values[pos.index].getAll()\n } else {\n return this.values[pos.index].slice()\n }\n } else {\n return []\n }\n } else {\n if (pos.found) {\n return this.values[pos.index].get(keyList)\n } else {\n return []\n }\n }\n },\n\n getAll (opts) {\n opts || (opts = {})\n let results = []\n const values = this.values\n if (opts.order === 'desc') {\n for (let i = values.length - 1; i >= 0; i--) {\n const value = values[i]\n if (value.isIndex) {\n results = results.concat(value.getAll(opts))\n } else {\n results = results.concat(value)\n }\n }\n } else {\n for (let i = 0; i < values.length; i++) {\n const value = values[i]\n if (value.isIndex) {\n results = results.concat(value.getAll(opts))\n } else {\n results = results.concat(value)\n }\n }\n }\n return results\n },\n\n visitAll (cb, thisArg) {\n this.values.forEach(function (value) {\n if (value.isIndex) {\n value.visitAll(cb, thisArg)\n } else {\n value.forEach(cb, thisArg)\n }\n })\n },\n\n between (leftKeys, rightKeys, opts) {\n opts || (opts = {})\n if (!utils.isArray(leftKeys)) {\n leftKeys = [leftKeys]\n }\n if (!utils.isArray(rightKeys)) {\n rightKeys = [rightKeys]\n }\n utils.fillIn(opts, {\n leftInclusive: true,\n rightInclusive: false,\n limit: undefined,\n offset: 0\n })\n\n let results = this._between(leftKeys, rightKeys, opts)\n\n if (opts.limit) {\n return results.slice(opts.offset, opts.limit + opts.offset)\n } else {\n return results.slice(opts.offset)\n }\n },\n\n _between (leftKeys, rightKeys, opts) {\n let results = []\n\n let leftKey = leftKeys.shift()\n let rightKey = rightKeys.shift()\n\n let pos\n\n if (leftKey !== undefined) {\n pos = binarySearch(this.keys, leftKey)\n } else {\n pos = {\n found: false,\n index: 0\n }\n }\n\n if (leftKeys.length === 0) {\n if (pos.found && opts.leftInclusive === false) {\n pos.index += 1\n }\n\n for (let i = pos.index; i < this.keys.length; i += 1) {\n if (rightKey !== undefined) {\n if (opts.rightInclusive) {\n if (this.keys[i] > rightKey) { break }\n } else {\n if (this.keys[i] >= rightKey) { break }\n }\n }\n\n if (this.values[i].isIndex) {\n results = results.concat(this.values[i].getAll())\n } else {\n results = results.concat(this.values[i])\n }\n\n if (opts.limit) {\n if (results.length >= (opts.limit + opts.offset)) {\n break\n }\n }\n }\n } else {\n for (let i = pos.index; i < this.keys.length; i += 1) {\n let currKey = this.keys[i]\n if (currKey > rightKey) { break }\n\n if (this.values[i].isIndex) {\n if (currKey === leftKey) {\n results = results.concat(this.values[i]._between(utils.copy(leftKeys), rightKeys.map(function () { return undefined }), opts))\n } else if (currKey === rightKey) {\n results = results.concat(this.values[i]._between(leftKeys.map(function () { return undefined }), utils.copy(rightKeys), opts))\n } else {\n results = results.concat(this.values[i].getAll())\n }\n } else {\n results = results.concat(this.values[i])\n }\n\n if (opts.limit) {\n if (results.length >= (opts.limit + opts.offset)) {\n break\n }\n }\n }\n }\n\n if (opts.limit) {\n return results.slice(0, opts.limit + opts.offset)\n } else {\n return results\n }\n },\n\n peek () {\n if (this.values.length) {\n if (this.values[0].isIndex) {\n return this.values[0].peek()\n } else {\n return this.values[0]\n }\n }\n return []\n },\n\n clear () {\n this.keys = []\n this.values = []\n },\n\n insertRecord (data) {\n let keyList = this.fieldList.map(function (field) {\n if (utils.isFunction(field)) {\n return field(data) || undefined\n } else {\n return data[field] || undefined\n }\n })\n this.set(keyList, data)\n },\n\n removeRecord (data) {\n let removed\n const isUnique = this.hashCode(data) !== undefined\n this.values.forEach((value, i) => {\n if (value.isIndex) {\n if (value.removeRecord(data)) {\n if (value.keys.length === 0) {\n removeAt(this.keys, i)\n removeAt(this.values, i)\n }\n removed = true\n return false\n }\n } else {\n let dataLocation = {}\n if (this.keys[i] === undefined || !isUnique) {\n for (let j = value.length - 1; j >= 0; j--) {\n if (value[j] === data) {\n dataLocation = {\n found: true,\n index: j\n }\n break\n }\n }\n } else if (isUnique) {\n dataLocation = binarySearch(value, data, this.hashCode)\n }\n if (dataLocation.found) {\n removeAt(value, dataLocation.index)\n if (value.length === 0) {\n removeAt(this.keys, i)\n removeAt(this.values, i)\n }\n removed = true\n return false\n }\n }\n })\n return removed ? data : undefined\n },\n\n updateRecord (data) {\n const removed = this.removeRecord(data)\n if (removed !== undefined) {\n this.insertRecord(data)\n }\n }\n})\n","import utils from './utils'\nimport Component from './Component'\nimport Query from './Query'\nimport Record from './Record'\nimport Index from '../lib/mindex/index'\n\nconst { noValidatePath } = Record\n\nconst DOMAIN = 'Collection'\n\nconst COLLECTION_DEFAULTS = {\n /**\n * Whether to call {@link Record#commit} on records that are added to the\n * collection and already exist in the collection.\n *\n * @name Collection#commitOnMerge\n * @type {boolean}\n * @default true\n */\n commitOnMerge: true,\n\n /**\n * Whether record events should bubble up and be emitted by the collection.\n *\n * @name Collection#emitRecordEvents\n * @type {boolean}\n * @default true\n */\n emitRecordEvents: true,\n\n /**\n * Field to be used as the unique identifier for records in this collection.\n * Defaults to `\"id\"` unless {@link Collection#mapper} is set, in which case\n * this will default to {@link Mapper#idAttribute}.\n *\n * @name Collection#idAttribute\n * @type {string}\n * @default \"id\"\n */\n idAttribute: 'id',\n\n /**\n * What to do when inserting a record into this Collection that shares a\n * primary key with a record already in this Collection.\n *\n * Possible values:\n * merge\n * replace\n * skip\n *\n * Merge:\n *\n * Recursively shallow copy properties from the new record onto the existing\n * record.\n *\n * Replace:\n *\n * Shallow copy top-level properties from the new record onto the existing\n * record. Any top-level own properties of the existing record that are _not_\n * on the new record will be removed.\n *\n * Skip:\n *\n * Ignore new record, keep existing record.\n *\n * @name Collection#onConflict\n * @type {string}\n * @default \"merge\"\n */\n onConflict: 'merge'\n}\n\n/**\n * An ordered set of {@link Record} instances.\n *\n * @example Collection#constructor\n * // import { Collection, Record } from 'js-data';\n * const JSData = require('js-data');\n * const {Collection, Record} = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const user1 = new Record({ id: 1 });\n * const user2 = new Record({ id: 2 });\n * const UserCollection = new Collection([user1, user2]);\n * console.log(UserCollection.get(1) === user1);\n *\n * @class Collection\n * @extends Component\n * @param {array} [records] Initial set of records to insert into the\n * collection.\n * @param {object} [opts] Configuration options.\n * @param {string} [opts.commitOnMerge] See {@link Collection#commitOnMerge}.\n * @param {string} [opts.idAttribute] See {@link Collection#idAttribute}.\n * @param {string} [opts.onConflict=\"merge\"] See {@link Collection#onConflict}.\n * @param {string} [opts.mapper] See {@link Collection#mapper}.\n * @since 3.0.0\n */\nfunction Collection (records, opts) {\n utils.classCallCheck(this, Collection)\n Component.call(this, opts)\n\n if (records && !utils.isArray(records)) {\n opts = records\n records = []\n }\n if (utils.isString(opts)) {\n opts = { idAttribute: opts }\n }\n\n // Default values for arguments\n records || (records = [])\n opts || (opts = {})\n\n Object.defineProperties(this, {\n /**\n * Default Mapper for this collection. Optional. If a Mapper is provided, then\n * the collection will use the {@link Mapper#idAttribute} setting, and will\n * wrap records in {@link Mapper#recordClass}.\n *\n * @example Collection#mapper\n * const JSData = require('js-data');\n * const {Collection, Mapper} = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * class MyMapperClass extends Mapper {\n * foo () { return 'bar'; }\n * }\n * const myMapper = new MyMapperClass({ name: 'myMapper' });\n * const collection = new Collection(null, { mapper: myMapper });\n *\n * @name Collection#mapper\n * @type {Mapper}\n * @default null\n * @since 3.0.0\n */\n mapper: {\n value: undefined,\n writable: true\n },\n // Query class used by this collection\n queryClass: {\n value: undefined,\n writable: true\n }\n })\n\n // Apply user-provided configuration\n utils.fillIn(this, opts)\n // Fill in any missing options with the defaults\n utils.fillIn(this, utils.copy(COLLECTION_DEFAULTS))\n\n if (!this.queryClass) {\n this.queryClass = Query\n }\n\n const idAttribute = this.recordId()\n\n Object.defineProperties(this, {\n /**\n * The main index, which uses @{link Collection#recordId} as the key.\n *\n * @name Collection#index\n * @type {Index}\n */\n index: {\n value: new Index([idAttribute], {\n hashCode (obj) {\n return utils.get(obj, idAttribute)\n }\n })\n },\n\n /**\n * Object that holds the secondary indexes of this collection.\n *\n * @name Collection#indexes\n * @type {Object.}\n */\n indexes: {\n value: {}\n }\n })\n\n // Insert initial data into the collection\n if (utils.isObject(records) || (utils.isArray(records) && records.length)) {\n this.add(records)\n }\n}\n\nexport default Component.extend({\n constructor: Collection,\n\n /**\n * Used to bind to events emitted by records in this Collection.\n *\n * @method Collection#_onRecordEvent\n * @since 3.0.0\n * @private\n * @param {...*} [arg] Args passed to {@link Collection#emit}.\n */\n _onRecordEvent (...args) {\n if (this.emitRecordEvents) {\n this.emit(...args)\n }\n },\n\n /**\n * Insert the provided record or records.\n *\n * If a record is already in the collection then the provided record will\n * either merge with or replace the existing record based on the value of the\n * `onConflict` option.\n *\n * The collection's secondary indexes will be updated as each record is\n * visited.\n *\n * @method Collection#add\n * @since 3.0.0\n * @param {(Object|Object[]|Record|Record[])} data The record or records to insert.\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.commitOnMerge=true] See {@link Collection#commitOnMerge}.\n * @param {boolean} [opts.noValidate] See {@link Record#noValidate}.\n * @param {string} [opts.onConflict] See {@link Collection#onConflict}.\n * @returns {(Object|Object[]|Record|Record[])} The added record or records.\n */\n add (records, opts) {\n // Default values for arguments\n opts || (opts = {})\n\n // Fill in \"opts\" with the Collection's configuration\n utils._(opts, this)\n records = this.beforeAdd(records, opts) || records\n\n // Track whether just one record or an array of records is being inserted\n let singular = false\n const idAttribute = this.recordId()\n if (!utils.isArray(records)) {\n if (utils.isObject(records)) {\n records = [records]\n singular = true\n } else {\n throw utils.err(`${DOMAIN}#add`, 'records')(400, 'object or array', records)\n }\n }\n\n // Map the provided records to existing records.\n // New records will be inserted. If any records map to existing records,\n // they will be merged into the existing records according to the onConflict\n // option.\n records = records.map((record) => {\n let id = this.recordId(record)\n // Grab existing record if there is one\n const existing = id === undefined ? id : this.get(id)\n // If the currently visited record is just a reference to an existing\n // record, then there is nothing to be done. Exit early.\n if (record === existing) {\n return existing\n }\n\n if (existing) {\n // Here, the currently visited record corresponds to a record already\n // in the collection, so we need to merge them\n const onConflict = opts.onConflict || this.onConflict\n if (onConflict !== 'merge' && onConflict !== 'replace' && onConflict !== 'skip') {\n throw utils.err(`${DOMAIN}#add`, 'opts.onConflict')(400, 'one of (merge, replace, skip)', onConflict, true)\n }\n const existingNoValidate = existing._get(noValidatePath)\n if (opts.noValidate) {\n // Disable validation\n existing._set(noValidatePath, true)\n }\n if (onConflict === 'merge') {\n utils.deepMixIn(existing, record)\n } else if (onConflict === 'replace') {\n utils.forOwn(existing, (value, key) => {\n if (key !== idAttribute && record[key] === undefined) {\n existing[key] = undefined\n }\n })\n existing.set(record)\n } // else if(onConflict === 'skip'){ do nothing }\n\n if (opts.noValidate) {\n // Restore previous `noValidate` value\n existing._set(noValidatePath, existingNoValidate)\n }\n record = existing\n if (opts.commitOnMerge && utils.isFunction(record.commit)) {\n record.commit()\n }\n // Update all indexes in the collection\n this.updateIndexes(record)\n } else {\n // Here, the currently visted record does not correspond to any record\n // in the collection, so (optionally) instantiate this record and insert\n // it into the collection\n record = this.mapper ? this.mapper.createRecord(record, opts) : record\n this.index.insertRecord(record)\n utils.forOwn(this.indexes, function (index, name) {\n index.insertRecord(record)\n })\n if (record && utils.isFunction(record.on)) {\n record.on('all', this._onRecordEvent, this)\n }\n }\n return record\n })\n // Finally, return the inserted data\n const result = singular ? records[0] : records\n if (!opts.silent) {\n this.emit('add', result)\n }\n return this.afterAdd(records, opts, result) || result\n },\n\n /**\n * Lifecycle hook called by {@link Collection#add}. If this method returns a\n * value then {@link Collection#add} will return that same value.\n *\n * @method Collection#method\n * @since 3.0.0\n * @param {(Object|Object[]|Record|Record[])} result The record or records\n * that were added to this Collection by {@link Collection#add}.\n * @param {object} opts The `opts` argument passed to {@link Collection#add}.\n */\n afterAdd () {},\n\n /**\n * Lifecycle hook called by {@link Collection#remove}. If this method returns\n * a value then {@link Collection#remove} will return that same value.\n *\n * @method Collection#afterRemove\n * @since 3.0.0\n * @param {(string|number)} id The `id` argument passed to {@link Collection#remove}.\n * @param {object} opts The `opts` argument passed to {@link Collection#remove}.\n * @param {object} record The result that will be returned by {@link Collection#remove}.\n */\n afterRemove () {},\n\n /**\n * Lifecycle hook called by {@link Collection#removeAll}. If this method\n * returns a value then {@link Collection#removeAll} will return that same\n * value.\n *\n * @method Collection#afterRemoveAll\n * @since 3.0.0\n * @param {object} query The `query` argument passed to {@link Collection#removeAll}.\n * @param {object} opts The `opts` argument passed to {@link Collection#removeAll}.\n * @param {object} records The result that will be returned by {@link Collection#removeAll}.\n */\n afterRemoveAll () {},\n\n /**\n * Lifecycle hook called by {@link Collection#add}. If this method returns a\n * value then the `records` argument in {@link Collection#add} will be\n * re-assigned to the returned value.\n *\n * @method Collection#beforeAdd\n * @since 3.0.0\n * @param {(Object|Object[]|Record|Record[])} records The `records` argument passed to {@link Collection#add}.\n * @param {object} opts The `opts` argument passed to {@link Collection#add}.\n */\n beforeAdd () {},\n\n /**\n * Lifecycle hook called by {@link Collection#remove}.\n *\n * @method Collection#beforeRemove\n * @since 3.0.0\n * @param {(string|number)} id The `id` argument passed to {@link Collection#remove}.\n * @param {object} opts The `opts` argument passed to {@link Collection#remove}.\n */\n beforeRemove () {},\n\n /**\n * Lifecycle hook called by {@link Collection#removeAll}.\n *\n * @method Collection#beforeRemoveAll\n * @since 3.0.0\n * @param {object} query The `query` argument passed to {@link Collection#removeAll}.\n * @param {object} opts The `opts` argument passed to {@link Collection#removeAll}.\n */\n beforeRemoveAll () {},\n\n /**\n * Find all records between two boundaries.\n *\n * Shortcut for `collection.query().between(18, 30, { index: 'age' }).run()`\n *\n * @example\n * // Get all users ages 18 to 30\n * const users = collection.between(18, 30, { index: 'age' });\n *\n * @example\n * // Same as above\n * const users = collection.between([18], [30], { index: 'age' });\n *\n * @method Collection#between\n * @since 3.0.0\n * @param {array} leftKeys Keys defining the left boundary.\n * @param {array} rightKeys Keys defining the right boundary.\n * @param {object} [opts] Configuration options.\n * @param {string} [opts.index] Name of the secondary index to use in the\n * query. If no index is specified, the main index is used.\n * @param {boolean} [opts.leftInclusive=true] Whether to include records\n * on the left boundary.\n * @param {boolean} [opts.rightInclusive=false] Whether to include records\n * on the left boundary.\n * @param {boolean} [opts.limit] Limit the result to a certain number.\n * @param {boolean} [opts.offset] The number of resulting records to skip.\n * @returns {Object[]|Record[]} The result.\n */\n between (leftKeys, rightKeys, opts) {\n return this.query().between(leftKeys, rightKeys, opts).run()\n },\n\n /**\n * Create a new secondary index on the contents of the collection.\n *\n * @example\n * // Index users by age\n * collection.createIndex('age');\n *\n * @example\n * // Index users by status and role\n * collection.createIndex('statusAndRole', ['status', 'role']);\n *\n * @method Collection#createIndex\n * @since 3.0.0\n * @param {string} name The name of the new secondary index.\n * @param {string[]} [fieldList] Array of field names to use as the key or\n * compound key of the new secondary index. If no fieldList is provided, then\n * the name will also be the field that is used to index the collection.\n */\n createIndex (name, fieldList, opts) {\n if (utils.isString(name) && fieldList === undefined) {\n fieldList = [name]\n }\n opts || (opts = {})\n opts.hashCode || (opts.hashCode = (obj) => this.recordId(obj))\n const index = this.indexes[name] = new Index(fieldList, opts)\n this.index.visitAll(index.insertRecord, index)\n },\n\n /**\n * Find the record or records that match the provided query or pass the\n * provided filter function.\n *\n * Shortcut for `collection.query().filter(queryOrFn[, thisArg]).run()`\n *\n * @example Collection#filter\n * const JSData = require('js-data');\n * const { Collection } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const collection = new Collection([\n * { id: 1, status: 'draft', created_at_timestamp: new Date().getTime() }\n * ]);\n *\n * // Get the draft posts created less than three months ago\n * let posts = collection.filter({\n * where: {\n * status: {\n * '==': 'draft'\n * },\n * created_at_timestamp: {\n * '>=': (new Date().getTime() - (1000 \\* 60 \\* 60 \\* 24 \\* 30 \\* 3)) // 3 months ago\n * }\n * }\n * });\n * console.log(posts);\n *\n * // Use a custom filter function\n * posts = collection.filter((post) => post.id % 2 === 0);\n *\n * @method Collection#filter\n * @param {(Object|Function)} [queryOrFn={}] Selection query or filter\n * function.\n * @param {object} [thisArg] Context to which to bind `queryOrFn` if\n * `queryOrFn` is a function.\n * @returns {Array} The result.\n * @see query\n * @since 3.0.0\n */\n filter (query, thisArg) {\n return this.query().filter(query, thisArg).run()\n },\n\n /**\n * Iterate over all records.\n *\n * @example\n * collection.forEach(function (record) {\n * // do something\n * });\n *\n * @method Collection#forEach\n * @since 3.0.0\n * @param {Function} forEachFn Iteration function.\n * @param {*} [thisArg] Context to which to bind `forEachFn`.\n * @returns {Array} The result.\n */\n forEach (cb, thisArg) {\n this.index.visitAll(cb, thisArg)\n },\n\n /**\n * Get the record with the given id.\n *\n * @method Collection#get\n * @since 3.0.0\n * @param {(string|number)} id The primary key of the record to get.\n * @returns {(Object|Record)} The record with the given id.\n */\n get (id) {\n const instances = id === undefined ? [] : this.query().get(id).run()\n return instances.length ? instances[0] : undefined\n },\n\n /**\n * Find the record or records that match the provided keyLists.\n *\n * Shortcut for `collection.query().getAll(keyList1, keyList2, ...).run()`\n *\n * @example\n * // Get the posts where \"status\" is \"draft\" or \"inReview\"\n * const posts = collection.getAll('draft', 'inReview', { index: 'status' });\n *\n * @example\n * // Same as above\n * const posts = collection.getAll(['draft'], ['inReview'], { index: 'status' });\n *\n * @method Collection#getAll\n * @since 3.0.0\n * @param {...Array} [keyList] Provide one or more keyLists, and all\n * records matching each keyList will be retrieved. If no keyLists are\n * provided, all records will be returned.\n * @param {object} [opts] Configuration options.\n * @param {string} [opts.index] Name of the secondary index to use in the\n * query. If no index is specified, the main index is used.\n * @returns {Array} The result.\n */\n getAll (...args) {\n return this.query().getAll(...args).run()\n },\n\n /**\n * Return the index with the given name. If no name is provided, return the\n * main index. Throws an error if the specified index does not exist.\n *\n * @method Collection#getIndex\n * @since 3.0.0\n * @param {string} [name] The name of the index to retrieve.\n */\n getIndex (name) {\n const index = name ? this.indexes[name] : this.index\n if (!index) {\n throw utils.err(`${DOMAIN}#getIndex`, name)(404, 'index')\n }\n return index\n },\n\n /**\n * Limit the result.\n *\n * Shortcut for `collection.query().limit(maximumNumber).run()`\n *\n * @example\n * const posts = collection.limit(10);\n *\n * @method Collection#limit\n * @since 3.0.0\n * @param {number} num The maximum number of records to keep in the result.\n * @returns {Array} The result.\n */\n limit (num) {\n return this.query().limit(num).run()\n },\n\n /**\n * Apply a mapping function to all records.\n *\n * @example\n * const names = collection.map((user) => user.name);\n *\n * @method Collection#map\n * @since 3.0.0\n * @param {Function} mapFn Mapping function.\n * @param {*} [thisArg] Context to which to bind `mapFn`.\n * @returns {Array} The result of the mapping.\n */\n map (cb, thisArg) {\n const data = []\n this.index.visitAll(function (value) {\n data.push(cb.call(thisArg, value))\n })\n return data\n },\n\n /**\n * Return the result of calling the specified function on each record in this\n * collection's main index.\n *\n * @method Collection#mapCall\n * @since 3.0.0\n * @param {string} funcName Name of function to call\n * @parama {...*} [args] Remaining arguments to be passed to the function.\n * @returns {Array} The result.\n */\n mapCall (funcName, ...args) {\n const data = []\n this.index.visitAll(function (record) {\n data.push(record[funcName](...args))\n })\n return data\n },\n\n /**\n * Return all \"unsaved\" (not uniquely identifiable) records in this colleciton.\n *\n * @method Collection#prune\n * @param {object} [opts] Configuration options, passed to {@link Collection#removeAll}.\n * @since 3.0.0\n * @returns {Array} The removed records, if any.\n */\n prune (opts) {\n return this.removeAll(this.unsaved(), opts)\n },\n\n /**\n * Create a new query to be executed against the contents of the collection.\n * The result will be all or a subset of the contents of the collection.\n *\n * @example\n * // Grab page 2 of users between ages 18 and 30\n * collection.query()\n * .between(18, 30, { index: 'age' }) // between ages 18 and 30\n * .skip(10) // second page\n * .limit(10) // page size\n * .run();\n *\n * @method Collection#query\n * @since 3.0.0\n * @returns {Query} New query object.\n */\n query () {\n const Ctor = this.queryClass\n return new Ctor(this)\n },\n\n /**\n * Return the primary key of the given, or if no record is provided, return the\n * name of the field that holds the primary key of records in this Collection.\n *\n * @method Collection#recordId\n * @since 3.0.0\n * @param {(Object|Record)} [record] The record whose primary key is to be\n * returned.\n * @returns {(string|number)} Primary key or name of field that holds primary\n * key.\n */\n recordId (record) {\n if (record) {\n return utils.get(record, this.recordId())\n }\n return this.mapper ? this.mapper.idAttribute : this.idAttribute\n },\n\n /**\n * Reduce the data in the collection to a single value and return the result.\n *\n * @example\n * const totalVotes = collection.reduce((prev, record) => {\n * return prev + record.upVotes + record.downVotes;\n * }, 0);\n *\n * @method Collection#reduce\n * @since 3.0.0\n * @param {Function} cb Reduction callback.\n * @param {*} initialValue Initial value of the reduction.\n * @returns {*} The result.\n */\n reduce (cb, initialValue) {\n const data = this.getAll()\n return data.reduce(cb, initialValue)\n },\n\n /**\n * Remove the record with the given id from this Collection.\n *\n * @method Collection#remove\n * @since 3.0.0\n * @param {(string|number|object|Record)} idOrRecord The primary key of the\n * record to be removed, or a reference to the record that is to be removed.\n * @param {object} [opts] Configuration options.\n * @returns {Object|Record} The removed record, if any.\n */\n remove (idOrRecord, opts) {\n // Default values for arguments\n opts || (opts = {})\n this.beforeRemove(idOrRecord, opts)\n let record = utils.isSorN(idOrRecord) ? this.get(idOrRecord) : idOrRecord\n\n // The record is in the collection, remove it\n if (utils.isObject(record)) {\n record = this.index.removeRecord(record)\n if (record) {\n utils.forOwn(this.indexes, function (index, name) {\n index.removeRecord(record)\n })\n if (utils.isFunction(record.off)) {\n record.off('all', this._onRecordEvent, this)\n if (!opts.silent) {\n this.emit('remove', record)\n }\n }\n }\n }\n return this.afterRemove(idOrRecord, opts, record) || record\n },\n\n /**\n * Remove from this collection the given records or the records selected by\n * the given \"query\".\n *\n * @method Collection#removeAll\n * @since 3.0.0\n * @param {Object|Object[]|Record[]} [queryOrRecords={}] Records to be removed or selection query. See {@link query}.\n * @param {object} [queryOrRecords.where] See {@link query.where}.\n * @param {number} [queryOrRecords.offset] See {@link query.offset}.\n * @param {number} [queryOrRecords.limit] See {@link query.limit}.\n * @param {string|Array[]} [queryOrRecords.orderBy] See {@link query.orderBy}.\n * @param {object} [opts] Configuration options.\n * @returns {(Object[]|Record[])} The removed records, if any.\n */\n removeAll (queryOrRecords, opts) {\n // Default values for arguments\n opts || (opts = {})\n this.beforeRemoveAll(queryOrRecords, opts)\n let records = utils.isArray(queryOrRecords) ? queryOrRecords.slice() : this.filter(queryOrRecords)\n\n // Remove each selected record from the collection\n const optsCopy = utils.plainCopy(opts)\n optsCopy.silent = true\n records = records\n .map((record) => this.remove(record, optsCopy))\n .filter((record) => record)\n if (!opts.silent) {\n this.emit('remove', records)\n }\n return this.afterRemoveAll(queryOrRecords, opts, records) || records\n },\n\n /**\n * Skip a number of results.\n *\n * Shortcut for `collection.query().skip(numberToSkip).run()`\n *\n * @example\n * const posts = collection.skip(10);\n *\n * @method Collection#skip\n * @since 3.0.0\n * @param {number} num The number of records to skip.\n * @returns {Array} The result.\n */\n skip (num) {\n return this.query().skip(num).run()\n },\n\n /**\n * Return the plain JSON representation of all items in this collection.\n * Assumes records in this collection have a toJSON method.\n *\n * @method Collection#toJSON\n * @since 3.0.0\n * @param {object} [opts] Configuration options.\n * @param {string[]} [opts.with] Array of relation names or relation fields\n * to include in the representation.\n * @returns {Array} The records.\n */\n toJSON (opts) {\n return this.mapCall('toJSON', opts)\n },\n\n /**\n * Return all \"unsaved\" (not uniquely identifiable) records in this colleciton.\n *\n * @method Collection#unsaved\n * @since 3.0.0\n * @returns {Array} The unsaved records, if any.\n */\n unsaved (opts) {\n return this.index.get()\n },\n\n /**\n * Update a record's position in a single index of this collection. See\n * {@link Collection#updateIndexes} to update a record's position in all\n * indexes at once.\n *\n * @method Collection#updateIndex\n * @since 3.0.0\n * @param {object} record The record to update.\n * @param {object} [opts] Configuration options.\n * @param {string} [opts.index] The index in which to update the record's\n * position. If you don't specify an index then the record will be updated\n * in the main index.\n */\n updateIndex (record, opts) {\n opts || (opts = {})\n this.getIndex(opts.index).updateRecord(record)\n },\n\n /**\n * Updates all indexes in this collection for the provided record. Has no\n * effect if the record is not in the collection.\n *\n * @method Collection#updateIndexes\n * @since 3.0.0\n * @param {object} record TODO\n */\n updateIndexes (record) {\n this.index.updateRecord(record)\n utils.forOwn(this.indexes, function (index, name) {\n index.updateRecord(record)\n })\n }\n})\n\n/**\n * Fired when a record changes. Only works for records that have tracked changes.\n * See {@link Collection~changeListener} on how to listen for this event.\n *\n * @event Collection#change\n * @see Collection~changeListener\n */\n\n/**\n * Callback signature for the {@link Collection#event:change} event.\n *\n * @example\n * function onChange (record, changes) {\n * // do something\n * }\n * collection.on('change', onChange);\n *\n * @callback Collection~changeListener\n * @param {Record} The Record that changed.\n * @param {object} The changes.\n * @see Collection#event:change\n * @since 3.0.0\n */\n\n/**\n * Fired when one or more records are added to the Collection. See\n * {@link Collection~addListener} on how to listen for this event.\n *\n * @event Collection#add\n * @see Collection~addListener\n * @see Collection#event:add\n * @see Collection#add\n */\n\n/**\n * Callback signature for the {@link Collection#event:add} event.\n *\n * @example\n * function onAdd (recordOrRecords) {\n * // do something\n * }\n * collection.on('add', onAdd);\n *\n * @callback Collection~addListener\n * @param {Record|Record[]} The Record or Records that were added.\n * @see Collection#event:add\n * @see Collection#add\n * @since 3.0.0\n */\n\n/**\n * Fired when one or more records are removed from the Collection. See\n * {@link Collection~removeListener} for how to listen for this event.\n *\n * @event Collection#remove\n * @see Collection~removeListener\n * @see Collection#event:remove\n * @see Collection#remove\n * @see Collection#removeAll\n */\n\n/**\n * Callback signature for the {@link Collection#event:remove} event.\n *\n * @example\n * function onRemove (recordsOrRecords) {\n * // do something\n * }\n * collection.on('remove', onRemove);\n *\n * @callback Collection~removeListener\n * @param {Record|Record[]} Record or Records that were removed.\n * @see Collection#event:remove\n * @see Collection#remove\n * @see Collection#removeAll\n * @since 3.0.0\n */\n\n/**\n * Create a subclass of this Collection:\n * @example Collection.extend\n * const JSData = require('js-data');\n * const { Collection } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomCollectionClass extends Collection {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customCollection = new CustomCollectionClass();\n * console.log(customCollection.foo());\n * console.log(CustomCollectionClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherCollectionClass = Collection.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherCollection = new OtherCollectionClass();\n * console.log(otherCollection.foo());\n * console.log(OtherCollectionClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherCollectionClass () {\n * Collection.call(this);\n * this.created_at = new Date().getTime();\n * }\n * Collection.extend({\n * constructor: AnotherCollectionClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const anotherCollection = new AnotherCollectionClass();\n * console.log(anotherCollection.created_at);\n * console.log(anotherCollection.foo());\n * console.log(AnotherCollectionClass.beep());\n *\n * @method Collection.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this Collection class.\n * @since 3.0.0\n */\n","import utils from './utils'\nimport Component from './Component'\n\nconst DOMAIN = 'Schema'\n\n/**\n * A function map for each of the seven primitive JSON types defined by the core specification.\n * Each function will check a given value and return true or false if the value is an instance of that type.\n * ```\n * types.integer(1) // returns true\n * types.string({}) // returns false\n * ```\n * http://json-schema.org/latest/json-schema-core.html#anchor8\n * @name Schema.types\n * @type {object}\n */\nconst types = {\n array: utils.isArray,\n boolean: utils.isBoolean,\n integer: utils.isInteger,\n 'null': utils.isNull,\n number: utils.isNumber,\n object: utils.isObject,\n string: utils.isString\n}\n\n/**\n * @ignore\n */\nconst segmentToString = function (segment, prev) {\n let str = ''\n if (segment) {\n if (utils.isNumber(segment)) {\n str += `[${segment}]`\n } else if (prev) {\n str += `.${segment}`\n } else {\n str += `${segment}`\n }\n }\n return str\n}\n\n/**\n * @ignore\n */\nconst makePath = function (opts) {\n opts || (opts = {})\n let path = ''\n const segments = opts.path || []\n segments.forEach(function (segment) {\n path += segmentToString(segment, path)\n })\n path += segmentToString(opts.prop, path)\n return path\n}\n\n/**\n * @ignore\n */\nconst makeError = function (actual, expected, opts) {\n return {\n expected,\n actual: '' + actual,\n path: makePath(opts)\n }\n}\n\n/**\n * @ignore\n */\nconst addError = function (actual, expected, opts, errors) {\n errors.push(makeError(actual, expected, opts))\n}\n\n/**\n * @ignore\n */\nconst maxLengthCommon = function (keyword, value, schema, opts) {\n const max = schema[keyword]\n if (value.length > max) {\n return makeError(value.length, `length no more than ${max}`, opts)\n }\n}\n\n/**\n * @ignore\n */\nconst minLengthCommon = function (keyword, value, schema, opts) {\n const min = schema[keyword]\n if (value.length < min) {\n return makeError(value.length, `length no less than ${min}`, opts)\n }\n}\n\n/**\n * A map of all object member validation functions for each keyword defined in the JSON Schema.\n * @name Schema.validationKeywords\n * @type {object}\n */\nconst validationKeywords = {\n /**\n * Validates the provided value against all schemas defined in the Schemas `allOf` keyword.\n * The instance is valid against if and only if it is valid against all the schemas declared in the Schema's value.\n *\n * The value of this keyword MUST be an array. This array MUST have at least one element.\n * Each element of this array MUST be a valid JSON Schema.\n *\n * see http://json-schema.org/latest/json-schema-validation.html#anchor82\n *\n * @name Schema.validationKeywords.allOf\n * @method\n * @param {*} value Value to be validated.\n * @param {object} schema Schema containing the `allOf` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n allOf (value, schema, opts) {\n let allErrors = []\n schema.allOf.forEach(function (_schema) {\n allErrors = allErrors.concat(validate(value, _schema, opts) || [])\n })\n return allErrors.length ? allErrors : undefined\n },\n\n /**\n * Validates the provided value against all schemas defined in the Schemas `anyOf` keyword.\n * The instance is valid against this keyword if and only if it is valid against\n * at least one of the schemas in this keyword's value.\n *\n * The value of this keyword MUST be an array. This array MUST have at least one element.\n * Each element of this array MUST be an object, and each object MUST be a valid JSON Schema.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor85\n *\n * @name Schema.validationKeywords.anyOf\n * @method\n * @param {*} value Value to be validated.\n * @param {object} schema Schema containing the `anyOf` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n anyOf (value, schema, opts) {\n let validated = false\n let allErrors = []\n schema.anyOf.forEach(function (_schema) {\n const errors = validate(value, _schema, opts)\n if (errors) {\n allErrors = allErrors.concat(errors)\n } else {\n validated = true\n }\n })\n return validated ? undefined : allErrors\n },\n\n /**\n * http://json-schema.org/latest/json-schema-validation.html#anchor70\n *\n * @name Schema.validationKeywords.dependencies\n * @method\n * @param {*} value TODO\n * @param {object} schema TODO\n * @param {object} opts TODO\n */\n dependencies (value, schema, opts) {\n // TODO\n },\n\n /**\n * Validates the provided value against an array of possible values defined by the Schema's `enum` keyword\n * Validation succeeds if the value is deeply equal to one of the values in the array.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor76\n *\n * @name Schema.validationKeywords.enum\n * @method\n * @param {*} value Value to validate\n * @param {object} schema Schema containing the `enum` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n enum (value, schema, opts) {\n const possibleValues = schema['enum']\n if (utils.findIndex(possibleValues, (item) => utils.deepEqual(item, value)) === -1) {\n return makeError(value, `one of (${possibleValues.join(', ')})`, opts)\n }\n },\n\n /**\n * Validates each of the provided array values against a schema or an array of schemas defined by the Schema's `items` keyword\n * see http://json-schema.org/latest/json-schema-validation.html#anchor37 for validation rules.\n *\n * @name Schema.validationKeywords.items\n * @method\n * @param {*} value Array to be validated.\n * @param {object} schema Schema containing the items keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n items (value, schema, opts) {\n opts || (opts = {})\n // TODO: additionalItems\n let items = schema.items\n let errors = []\n const checkingTuple = utils.isArray(items)\n const length = value.length\n for (var prop = 0; prop < length; prop++) {\n if (checkingTuple) {\n // Validating a tuple, instead of just checking each item against the\n // same schema\n items = schema.items[prop]\n }\n opts.prop = prop\n errors = errors.concat(validate(value[prop], items, opts) || [])\n }\n return errors.length ? errors : undefined\n },\n\n /**\n * Validates the provided number against a maximum value defined by the Schema's `maximum` keyword\n * Validation succeeds if the value is a number, and is less than, or equal to, the value of this keyword.\n * http://json-schema.org/latest/json-schema-validation.html#anchor17\n *\n * @name Schema.validationKeywords.maximum\n * @method\n * @param {*} value Number to validate against the keyword.\n * @param {object} schema Schema containing the `maximum` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n maximum (value, schema, opts) {\n // Must be a number\n const maximum = schema.maximum\n // Must be a boolean\n // Depends on maximum\n // default: false\n const exclusiveMaximum = schema.exclusiveMaximum\n if (typeof value === typeof maximum && !(exclusiveMaximum ? maximum > value : maximum >= value)) {\n return exclusiveMaximum\n ? makeError(value, `no more than nor equal to ${maximum}`, opts)\n : makeError(value, `no more than ${maximum}`, opts)\n }\n },\n\n /**\n * Validates the length of the provided array against a maximum value defined by the Schema's `maxItems` keyword.\n * Validation succeeds if the length of the array is less than, or equal to the value of this keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor42\n *\n * @name Schema.validationKeywords.maxItems\n * @method\n * @param {*} value Array to be validated.\n * @param {object} schema Schema containing the `maxItems` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n maxItems (value, schema, opts) {\n if (utils.isArray(value)) {\n return maxLengthCommon('maxItems', value, schema, opts)\n }\n },\n\n /**\n * Validates the length of the provided string against a maximum value defined in the Schema's `maxLength` keyword.\n * Validation succeeds if the length of the string is less than, or equal to the value of this keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor26\n *\n * @name Schema.validationKeywords.maxLength\n * @method\n * @param {*} value String to be validated.\n * @param {object} schema Schema containing the `maxLength` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n maxLength (value, schema, opts) {\n return maxLengthCommon('maxLength', value, schema, opts)\n },\n\n /**\n * Validates the count of the provided object's properties against a maximum value defined in the Schema's `maxProperties` keyword.\n * Validation succeeds if the object's property count is less than, or equal to the value of this keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor54\n *\n * @name Schema.validationKeywords.maxProperties\n * @method\n * @param {*} value Object to be validated.\n * @param {object} schema Schema containing the `maxProperties` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n maxProperties (value, schema, opts) {\n // validate only objects\n if (!utils.isObject(value)) return\n const maxProperties = schema.maxProperties\n const length = Object.keys(value).length\n if (length > maxProperties) {\n return makeError(length, `no more than ${maxProperties} properties`, opts)\n }\n },\n\n /**\n * Validates the provided value against a minimum value defined by the Schema's `minimum` keyword\n * Validation succeeds if the value is a number and is greater than, or equal to, the value of this keyword.\n * http://json-schema.org/latest/json-schema-validation.html#anchor21\n *\n * @name Schema.validationKeywords.minimum\n * @method\n * @param {*} value Number to validate against the keyword.\n * @param {object} schema Schema containing the `minimum` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n minimum (value, schema, opts) {\n // Must be a number\n const minimum = schema.minimum\n // Must be a boolean\n // Depends on minimum\n // default: false\n const exclusiveMinimum = schema.exclusiveMinimum\n if (typeof value === typeof minimum && !(exclusiveMinimum ? value > minimum : value >= minimum)) {\n return exclusiveMinimum\n ? makeError(value, `no less than nor equal to ${minimum}`, opts)\n : makeError(value, `no less than ${minimum}`, opts)\n }\n },\n\n /**\n * Validates the length of the provided array against a minimum value defined by the Schema's `minItems` keyword.\n * Validation succeeds if the length of the array is greater than, or equal to the value of this keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor45\n *\n * @name Schema.validationKeywords.minItems\n * @method\n * @param {*} value Array to be validated.\n * @param {object} schema Schema containing the `minItems` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n minItems (value, schema, opts) {\n if (utils.isArray(value)) {\n return minLengthCommon('minItems', value, schema, opts)\n }\n },\n\n /**\n * Validates the length of the provided string against a minimum value defined in the Schema's `minLength` keyword.\n * Validation succeeds if the length of the string is greater than, or equal to the value of this keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor29\n *\n * @name Schema.validationKeywords.minLength\n * @method\n * @param {*} value String to be validated.\n * @param {object} schema Schema containing the `minLength` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n minLength (value, schema, opts) {\n return minLengthCommon('minLength', value, schema, opts)\n },\n\n /**\n * Validates the count of the provided object's properties against a minimum value defined in the Schema's `minProperties` keyword.\n * Validation succeeds if the object's property count is greater than, or equal to the value of this keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor57\n *\n * @name Schema.validationKeywords.minProperties\n * @method\n * @param {*} value Object to be validated.\n * @param {object} schema Schema containing the `minProperties` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n minProperties (value, schema, opts) {\n // validate only objects\n if (!utils.isObject(value)) return\n const minProperties = schema.minProperties\n const length = Object.keys(value).length\n if (length < minProperties) {\n return makeError(length, `no more than ${minProperties} properties`, opts)\n }\n },\n\n /**\n * Validates the provided number is a multiple of the number defined in the Schema's `multipleOf` keyword.\n * Validation succeeds if the number can be divided equally into the value of this keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor14\n *\n * @name Schema.validationKeywords.multipleOf\n * @method\n * @param {*} value Number to be validated.\n * @param {object} schema Schema containing the `multipleOf` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n multipleOf (value, schema, opts) {\n const multipleOf = schema.multipleOf\n if (utils.isNumber(value)) {\n if ((value / multipleOf) % 1 !== 0) {\n return makeError(value, `multipleOf ${multipleOf}`, opts)\n }\n }\n },\n\n /**\n * Validates the provided value is not valid with any of the schemas defined in the Schema's `not` keyword.\n * An instance is valid against this keyword if and only if it is NOT valid against the schemas in this keyword's value.\n *\n * see http://json-schema.org/latest/json-schema-validation.html#anchor91\n * @name Schema.validationKeywords.not\n * @method\n * @param {*} value to be checked.\n * @param {object} schema Schema containing the not keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n not (value, schema, opts) {\n if (!validate(value, schema.not, opts)) {\n // TODO: better messaging\n return makeError('succeeded', 'should have failed', opts)\n }\n },\n\n /**\n * Validates the provided value is valid with one and only one of the schemas defined in the Schema's `oneOf` keyword.\n * An instance is valid against this keyword if and only if it is valid against a single schemas in this keyword's value.\n *\n * see http://json-schema.org/latest/json-schema-validation.html#anchor88\n * @name Schema.validationKeywords.oneOf\n * @method\n * @param {*} value to be checked.\n * @param {object} schema Schema containing the `oneOf` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n oneOf (value, schema, opts) {\n let validated = false\n let allErrors = []\n schema.oneOf.forEach(function (_schema) {\n const errors = validate(value, _schema, opts)\n if (errors) {\n allErrors = allErrors.concat(errors)\n } else if (validated) {\n allErrors = [makeError('valid against more than one', 'valid against only one', opts)]\n validated = false\n return false\n } else {\n validated = true\n }\n })\n return validated ? undefined : allErrors\n },\n\n /**\n * Validates the provided string matches a pattern defined in the Schema's `pattern` keyword.\n * Validation succeeds if the string is a match of the regex value of this keyword.\n *\n * see http://json-schema.org/latest/json-schema-validation.html#anchor33\n * @name Schema.validationKeywords.pattern\n * @method\n * @param {*} value String to be validated.\n * @param {object} schema Schema containing the `pattern` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n pattern (value, schema, opts) {\n const pattern = schema.pattern\n if (utils.isString(value) && !value.match(pattern)) {\n return makeError(value, pattern, opts)\n }\n },\n\n /**\n * Validates the provided object's properties against a map of values defined in the Schema's `properties` keyword.\n * Validation succeeds if the object's property are valid with each of the schema's in the provided map.\n * Validation also depends on the additionalProperties and or patternProperties.\n *\n * see http://json-schema.org/latest/json-schema-validation.html#anchor64 for more info.\n *\n * @name Schema.validationKeywords.properties\n * @method\n * @param {*} value Object to be validated.\n * @param {object} schema Schema containing the `properties` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n properties (value, schema, opts) {\n opts || (opts = {})\n\n if (utils.isArray(value)) {\n return\n }\n\n // Can be a boolean or an object\n // Technically the default is an \"empty schema\", but here \"true\" is\n // functionally the same\n const additionalProperties = schema.additionalProperties === undefined ? true : schema.additionalProperties\n const validated = []\n // \"p\": The property set from \"properties\".\n // Default is an object\n const properties = schema.properties || {}\n // \"pp\": The property set from \"patternProperties\".\n // Default is an object\n const patternProperties = schema.patternProperties || {}\n let errors = []\n\n utils.forOwn(properties, function (_schema, prop) {\n opts.prop = prop\n errors = errors.concat(validate(value[prop], _schema, opts) || [])\n validated.push(prop)\n })\n\n const toValidate = utils.omit(value, validated)\n utils.forOwn(patternProperties, function (_schema, pattern) {\n utils.forOwn(toValidate, function (undef, prop) {\n if (prop.match(pattern)) {\n opts.prop = prop\n errors = errors.concat(validate(value[prop], _schema, opts) || [])\n validated.push(prop)\n }\n })\n })\n const keys = Object.keys(utils.omit(value, validated))\n // If \"s\" is not empty, validation fails\n if (additionalProperties === false) {\n if (keys.length) {\n const origProp = opts.prop\n opts.prop = ''\n addError(`extra fields: ${keys.join(', ')}`, 'no extra fields', opts, errors)\n opts.prop = origProp\n }\n } else if (utils.isObject(additionalProperties)) {\n // Otherwise, validate according to provided schema\n keys.forEach(function (prop) {\n opts.prop = prop\n errors = errors.concat(validate(value[prop], additionalProperties, opts) || [])\n })\n }\n return errors.length ? errors : undefined\n },\n\n /**\n * Validates the provided object's has all properties listed in the Schema's `properties` keyword array.\n * Validation succeeds if the object contains all properties provided in the array value of this keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor61\n *\n * @name Schema.validationKeywords.required\n * @method\n * @param {*} value Object to be validated.\n * @param {object} schema Schema containing the `required` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n required (value, schema, opts) {\n opts || (opts = {})\n const required = schema.required\n let errors = []\n if (!opts.existingOnly) {\n required.forEach(function (prop) {\n if (utils.get(value, prop) === undefined) {\n const prevProp = opts.prop\n opts.prop = prop\n addError(undefined, 'a value', opts, errors)\n opts.prop = prevProp\n }\n })\n }\n return errors.length ? errors : undefined\n },\n\n /**\n * Validates the provided value's type is equal to the type, or array of types, defined in the Schema's `type` keyword.\n * see http://json-schema.org/latest/json-schema-validation.html#anchor79\n *\n * @name Schema.validationKeywords.type\n * @method\n * @param {*} value Value to be validated.\n * @param {object} schema Schema containing the `type` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n type (value, schema, opts) {\n let type = schema.type\n let validType\n // Can be one of several types\n if (utils.isString(type)) {\n type = [type]\n }\n // Try to match the value against an expected type\n type.forEach(function (_type) {\n // TODO: throw an error if type is not defined\n if (types[_type](value, schema, opts)) {\n // Matched a type\n validType = _type\n return false\n }\n })\n // Value did not match any expected type\n if (!validType) {\n return makeError(value !== undefined && value !== null ? typeof value : '' + value, `one of (${type.join(', ')})`, opts)\n }\n // Run keyword validators for matched type\n // http://json-schema.org/latest/json-schema-validation.html#anchor12\n const validator = typeGroupValidators[validType]\n if (validator) {\n return validator(value, schema, opts)\n }\n },\n\n /**\n * Validates the provided array values are unique.\n * Validation succeeds if the items in the array are unique, but only if the value of this keyword is true\n * see http://json-schema.org/latest/json-schema-validation.html#anchor49\n *\n * @name Schema.validationKeywords.uniqueItems\n * @method\n * @param {*} value Array to be validated.\n * @param {object} schema Schema containing the `uniqueItems` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n uniqueItems (value, schema, opts) {\n if (value && value.length && schema.uniqueItems) {\n const length = value.length\n let item, i, j\n // Check n - 1 items\n for (i = length - 1; i > 0; i--) {\n item = value[i]\n // Only compare against unchecked items\n for (j = i - 1; j >= 0; j--) {\n // Found a duplicate\n if (utils.deepEqual(item, value[j])) {\n return makeError(item, 'no duplicates', opts)\n }\n }\n }\n }\n }\n}\n\n/**\n * @ignore\n */\nconst runOps = function (ops, value, schema, opts) {\n let errors = []\n ops.forEach(function (op) {\n if (schema[op] !== undefined) {\n errors = errors.concat(validationKeywords[op](value, schema, opts) || [])\n }\n })\n return errors.length ? errors : undefined\n}\n\n/**\n * Validation keywords validated for any type:\n *\n * - `enum`\n * - `type`\n * - `allOf`\n * - `anyOf`\n * - `oneOf`\n * - `not`\n *\n * @name Schema.ANY_OPS\n * @type {string[]}\n */\nconst ANY_OPS = ['enum', 'type', 'allOf', 'anyOf', 'oneOf', 'not']\n\n/**\n * Validation keywords validated for array types:\n *\n * - `items`\n * - `maxItems`\n * - `minItems`\n * - `uniqueItems`\n *\n * @name Schema.ARRAY_OPS\n * @type {string[]}\n */\nconst ARRAY_OPS = ['items', 'maxItems', 'minItems', 'uniqueItems']\n\n/**\n * Validation keywords validated for numeric (number and integer) types:\n *\n * - `multipleOf`\n * - `maximum`\n * - `minimum`\n *\n * @name Schema.NUMERIC_OPS\n * @type {string[]}\n */\nconst NUMERIC_OPS = ['multipleOf', 'maximum', 'minimum']\n\n/**\n * Validation keywords validated for object types:\n *\n * - `maxProperties`\n * - `minProperties`\n * - `required`\n * - `properties`\n * - `dependencies`\n *\n * @name Schema.OBJECT_OPS\n * @type {string[]}\n */\nconst OBJECT_OPS = ['maxProperties', 'minProperties', 'required', 'properties', 'dependencies']\n\n/**\n * Validation keywords validated for string types:\n *\n * - `maxLength`\n * - `minLength`\n * - `pattern`\n *\n * @name Schema.STRING_OPS\n * @type {string[]}\n */\nconst STRING_OPS = ['maxLength', 'minLength', 'pattern']\n\n/**\n * http://json-schema.org/latest/json-schema-validation.html#anchor75\n * @ignore\n */\nconst validateAny = function (value, schema, opts) {\n return runOps(ANY_OPS, value, schema, opts)\n}\n\n/**\n * Validates the provided value against a given Schema according to the http://json-schema.org/ v4 specification.\n *\n * @name Schema.validate\n * @method\n * @param {*} value Value to be validated.\n * @param {object} schema Valid Schema according to the http://json-schema.org/ v4 specification.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\nconst validate = function (value, schema, opts) {\n let errors = []\n opts || (opts = {})\n opts.ctx || (opts.ctx = { value, schema })\n let shouldPop\n let prevProp = opts.prop\n if (schema === undefined) {\n return\n }\n if (!utils.isObject(schema)) {\n throw utils.err(`${DOMAIN}#validate`)(500, `Invalid schema at path: \"${opts.path}\"`)\n }\n if (opts.path === undefined) {\n opts.path = []\n }\n // Track our location as we recurse\n if (opts.prop !== undefined) {\n shouldPop = true\n opts.path.push(opts.prop)\n opts.prop = undefined\n }\n // Validate against parent schema\n if (schema['extends']) {\n // opts.path = path\n // opts.prop = prop\n if (utils.isFunction(schema['extends'].validate)) {\n errors = errors.concat(schema['extends'].validate(value, opts) || [])\n } else {\n errors = errors.concat(validate(value, schema['extends'], opts) || [])\n }\n }\n if (value === undefined) {\n // Check if property is required\n if (schema.required === true && !opts.existingOnly) {\n addError(value, 'a value', opts, errors)\n }\n if (shouldPop) {\n opts.path.pop()\n opts.prop = prevProp\n }\n return errors.length ? errors : undefined\n }\n\n errors = errors.concat(validateAny(value, schema, opts) || [])\n if (shouldPop) {\n opts.path.pop()\n opts.prop = prevProp\n }\n return errors.length ? errors : undefined\n}\n\n// These strings are cached for optimal performance of the change detection\n// boolean - Whether a Record is changing in the current execution frame\nconst changingPath = 'changing'\n// string[] - Properties that have changed in the current execution frame\nconst changedPath = 'changed'\n// Object[] - History of change records\nconst changeHistoryPath = 'history'\n// boolean - Whether a Record is currently being instantiated\nconst creatingPath = 'creating'\n// number - The setTimeout change event id of a Record, if any\nconst eventIdPath = 'eventId'\n// boolean - Whether to skip validation for a Record's currently changing property\nconst noValidatePath = 'noValidate'\n// boolean - Whether to preserve Change History for a Record\nconst keepChangeHistoryPath = 'keepChangeHistory'\n// boolean - Whether to skip change notification for a Record's currently\n// changing property\nconst silentPath = 'silent'\nconst validationFailureMsg = 'validation failed'\n\n/**\n * A map of validation functions grouped by type.\n *\n * @name Schema.typeGroupValidators\n * @type {object}\n */\nconst typeGroupValidators = {\n /**\n * Validates the provided value against the schema using all of the validation keywords specific to instances of an array.\n * The validation keywords for the type `array` are:\n *```\n * ['items', 'maxItems', 'minItems', 'uniqueItems']\n *```\n * see http://json-schema.org/latest/json-schema-validation.html#anchor25\n *\n * @name Schema.typeGroupValidators.array\n * @method\n * @param {*} value Array to be validated.\n * @param {object} schema Schema containing at least one array keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n array: function (value, schema, opts) {\n return runOps(ARRAY_OPS, value, schema, opts)\n },\n\n /**\n * Validates the provided value against the schema using all of the validation keywords specific to instances of an integer.\n * The validation keywords for the type `integer` are:\n *```\n * ['multipleOf', 'maximum', 'minimum']\n *```\n * @name Schema.typeGroupValidators.integer\n * @method\n * @param {*} value Number to be validated.\n * @param {object} schema Schema containing at least one `integer` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n integer: function (value, schema, opts) {\n // Additional validations for numerics are the same\n return typeGroupValidators.numeric(value, schema, opts)\n },\n\n /**\n * Validates the provided value against the schema using all of the validation keywords specific to instances of an number.\n * The validation keywords for the type `number` are:\n *```\n * ['multipleOf', 'maximum', 'minimum']\n *```\n * @name Schema.typeGroupValidators.number\n * @method\n * @param {*} value Number to be validated.\n * @param {object} schema Schema containing at least one `number` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n number: function (value, schema, opts) {\n // Additional validations for numerics are the same\n return typeGroupValidators.numeric(value, schema, opts)\n },\n\n /**\n * Validates the provided value against the schema using all of the validation keywords specific to instances of a number or integer.\n * The validation keywords for the type `numeric` are:\n *```\n * ['multipleOf', 'maximum', 'minimum']\n *```\n * See http://json-schema.org/latest/json-schema-validation.html#anchor13.\n *\n * @name Schema.typeGroupValidators.numeric\n * @method\n * @param {*} value Number to be validated.\n * @param {object} schema Schema containing at least one `numeric` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n numeric: function (value, schema, opts) {\n return runOps(NUMERIC_OPS, value, schema, opts)\n },\n\n /**\n * Validates the provided value against the schema using all of the validation keywords specific to instances of an object.\n * The validation keywords for the type `object` are:\n *```\n * ['maxProperties', 'minProperties', 'required', 'properties', 'dependencies']\n *```\n * See http://json-schema.org/latest/json-schema-validation.html#anchor53.\n *\n * @name Schema.typeGroupValidators.object\n * @method\n * @param {*} value Object to be validated.\n * @param {object} schema Schema containing at least one `object` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n object: function (value, schema, opts) {\n return runOps(OBJECT_OPS, value, schema, opts)\n },\n\n /**\n * Validates the provided value against the schema using all of the validation keywords specific to instances of an string.\n * The validation keywords for the type `string` are:\n *```\n * ['maxLength', 'minLength', 'pattern']\n *```\n * See http://json-schema.org/latest/json-schema-validation.html#anchor25.\n *\n * @name Schema.typeGroupValidators.string\n * @method\n * @param {*} value String to be validated.\n * @param {object} schema Schema containing at least one `string` keyword.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n string: function (value, schema, opts) {\n return runOps(STRING_OPS, value, schema, opts)\n }\n}\n\n/**\n * js-data's Schema class.\n *\n * @example Schema#constructor\n * const JSData = require('js-data');\n * const { Schema } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const PostSchema = new Schema({\n * type: 'object',\n * properties: {\n * title: { type: 'string' }\n * }\n * });\n * PostSchema.validate({ title: 1234 });\n *\n * @class Schema\n * @extends Component\n * @param {object} definition Schema definition according to json-schema.org\n */\nfunction Schema (definition) {\n definition || (definition = {})\n // TODO: schema validation\n utils.fillIn(this, definition)\n\n if (this.type === 'object') {\n this.properties = this.properties || {}\n utils.forOwn(this.properties, (_definition, prop) => {\n if (!(_definition instanceof Schema)) {\n this.properties[prop] = new Schema(_definition)\n }\n })\n } else if (this.type === 'array' && this.items && !(this.items instanceof Schema)) {\n this.items = new Schema(this.items)\n }\n if (this.extends && !(this.extends instanceof Schema)) {\n this.extends = new Schema(this.extends)\n }\n ['allOf', 'anyOf', 'oneOf'].forEach((validationKeyword) => {\n if (this[validationKeyword]) {\n this[validationKeyword].forEach((_definition, i) => {\n if (!(_definition instanceof Schema)) {\n this[validationKeyword][i] = new Schema(_definition)\n }\n })\n }\n })\n}\n\nexport default Component.extend({\n constructor: Schema,\n\n /**\n * This adds ES5 getters/setters to the target based on the \"properties\" in\n * this Schema, which makes possible change tracking and validation on\n * property assignment.\n *\n * @name Schema#apply\n * @method\n * @param {object} target The prototype to which to apply this schema.\n */\n apply (target, opts) {\n opts || (opts = {})\n opts.getter || (opts.getter = '_get')\n opts.setter || (opts.setter = '_set')\n opts.unsetter || (opts.unsetter = '_unset')\n opts.track || (opts.track = this.track)\n const properties = this.properties || {}\n utils.forOwn(properties, (schema, prop) => {\n Object.defineProperty(\n target,\n prop,\n this.makeDescriptor(prop, schema, opts)\n )\n })\n },\n\n /**\n * Apply default values to the target object for missing values.\n *\n * @name Schema#applyDefaults\n * @method\n * @param {object} target The target to which to apply values for missing values.\n */\n applyDefaults (target) {\n if (!target) {\n return\n }\n const properties = this.properties || {}\n const hasSet = utils.isFunction(target.set) || utils.isFunction(target._set)\n utils.forOwn(properties, function (schema, prop) {\n if (schema.hasOwnProperty('default') && utils.get(target, prop) === undefined) {\n if (hasSet) {\n target.set(prop, utils.plainCopy(schema['default']), { silent: true })\n } else {\n utils.set(target, prop, utils.plainCopy(schema['default']))\n }\n }\n if (schema.type === 'object' && schema.properties) {\n if (hasSet) {\n const orig = target._get('noValidate')\n target._set('noValidate', true)\n utils.set(target, prop, utils.get(target, prop) || {}, { silent: true })\n target._set('noValidate', orig)\n } else {\n utils.set(target, prop, utils.get(target, prop) || {})\n }\n schema.applyDefaults(utils.get(target, prop))\n }\n })\n },\n\n /**\n * Assemble a property descriptor for tracking and validating changes to\n * a property according to the given schema. This method is called when\n * {@link Mapper#applySchema} is set to `true`.\n *\n * @name Schema#makeDescriptor\n * @method\n * @param {string} prop The property name.\n * @param {(Schema|object)} schema The schema for the property.\n * @param {object} [opts] Optional configuration.\n * @param {function} [opts.getter] Custom getter function.\n * @param {function} [opts.setter] Custom setter function.\n * @param {function} [opts.track] Whether to track changes.\n * @returns {object} A property descriptor for the given schema.\n */\n makeDescriptor (prop, schema, opts) {\n const descriptor = {\n // Better to allow configurability, but at the user's own risk\n configurable: true,\n // These properties are enumerable by default, but regardless of their\n // enumerability, they won't be \"own\" properties of individual records\n enumerable: schema.enumerable === undefined ? true : !!schema.enumerable\n }\n // Cache a few strings for optimal performance\n const keyPath = `props.${prop}`\n const previousPath = `previous.${prop}`\n const getter = opts.getter\n const setter = opts.setter\n const unsetter = opts.unsetter\n const track = utils.isBoolean(opts.track) ? opts.track : schema.track\n\n descriptor.get = function () {\n return this._get(keyPath)\n }\n\n if (utils.isFunction(schema.get)) {\n const originalGet = descriptor.get\n descriptor.get = function () {\n return schema.get.call(this, originalGet)\n }\n }\n\n descriptor.set = function (value) {\n // These are accessed a lot\n const _get = this[getter]\n const _set = this[setter]\n const _unset = this[unsetter]\n // Optionally check that the new value passes validation\n if (!_get(noValidatePath)) {\n const errors = schema.validate(value, { path: [prop] })\n if (errors) {\n // Immediately throw an error, preventing the record from getting into\n // an invalid state\n const error = new Error(validationFailureMsg)\n error.errors = errors\n throw error\n }\n }\n // TODO: Make it so tracking can be turned on for all properties instead of\n // only per-property\n if (track && !_get(creatingPath)) {\n // previous is versioned on database commit\n // props are versioned on set()\n const previous = _get(previousPath)\n const current = _get(keyPath)\n let changing = _get(changingPath)\n let changed = _get(changedPath)\n\n if (!changing) {\n // Track properties that are changing in the current event loop\n changed = []\n }\n\n // Add changing properties to this array once at most\n const index = changed.indexOf(prop)\n if (current !== value && index === -1) {\n changed.push(prop)\n }\n if (previous === value) {\n if (index >= 0) {\n changed.splice(index, 1)\n }\n }\n // No changes in current event loop\n if (!changed.length) {\n changing = false\n _unset(changingPath)\n _unset(changedPath)\n // Cancel pending change event\n if (_get(eventIdPath)) {\n clearTimeout(_get(eventIdPath))\n _unset(eventIdPath)\n }\n }\n // Changes detected in current event loop\n if (!changing && changed.length) {\n _set(changedPath, changed)\n _set(changingPath, true)\n // Saving the timeout id allows us to batch all changes in the same\n // event loop into a single \"change\"\n // TODO: Optimize\n _set(eventIdPath, setTimeout(() => {\n // Previous event loop where changes were gathered has ended, so\n // notify any listeners of those changes and prepare for any new\n // changes\n _unset(changedPath)\n _unset(eventIdPath)\n _unset(changingPath)\n // TODO: Optimize\n if (!_get(silentPath)) {\n let i\n for (i = 0; i < changed.length; i++) {\n this.emit('change:' + changed[i], this, utils.get(this, changed[i]))\n }\n\n const changes = utils.diffObjects({ [prop]: value }, { [prop]: current })\n\n if (_get(keepChangeHistoryPath)) {\n const changeRecord = utils.plainCopy(changes)\n changeRecord.timestamp = new Date().getTime()\n let changeHistory = _get(changeHistoryPath)\n !changeHistory && _set(changeHistoryPath, (changeHistory = []))\n changeHistory.push(changeRecord)\n }\n this.emit('change', this, changes)\n }\n _unset(silentPath)\n }, 0))\n }\n }\n _set(keyPath, value)\n return value\n }\n\n if (utils.isFunction(schema.set)) {\n const originalSet = descriptor.set\n descriptor.set = function (value) {\n return schema.set.call(this, value, originalSet)\n }\n }\n\n return descriptor\n },\n\n /**\n * Create a copy of the given value that contains only the properties defined\n * in this schema.\n *\n * @name Schema#pick\n * @method\n * @param {*} value The value to copy.\n * @returns {*} The copy.\n */\n pick (value) {\n if (value === undefined) {\n return\n }\n if (this.type === 'object') {\n let copy = {}\n const properties = this.properties\n if (properties) {\n utils.forOwn(properties, (_definition, prop) => {\n copy[prop] = _definition.pick(value[prop])\n })\n }\n if (this.extends) {\n utils.fillIn(copy, this.extends.pick(value))\n }\n // Conditionally copy properties not defined in \"properties\"\n if (this.additionalProperties) {\n for (var key in value) {\n if (!properties[key]) {\n copy[key] = utils.plainCopy(value[key])\n }\n }\n }\n return copy\n } else if (this.type === 'array') {\n return value.map((item) => {\n const _copy = this.items ? this.items.pick(item) : {}\n if (this.extends) {\n utils.fillIn(_copy, this.extends.pick(item))\n }\n return _copy\n })\n }\n return utils.plainCopy(value)\n },\n\n /**\n * Validate the provided value against this schema.\n *\n * @name Schema#validate\n * @method\n * @param {*} value Value to validate.\n * @param {object} [opts] Configuration options.\n * @returns {(array|undefined)} Array of errors or `undefined` if valid.\n */\n validate (value, opts) {\n return validate(value, this, opts)\n }\n}, {\n ANY_OPS,\n ARRAY_OPS,\n NUMERIC_OPS,\n OBJECT_OPS,\n STRING_OPS,\n typeGroupValidators,\n types,\n validate,\n validationKeywords\n})\n\n/**\n * Create a subclass of this Schema:\n * @example Schema.extend\n * const JSData = require('js-data');\n * const { Schema } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomSchemaClass extends Schema {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customSchema = new CustomSchemaClass();\n * console.log(customSchema.foo());\n * console.log(CustomSchemaClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherSchemaClass = Schema.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherSchema = new OtherSchemaClass();\n * console.log(otherSchema.foo());\n * console.log(OtherSchemaClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherSchemaClass () {\n * Schema.call(this);\n * this.created_at = new Date().getTime();\n * }\n * Schema.extend({\n * constructor: AnotherSchemaClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const anotherSchema = new AnotherSchemaClass();\n * console.log(anotherSchema.created_at);\n * console.log(anotherSchema.foo());\n * console.log(AnotherSchemaClass.beep());\n *\n * @method Schema.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this Schema class.\n * @since 3.0.0\n */\n","import utils from './utils'\nimport Component from './Component'\nimport Record from './Record'\nimport Schema from './Schema'\nimport { Relation } from './relations'\nimport {\n belongsTo,\n belongsToType,\n hasMany,\n hasManyType,\n hasOne,\n hasOneType\n} from './decorators'\n\nconst DOMAIN = 'Mapper'\nconst applyDefaultsHooks = [\n 'beforeCreate',\n 'beforeCreateMany'\n]\nconst validatingHooks = [\n 'beforeCreate',\n 'beforeCreateMany',\n 'beforeUpdate',\n 'beforeUpdateAll',\n 'beforeUpdateMany'\n]\nconst makeNotify = function (num) {\n return function (...args) {\n const opts = args[args.length - num]\n const op = opts.op\n this.dbg(op, ...args)\n\n if (applyDefaultsHooks.indexOf(op) !== -1 && opts.applyDefaults !== false) {\n const schema = this.getSchema()\n if (schema && schema.applyDefaults) {\n let toProcess = args[0]\n if (!utils.isArray(toProcess)) {\n toProcess = [toProcess]\n }\n toProcess.forEach((record) => {\n schema.applyDefaults(record)\n })\n }\n }\n\n // Automatic validation\n if (validatingHooks.indexOf(op) !== -1 && !opts.noValidate) {\n // Save current value of option\n const originalExistingOnly = opts.existingOnly\n\n // For updates, ignore required fields if they aren't present\n if (op.indexOf('beforeUpdate') === 0 && opts.existingOnly === undefined) {\n opts.existingOnly = true\n }\n const errors = this.validate(args[op === 'beforeUpdate' ? 1 : 0], utils.pick(opts, ['existingOnly']))\n\n // Restore option\n opts.existingOnly = originalExistingOnly\n\n // Abort lifecycle due to validation errors\n if (errors) {\n const err = new Error('validation failed')\n err.errors = errors\n return utils.reject(err)\n }\n }\n\n // Emit lifecycle event\n if (opts.notify || (opts.notify === undefined && this.notify)) {\n setTimeout(() => {\n this.emit(op, ...args)\n })\n }\n }\n}\n\n// These are the default implementations of all of the lifecycle hooks\nconst notify = makeNotify(1)\nconst notify2 = makeNotify(2)\n\n// This object provides meta information used by Mapper#crud to actually\n// execute each lifecycle method\nconst LIFECYCLE_METHODS = {\n count: {\n defaults: [{}, {}],\n skip: true,\n types: []\n },\n destroy: {\n defaults: [{}, {}],\n skip: true,\n types: []\n },\n destroyAll: {\n defaults: [{}, {}],\n skip: true,\n types: []\n },\n find: {\n defaults: [undefined, {}],\n types: []\n },\n findAll: {\n defaults: [{}, {}],\n types: []\n },\n sum: {\n defaults: [undefined, {}, {}],\n skip: true,\n types: []\n },\n update: {\n adapterArgs (mapper, id, props, opts) {\n return [id, mapper.toJSON(props, opts), opts]\n },\n beforeAssign: 1,\n defaults: [undefined, {}, {}],\n types: []\n },\n updateAll: {\n adapterArgs (mapper, props, query, opts) {\n return [mapper.toJSON(props, opts), query, opts]\n },\n beforeAssign: 0,\n defaults: [{}, {}, {}],\n types: []\n },\n updateMany: {\n adapterArgs (mapper, records, opts) {\n return [records.map((record) => mapper.toJSON(record, opts)), opts]\n },\n beforeAssign: 0,\n defaults: [[], {}],\n types: []\n }\n}\n\nconst MAPPER_DEFAULTS = {\n /**\n * Hash of registered adapters. Don't modify directly. Use\n * {@link Mapper#registerAdapter} instead.\n *\n * @default {}\n * @name Mapper#_adapters\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/connecting-to-a-data-source\",\"Connecting to a data source\"]\n */\n _adapters: {},\n\n /**\n * Whether {@link Mapper#beforeCreate} and {@link Mapper#beforeCreateMany}\n * should automatically receive default values according to the Mapper's schema.\n *\n * @default true\n * @name Mapper#applyDefaults\n * @since 3.0.0\n * @type {boolean}\n */\n applyDefaults: true,\n\n /**\n * Whether to augment {@link Mapper#recordClass} with ES5 getters and setters\n * according to the properties defined in {@link Mapper#schema}. This makes\n * possible validation and change tracking on individual properties\n * when using the dot (e.g. `user.name = \"Bob\"`) operator to modify a\n * property, and is `true` by default.\n *\n * @default true\n * @name Mapper#applySchema\n * @since 3.0.0\n * @type {boolean}\n */\n applySchema: true,\n\n /**\n * The name of the registered adapter that this Mapper should used by default.\n *\n * @default \"http\"\n * @name Mapper#defaultAdapter\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/connecting-to-a-data-source\",\"Connecting to a data source\"]\n * @type {string}\n */\n defaultAdapter: 'http',\n\n /**\n * The field used as the unique identifier on records handled by this Mapper.\n *\n * @default id\n * @name Mapper#idAttribute\n * @since 3.0.0\n * @type {string}\n */\n idAttribute: 'id',\n\n /**\n * Whether records created from this mapper keep changeHistory on property changes.\n *\n * @default true\n * @name Mapper#keepChangeHistory\n * @since 3.0.0\n * @type {boolean}\n */\n keepChangeHistory: true,\n\n /**\n * Whether this Mapper should emit operational events.\n *\n * @default true\n * @name Mapper#notify\n * @since 3.0.0\n * @type {boolean}\n */\n notify: true,\n\n /**\n * Whether to skip validation when the Record instances are created.\n *\n * @default false\n * @name Mapper#noValidate\n * @since 3.0.0\n * @type {boolean}\n */\n noValidate: false,\n\n /**\n * Whether {@link Mapper#create}, {@link Mapper#createMany},\n * {@link Mapper#update}, {@link Mapper#updateAll}, {@link Mapper#updateMany},\n * {@link Mapper#find}, {@link Mapper#findAll}, {@link Mapper#destroy},\n * {@link Mapper#destroyAll}, {@link Mapper#count}, and {@link Mapper#sum}\n * should return a raw result object that contains both the instance data\n * returned by the adapter _and_ metadata about the operation.\n *\n * The default is to NOT return the result object, and instead return just the\n * instance data.\n *\n * @default false\n * @name Mapper#raw\n * @since 3.0.0\n * @type {boolean}\n */\n raw: false,\n\n /**\n * Whether records created from this mapper automatically validate their properties\n * when their properties are modified.\n *\n * @default true\n * @name Mapper#validateOnSet\n * @since 3.0.0\n * @type {boolean}\n */\n validateOnSet: true\n}\n\n/**\n * The core of JSData's [ORM/ODM][orm] implementation. Given a minimum amout of\n * meta information about a resource, a Mapper can perform generic CRUD\n * operations against that resource. Apart from its configuration, a Mapper is\n * stateless. The particulars of various persistence layers have been abstracted\n * into adapters, which a Mapper uses to perform its operations.\n *\n * The term \"Mapper\" comes from the [Data Mapper Pattern][pattern] described in\n * Martin Fowler's [Patterns of Enterprise Application Architecture][book]. A\n * Data Mapper moves data between [in-memory object instances][record] and a\n * relational or document-based database. JSData's Mapper can work with any\n * persistence layer you can write an adapter for.\n *\n * _(\"Model\" is a heavily overloaded term and is avoided in this documentation\n * to prevent confusion.)_\n *\n * [orm]: https://en.wikipedia.org/wiki/Object-relational_mapping\n *\n * @example\n * [pattern]: https://en.wikipedia.org/wiki/Data_mapper_pattern\n * [book]: http://martinfowler.com/books/eaa.html\n * [record]: Record.html\n * // Import and instantiate\n * import { Mapper } from 'js-data';\n * const UserMapper = new Mapper({ name: 'user' });\n *\n * @example\n * // Define a Mapper using the Container component\n * import { Container } from 'js-data';\n * const store = new Container();\n * store.defineMapper('user');\n *\n * @class Mapper\n * @extends Component\n * @param {object} opts Configuration options.\n * @param {boolean} [opts.applySchema=true] See {@link Mapper#applySchema}.\n * @param {boolean} [opts.debug=false] See {@link Component#debug}.\n * @param {string} [opts.defaultAdapter=http] See {@link Mapper#defaultAdapter}.\n * @param {string} [opts.idAttribute=id] See {@link Mapper#idAttribute}.\n * @param {object} [opts.methods] See {@link Mapper#methods}.\n * @param {string} opts.name See {@link Mapper#name}.\n * @param {boolean} [opts.notify] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw=false] See {@link Mapper#raw}.\n * @param {Function|boolean} [opts.recordClass] See {@link Mapper#recordClass}.\n * @param {Object|Schema} [opts.schema] See {@link Mapper#schema}.\n * @returns {Mapper} A new {@link Mapper} instance.\n * @see http://www.js-data.io/v3.0/docs/components-of-jsdata#mapper\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#mapper\",\"Components of JSData: Mapper\"]\n * @tutorial [\"http://www.js-data.io/v3.0/docs/modeling-your-data\",\"Modeling your data\"]\n */\nfunction Mapper (opts) {\n utils.classCallCheck(this, Mapper)\n Component.call(this)\n opts || (opts = {})\n\n // Prepare certain properties to be non-enumerable\n Object.defineProperties(this, {\n _adapters: {\n value: undefined,\n writable: true\n },\n\n /**\n * The {@link Container} that holds this Mapper. __Do not modify.__\n *\n * @name Mapper#lifecycleMethods\n * @since 3.0.0\n * @type {Object}\n */\n datastore: {\n value: undefined,\n writable: true\n },\n\n /**\n * The meta information describing this Mapper's available lifecycle\n * methods. __Do not modify.__\n *\n * @name Mapper#lifecycleMethods\n * @since 3.0.0\n * @type {Object}\n */\n lifecycleMethods: {\n value: LIFECYCLE_METHODS\n },\n\n /**\n * Set to `false` to force the Mapper to work with POJO objects only.\n *\n * @example\n * // Use POJOs only.\n * import { Mapper, Record } from 'js-data';\n * const UserMapper = new Mapper({ recordClass: false });\n * UserMapper.recordClass // false;\n * const user = UserMapper.createRecord();\n * user instanceof Record; // false\n *\n * @example\n * // Set to a custom class to have records wrapped in your custom class.\n * import { Mapper, Record } from 'js-data';\n * // Custom class\n * class User {\n * constructor (props = {}) {\n * for (var key in props) {\n * if (props.hasOwnProperty(key)) {\n * this[key] = props[key];\n * }\n * }\n * }\n * }\n * const UserMapper = new Mapper({ recordClass: User });\n * UserMapper.recordClass; // function User() {}\n * const user = UserMapper.createRecord();\n * user instanceof Record; // false\n * user instanceof User; // true\n *\n *\n * @example\n * // Extend the {@link Record} class.\n * import { Mapper, Record } from 'js-data';\n * // Custom class\n * class User extends Record {\n * constructor () {\n * super(props);\n * }\n * }\n * const UserMapper = new Mapper({ recordClass: User });\n * UserMapper.recordClass; // function User() {}\n * const user = UserMapper.createRecord();\n * user instanceof Record; // true\n * user instanceof User; // true\n *\n * @name Mapper#recordClass\n * @default {@link Record}\n * @see Record\n * @since 3.0.0\n */\n recordClass: {\n value: undefined,\n writable: true\n },\n\n /**\n * This Mapper's {@link Schema}.\n *\n * @example Mapper#schema\n * const JSData = require('js-data');\n * const { Mapper } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const UserMapper = new Mapper({\n * name: 'user',\n * schema: {\n * properties: {\n * id: { type: 'number' },\n * first: { type: 'string', track: true },\n * last: { type: 'string', track: true },\n * role: { type: 'string', track: true, required: true },\n * age: { type: 'integer', track: true },\n * is_active: { type: 'number' }\n * }\n * }\n * });\n * const user = UserMapper.createRecord({\n * id: 1,\n * name: 'John',\n * role: 'admin'\n * });\n * user.on('change', function (user, changes) {\n * console.log(changes);\n * });\n * user.on('change:role', function (user, value) {\n * console.log('change:role - ' + value);\n * });\n * user.role = 'owner';\n *\n * @name Mapper#schema\n * @see Schema\n * @since 3.0.0\n * @type {Schema}\n */\n schema: {\n value: undefined,\n writable: true\n }\n })\n\n // Apply user-provided configuration\n utils.fillIn(this, opts)\n // Fill in any missing options with the defaults\n utils.fillIn(this, utils.copy(MAPPER_DEFAULTS))\n\n /**\n * The name for this Mapper. This is the minimum amount of meta information\n * required for a Mapper to be able to execute CRUD operations for a\n * Resource.\n *\n * @name Mapper#name\n * @since 3.0.0\n * @type {string}\n */\n if (!this.name) {\n throw utils.err(`new ${DOMAIN}`, 'opts.name')(400, 'string', this.name)\n }\n\n // Setup schema, with an empty default schema if necessary\n if (this.schema) {\n this.schema.type || (this.schema.type = 'object')\n if (!(this.schema instanceof Schema)) {\n this.schema = new Schema(this.schema || { type: 'object' })\n }\n }\n\n // Create a subclass of Record that's tied to this Mapper\n if (this.recordClass === undefined) {\n const superClass = Record\n this.recordClass = superClass.extend({\n constructor: (function Record () {\n var subClass = function Record (props, opts) {\n utils.classCallCheck(this, subClass)\n superClass.call(this, props, opts)\n }\n return subClass\n })()\n })\n }\n\n if (this.recordClass) {\n this.recordClass.mapper = this\n\n /**\n * Functions that should be added to the prototype of {@link Mapper#recordClass}.\n *\n * @name Mapper#methods\n * @since 3.0.0\n * @type {Object}\n */\n if (utils.isObject(this.methods)) {\n utils.addHiddenPropsToTarget(this.recordClass.prototype, this.methods)\n }\n\n // We can only apply the schema to the prototype of this.recordClass if the\n // class extends Record\n if (Record.prototype.isPrototypeOf(Object.create(this.recordClass.prototype)) && this.schema && this.schema.apply && this.applySchema) {\n this.schema.apply(this.recordClass.prototype)\n }\n }\n}\n\nexport default Component.extend({\n constructor: Mapper,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#count}. If this method\n * returns a promise then {@link Mapper#count} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterCount\n * @param {object} query The `query` argument passed to {@link Mapper#count}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#count}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterCount: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#create}. If this method\n * returns a promise then {@link Mapper#create} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterCreate\n * @param {object} props The `props` argument passed to {@link Mapper#create}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#create}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterCreate: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#createMany}. If this method\n * returns a promise then {@link Mapper#createMany} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterCreateMany\n * @param {array} records The `records` argument passed to {@link Mapper#createMany}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#createMany}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterCreateMany: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#destroy}. If this method\n * returns a promise then {@link Mapper#destroy} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterDestroy\n * @param {(string|number)} id The `id` argument passed to {@link Mapper#destroy}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#destroy}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterDestroy: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#destroyAll}. If this method\n * returns a promise then {@link Mapper#destroyAll} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterDestroyAll\n * @param {*} data The `data` returned by the adapter.\n * @param {query} query The `query` argument passed to {@link Mapper#destroyAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#destroyAll}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterDestroyAll: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#find}. If this method\n * returns a promise then {@link Mapper#find} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterFind\n * @param {(string|number)} id The `id` argument passed to {@link Mapper#find}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#find}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterFind: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#findAll}. If this method\n * returns a promise then {@link Mapper#findAll} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterFindAll\n * @param {object} query The `query` argument passed to {@link Mapper#findAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#findAll}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterFindAll: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#sum}. If this method\n * returns a promise then {@link Mapper#sum} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterSum\n * @param {object} query The `query` argument passed to {@link Mapper#sum}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#sum}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterSum: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#update}. If this method\n * returns a promise then {@link Mapper#update} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterUpdate\n * @param {(string|number)} id The `id` argument passed to {@link Mapper#update}.\n * @param {props} props The `props` argument passed to {@link Mapper#update}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#update}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterUpdate: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#updateAll}. If this method\n * returns a promise then {@link Mapper#updateAll} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterUpdateAll\n * @param {object} props The `props` argument passed to {@link Mapper#updateAll}.\n * @param {object} query The `query` argument passed to {@link Mapper#updateAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#updateAll}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterUpdateAll: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#updateMany}. If this method\n * returns a promise then {@link Mapper#updateMany} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#afterUpdateMany\n * @param {array} records The `records` argument passed to {@link Mapper#updateMany}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#updateMany}.\n * @param {*} result The result, if any.\n * @since 3.0.0\n */\n afterUpdateMany: notify2,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#create}. If this method\n * returns a promise then {@link Mapper#create} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeCreate\n * @param {object} props The `props` argument passed to {@link Mapper#create}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#create}.\n * @since 3.0.0\n */\n beforeCreate: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#createMany}. If this method\n * returns a promise then {@link Mapper#createMany} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeCreateMany\n * @param {array} records The `records` argument passed to {@link Mapper#createMany}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#createMany}.\n * @since 3.0.0\n */\n beforeCreateMany: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#count}. If this method\n * returns a promise then {@link Mapper#count} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeCount\n * @param {object} query The `query` argument passed to {@link Mapper#count}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#count}.\n * @since 3.0.0\n */\n beforeCount: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#destroy}. If this method\n * returns a promise then {@link Mapper#destroy} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeDestroy\n * @param {(string|number)} id The `id` argument passed to {@link Mapper#destroy}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#destroy}.\n * @since 3.0.0\n */\n beforeDestroy: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#destroyAll}. If this method\n * returns a promise then {@link Mapper#destroyAll} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeDestroyAll\n * @param {query} query The `query` argument passed to {@link Mapper#destroyAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#destroyAll}.\n * @since 3.0.0\n */\n beforeDestroyAll: notify,\n\n /**\n * Mappers lifecycle hook called by {@link Mapper#find}. If this method\n * returns a promise then {@link Mapper#find} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeFind\n * @param {(string|number)} id The `id` argument passed to {@link Mapper#find}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#find}.\n * @since 3.0.0\n */\n beforeFind: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#findAll}. If this method\n * returns a promise then {@link Mapper#findAll} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeFindAll\n * @param {object} query The `query` argument passed to {@link Mapper#findAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#findAll}.\n * @since 3.0.0\n */\n beforeFindAll: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#sum}. If this method\n * returns a promise then {@link Mapper#sum} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeSum\n * @param {string} field The `field` argument passed to {@link Mapper#sum}.\n * @param {object} query The `query` argument passed to {@link Mapper#sum}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#sum}.\n * @since 3.0.0\n */\n beforeSum: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#update}. If this method\n * returns a promise then {@link Mapper#update} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeUpdate\n * @param {(string|number)} id The `id` argument passed to {@link Mapper#update}.\n * @param {props} props The `props` argument passed to {@link Mapper#update}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#update}.\n * @since 3.0.0\n */\n beforeUpdate: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#updateAll}. If this method\n * returns a promise then {@link Mapper#updateAll} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeUpdateAll\n * @param {object} props The `props` argument passed to {@link Mapper#updateAll}.\n * @param {object} query The `query` argument passed to {@link Mapper#updateAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#updateAll}.\n * @since 3.0.0\n */\n beforeUpdateAll: notify,\n\n /**\n * Mapper lifecycle hook called by {@link Mapper#updateMany}. If this method\n * returns a promise then {@link Mapper#updateMany} will wait for the promise\n * to resolve before continuing.\n *\n * @method Mapper#beforeUpdateMany\n * @param {array} records The `records` argument passed to {@link Mapper#updateMany}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#updateMany}.\n * @since 3.0.0\n */\n beforeUpdateMany: notify,\n\n /**\n * This method is called at the end of most lifecycle methods. It does the\n * following:\n *\n * 1. If `opts.raw` is `true`, add this Mapper's configuration to the `opts`\n * argument as metadata for the operation.\n * 2. Wrap the result data appropriately using {@link Mapper#wrap}, which\n * calls {@link Mapper#createRecord}.\n *\n * @method Mapper#_end\n * @private\n * @since 3.0.0\n */\n _end (result, opts, skip) {\n if (opts.raw) {\n utils._(result, opts)\n }\n if (skip) {\n return result\n }\n let _data = opts.raw ? result.data : result\n if (_data && utils.isFunction(this.wrap)) {\n _data = this.wrap(_data, opts)\n if (opts.raw) {\n result.data = _data\n } else {\n result = _data\n }\n }\n return result\n },\n\n /**\n * Define a belongsTo relationship. Only useful if you're managing your\n * Mappers manually and not using a Container or DataStore component.\n *\n * @example\n * PostMapper.belongsTo(UserMapper, {\n * // post.user_id points to user.id\n * foreignKey: 'user_id'\n * // user records will be attached to post records at \"post.user\"\n * localField: 'user'\n * });\n *\n * CommentMapper.belongsTo(UserMapper, {\n * // comment.user_id points to user.id\n * foreignKey: 'user_id'\n * // user records will be attached to comment records at \"comment.user\"\n * localField: 'user'\n * });\n * CommentMapper.belongsTo(PostMapper, {\n * // comment.post_id points to post.id\n * foreignKey: 'post_id'\n * // post records will be attached to comment records at \"comment.post\"\n * localField: 'post'\n * });\n *\n * @method Mapper#belongsTo\n * @see http://www.js-data.io/v3.0/docs/relations\n * @since 3.0.0\n */\n belongsTo (relatedMapper, opts) {\n return belongsTo(relatedMapper, opts)(this)\n },\n\n /**\n * Select records according to the `query` argument and return the count.\n *\n * {@link Mapper#beforeCount} will be called before calling the adapter.\n * {@link Mapper#afterCount} will be called after calling the adapter.\n *\n * @example\n * // Get the number of published blog posts\n * PostMapper.count({ status: 'published' }).then((numPublished) => {\n * console.log(numPublished); // e.g. 45\n * });\n *\n * @method Mapper#count\n * @param {object} [query={}] Selection query. See {@link query}.\n * @param {object} [query.where] See {@link query.where}.\n * @param {number} [query.offset] See {@link query.offset}.\n * @param {number} [query.limit] See {@link query.limit}.\n * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}.\n * @param {object} [opts] Configuration options. Refer to the `count` method\n * of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @returns {Promise} Resolves with the count of the selected records.\n * @since 3.0.0\n */\n count (query, opts) {\n return this.crud('count', query, opts)\n },\n\n /**\n * Fired during {@link Mapper#create}. See\n * {@link Mapper~beforeCreateListener} for how to listen for this event.\n *\n * @event Mapper#beforeCreate\n * @see Mapper~beforeCreateListener\n * @see Mapper#create\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeCreate} event.\n *\n * @example\n * function onBeforeCreate (props, opts) {\n * // do something\n * }\n * store.on('beforeCreate', onBeforeCreate);\n *\n * @callback Mapper~beforeCreateListener\n * @param {object} props The `props` argument passed to {@link Mapper#beforeCreate}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#beforeCreate}.\n * @see Mapper#event:beforeCreate\n * @see Mapper#create\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#create}. See\n * {@link Mapper~afterCreateListener} for how to listen for this event.\n *\n * @event Mapper#afterCreate\n * @see Mapper~afterCreateListener\n * @see Mapper#create\n */\n /**\n * Callback signature for the {@link Mapper#event:afterCreate} event.\n *\n * @example\n * function onAfterCreate (props, opts, result) {\n * // do something\n * }\n * store.on('afterCreate', onAfterCreate);\n *\n * @callback Mapper~afterCreateListener\n * @param {object} props The `props` argument passed to {@link Mapper#afterCreate}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#afterCreate}.\n * @param {object} result The `result` argument passed to {@link Mapper#afterCreate}.\n * @see Mapper#event:afterCreate\n * @see Mapper#create\n * @since 3.0.0\n */\n /**\n * Create and save a new the record using the provided `props`.\n *\n * {@link Mapper#beforeCreate} will be called before calling the adapter.\n * {@link Mapper#afterCreate} will be called after calling the adapter.\n *\n * @example\n * // Create and save a new blog post\n * PostMapper.create({\n * title: 'Modeling your data',\n * status: 'draft'\n * }).then((post) => {\n * console.log(post); // { id: 1234, status: 'draft', ... }\n * });\n *\n * @fires Mapper#beforeCreate\n * @fires Mapper#afterCreate\n * @method Mapper#create\n * @param {object} props The properties for the new record.\n * @param {object} [opts] Configuration options. Refer to the `create` method\n * of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @param {string[]} [opts.with=[]] Relations to create in a cascading\n * create if `props` contains nested relations. NOT performed in a\n * transaction. Each nested create will result in another {@link Mapper#create}\n * or {@link Mapper#createMany} call.\n * @param {string[]} [opts.pass=[]] Relations to send to the adapter as part\n * of the payload. Normally relations are not sent.\n * @returns {Promise} Resolves with the created record.\n * @since 3.0.0\n */\n create (props, opts) {\n // Default values for arguments\n props || (props = {})\n opts || (opts = {})\n const originalRecord = props\n let parentRelationMap = {}\n let adapterResponse = {}\n\n // Fill in \"opts\" with the Mapper's configuration\n utils._(opts, this)\n opts.adapter = this.getAdapterName(opts)\n\n opts.op = 'beforeCreate'\n return this._runHook(opts.op, props, opts).then((props) => {\n opts.with || (opts.with = [])\n return this._createParentRecordIfRequired(props, opts)\n }).then((relationMap) => {\n parentRelationMap = relationMap\n }).then(() => {\n opts.op = 'create'\n return this._invokeAdapterMethod(opts.op, props, opts)\n }).then((result) => {\n adapterResponse = result\n }).then(() => {\n const createdProps = opts.raw ? adapterResponse.data : adapterResponse\n\n return this._createOrAssignChildRecordIfRequired(createdProps, {\n opts,\n parentRelationMap,\n originalProps: props\n })\n }).then((createdProps) => {\n return this._commitChanges(originalRecord, createdProps)\n }).then((record) => {\n if (opts.raw) {\n adapterResponse.data = record\n } else {\n adapterResponse = record\n }\n const result = this._end(adapterResponse, opts)\n opts.op = 'afterCreate'\n return this._runHook(opts.op, props, opts, result)\n })\n },\n\n _commitChanges (recordOrRecords, newValues) {\n if (utils.isArray(recordOrRecords)) {\n return recordOrRecords.map((record, i) => this._commitChanges(record, newValues[i]))\n }\n\n utils.set(recordOrRecords, newValues, { silent: true })\n\n if (utils.isFunction(recordOrRecords.commit)) {\n recordOrRecords.commit()\n }\n\n return recordOrRecords\n },\n\n /**\n * Use {@link Mapper#createRecord} instead.\n * @deprecated\n * @method Mapper#createInstance\n * @param {Object|Array} props See {@link Mapper#createRecord}.\n * @param {object} [opts] See {@link Mapper#createRecord}.\n * @returns {Object|Array} See {@link Mapper#createRecord}.\n * @see Mapper#createRecord\n * @since 3.0.0\n */\n createInstance (props, opts) {\n return this.createRecord(props, opts)\n },\n\n /**\n * Creates parent record for relation types like BelongsTo or HasMany with localKeys\n * in order to satisfy foreignKey dependency (so called child records).\n * @param {object} props See {@link Mapper#create}.\n * @param {object} opts See {@link Mapper#create}.\n * @returns {Object} cached parent records map\n * @see Mapper#create\n * @since 3.0.0\n */\n _createParentRecordIfRequired (props, opts) {\n const tasks = []\n const relations = []\n\n utils.forEachRelation(this, opts, (def, optsCopy) => {\n if (!def.isRequiresParentId() || !def.getLocalField(props)) {\n return\n }\n\n optsCopy.raw = false\n relations.push(def)\n tasks.push(def.createParentRecord(props, optsCopy))\n })\n\n return utils.Promise.all(tasks).then(records => {\n return relations.reduce((map, relation, index) => {\n relation.setLocalField(map, records[index])\n return map\n }, {})\n })\n },\n\n /**\n * Creates child record for relation types like HasOne or HasMany with foreignKey\n * in order to satisfy foreignKey dependency (so called parent records).\n * @param {object} props See {@link Mapper#create}.\n * @param {object} context contains collected information.\n * @param {object} context.opts See {@link Mapper#create}.\n * @param {object} context.parentRelationMap contains parent records map\n * @param {object} context.originalProps contains data passed into {@link Mapper#create} method\n * @return {Promise} updated props\n * @see Mapper#create\n * @since 3.0.0\n */\n _createOrAssignChildRecordIfRequired (props, context) {\n const tasks = []\n\n utils.forEachRelation(this, context.opts, (def, optsCopy) => {\n const relationData = def.getLocalField(context.originalProps)\n\n if (!relationData) {\n return\n }\n\n optsCopy.raw = false\n // Create hasMany and hasOne after the main create because we needed\n // a generated id to attach to these items\n if (def.isRequiresChildId()) {\n tasks.push(def.createChildRecord(props, relationData, optsCopy))\n } else if (def.isRequiresParentId()) {\n const parent = def.getLocalField(context.parentRelationMap)\n\n if (parent) {\n def.setLocalField(props, parent)\n }\n }\n })\n\n return utils.Promise.all(tasks)\n .then(() => props)\n },\n\n /**\n * Fired during {@link Mapper#createMany}. See\n * {@link Mapper~beforeCreateManyListener} for how to listen for this event.\n *\n * @event Mapper#beforeCreateMany\n * @see Mapper~beforeCreateManyListener\n * @see Mapper#createMany\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeCreateMany} event.\n *\n * @example\n * function onBeforeCreateMany (records, opts) {\n * // do something\n * }\n * store.on('beforeCreateMany', onBeforeCreateMany);\n *\n * @callback Mapper~beforeCreateManyListener\n * @param {object} records The `records` argument received by {@link Mapper#beforeCreateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreateMany}.\n * @see Mapper#event:beforeCreateMany\n * @see Mapper#createMany\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#createMany}. See\n * {@link Mapper~afterCreateManyListener} for how to listen for this event.\n *\n * @event Mapper#afterCreateMany\n * @see Mapper~afterCreateManyListener\n * @see Mapper#createMany\n */\n /**\n * Callback signature for the {@link Mapper#event:afterCreateMany} event.\n *\n * @example\n * function onAfterCreateMany (records, opts, result) {\n * // do something\n * }\n * store.on('afterCreateMany', onAfterCreateMany);\n *\n * @callback Mapper~afterCreateManyListener\n * @param {object} records The `records` argument received by {@link Mapper#afterCreateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterCreateMany}.\n * @param {object} result The `result` argument received by {@link Mapper#afterCreateMany}.\n * @see Mapper#event:afterCreateMany\n * @see Mapper#createMany\n * @since 3.0.0\n */\n /**\n * Given an array of records, batch create them via an adapter.\n *\n * {@link Mapper#beforeCreateMany} will be called before calling the adapter.\n * {@link Mapper#afterCreateMany} will be called after calling the adapter.\n *\n * @example\n * // Create and save several new blog posts\n * PostMapper.createMany([{\n * title: 'Modeling your data',\n * status: 'draft'\n * }, {\n * title: 'Reading data',\n * status: 'draft'\n * }]).then((posts) => {\n * console.log(posts[0]); // { id: 1234, status: 'draft', ... }\n * console.log(posts[1]); // { id: 1235, status: 'draft', ... }\n * });\n *\n * @fires Mapper#beforeCreate\n * @fires Mapper#afterCreate\n * @method Mapper#createMany\n * @param {Record[]} records Array of records to be created in one batch.\n * @param {object} [opts] Configuration options. Refer to the `createMany`\n * method of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @param {string[]} [opts.with=[]] Relations to create in a cascading\n * create if `records` contains nested relations. NOT performed in a\n * transaction. Each nested create will result in another {@link Mapper#createMany}\n * call.\n * @param {string[]} [opts.pass=[]] Relations to send to the adapter as part\n * of the payload. Normally relations are not sent.\n * @returns {Promise} Resolves with the created records.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/saving-data\",\"Saving data\"]\n */\n createMany (records, opts) {\n // Default values for arguments\n records || (records = [])\n opts || (opts = {})\n const originalRecords = records\n let adapterResponse\n\n // Fill in \"opts\" with the Mapper's configuration\n utils._(opts, this)\n opts.adapter = this.getAdapterName(opts)\n\n // beforeCreateMany lifecycle hook\n opts.op = 'beforeCreateMany'\n return this._runHook(opts.op, records, opts).then((records) => {\n // Deep pre-create belongsTo relations\n const belongsToRelationData = {}\n opts.with || (opts.with = [])\n let tasks = []\n utils.forEachRelation(this, opts, (def, optsCopy) => {\n const relationData = records\n .map((record) => def.getLocalField(record))\n .filter(Boolean)\n if (def.type === belongsToType && relationData.length === records.length) {\n // Create belongsTo relation first because we need a generated id to\n // attach to the child\n optsCopy.raw = false\n tasks.push(def.createLinked(relationData, optsCopy).then((relatedRecords) => {\n records.forEach((record, i) => def.setForeignKey(record, relatedRecords[i]))\n }).then((relatedRecords) => {\n def.setLocalField(belongsToRelationData, relatedRecords)\n }))\n }\n })\n return utils.Promise.all(tasks).then(() => {\n opts.op = 'createMany'\n return this._invokeAdapterMethod(opts.op, records, opts)\n }).then((result) => {\n adapterResponse = result\n }).then(() => {\n const createdRecordsData = opts.raw ? adapterResponse.data : adapterResponse\n\n // Deep post-create hasOne relations\n tasks = []\n utils.forEachRelation(this, opts, (def, optsCopy) => {\n const relationData = records\n .map((record) => def.getLocalField(record))\n .filter(Boolean)\n if (relationData.length !== records.length) {\n return\n }\n\n optsCopy.raw = false\n const belongsToData = def.getLocalField(belongsToRelationData)\n let task\n // Create hasMany and hasOne after the main create because we needed\n // a generated id to attach to these items\n if (def.type === hasManyType) {\n // Not supported\n this.log('warn', 'deep createMany of hasMany type not supported!')\n } else if (def.type === hasOneType) {\n createdRecordsData.forEach((createdRecordData, i) => {\n def.setForeignKey(createdRecordData, relationData[i])\n })\n task = def.getRelation().createMany(relationData, optsCopy).then((relatedData) => {\n createdRecordsData.forEach((createdRecordData, i) => {\n def.setLocalField(createdRecordData, relatedData[i])\n })\n })\n } else if (def.type === belongsToType && belongsToData && belongsToData.length === createdRecordsData.length) {\n createdRecordsData.forEach((createdRecordData, i) => {\n def.setLocalField(createdRecordData, belongsToData[i])\n })\n }\n if (task) {\n tasks.push(task)\n }\n })\n return utils.Promise.all(tasks).then(() => {\n return this._commitChanges(originalRecords, createdRecordsData)\n })\n })\n }).then((records) => {\n if (opts.raw) {\n adapterResponse.data = records\n } else {\n adapterResponse = records\n }\n const result = this._end(adapterResponse, opts)\n opts.op = 'afterCreateMany'\n return this._runHook(opts.op, records, opts, result)\n })\n },\n\n /**\n * Create an unsaved, uncached instance of this Mapper's\n * {@link Mapper#recordClass}.\n *\n * Returns `props` if `props` is already an instance of\n * {@link Mapper#recordClass}.\n *\n * __Note:__ This method does __not__ interact with any adapter, and does\n * __not__ save any data. It only creates new objects in memory.\n *\n * @example\n * // Create empty unsaved record instance\n * const post = PostMapper.createRecord();\n *\n * @example\n * // Create an unsaved record instance with inital properties\n * const post = PostMapper.createRecord({\n * title: 'Modeling your data',\n * status: 'draft'\n * });\n *\n * @example\n * // Create a record instance that corresponds to a saved record\n * const post = PostMapper.createRecord({\n * // JSData thinks this record has been saved if it has a primary key\n * id: 1234,\n * title: 'Modeling your data',\n * status: 'draft'\n * });\n *\n * @example\n * // Create record instances from an array\n * const posts = PostMapper.createRecord([{\n * title: 'Modeling your data',\n * status: 'draft'\n * }, {\n * title: 'Reading data',\n * status: 'draft'\n * }]);\n *\n * @example\n * // Records are validated by default\n * import { Mapper } from 'js-data';\n * const PostMapper = new Mapper({\n * name: 'post',\n * schema: { properties: { title: { type: 'string' } } }\n * });\n * try {\n * const post = PostMapper.createRecord({\n * title: 1234,\n * });\n * } catch (err) {\n * console.log(err.errors); // [{ expected: 'one of (string)', actual: 'number', path: 'title' }]\n * }\n *\n * @example\n * // Skip validation\n * import { Mapper } from 'js-data';\n * const PostMapper = new Mapper({\n * name: 'post',\n * schema: { properties: { title: { type: 'string' } } }\n * });\n * const post = PostMapper.createRecord({\n * title: 1234,\n * }, { noValidate: true });\n * console.log(post.isValid()); // false\n *\n * @method Mapper#createRecord\n * @param {Object|Object[]} props The properties for the Record instance or an\n * array of property objects for the Record instances.\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}.\n * @returns {Record|Record[]} The Record instance or Record instances.\n * @since 3.0.0\n */\n createRecord (props, opts) {\n props || (props = {})\n if (utils.isArray(props)) {\n return props.map((_props) => this.createRecord(_props, opts))\n }\n if (!utils.isObject(props)) {\n throw utils.err(`${DOMAIN}#createRecord`, 'props')(400, 'array or object', props)\n }\n\n if (this.relationList) {\n this.relationList.forEach(function (def) {\n def.ensureLinkedDataHasProperType(props, opts)\n })\n }\n const RecordCtor = this.recordClass\n\n return (!RecordCtor || props instanceof RecordCtor) ? props : new RecordCtor(props, opts)\n },\n\n /**\n * Lifecycle invocation method. You probably won't call this method directly.\n *\n * @method Mapper#crud\n * @param {string} method Name of the lifecycle method to invoke.\n * @param {...*} args Arguments to pass to the lifecycle method.\n * @returns {Promise}\n * @since 3.0.0\n */\n crud (method, ...args) {\n const config = this.lifecycleMethods[method]\n if (!config) {\n throw utils.err(`${DOMAIN}#crud`, method)(404, 'method')\n }\n\n const upper = `${method.charAt(0).toUpperCase()}${method.substr(1)}`\n const before = `before${upper}`\n const after = `after${upper}`\n\n let op, adapter\n\n // Default values for arguments\n config.defaults.forEach((value, i) => {\n if (args[i] === undefined) {\n args[i] = utils.copy(value)\n }\n })\n\n const opts = args[args.length - 1]\n\n // Fill in \"opts\" with the Mapper's configuration\n utils._(opts, this)\n adapter = opts.adapter = this.getAdapterName(opts)\n\n // before lifecycle hook\n op = opts.op = before\n return utils.resolve(this[op](...args)).then((_value) => {\n if (args[config.beforeAssign] !== undefined) {\n // Allow for re-assignment from lifecycle hook\n args[config.beforeAssign] = _value === undefined ? args[config.beforeAssign] : _value\n }\n // Now delegate to the adapter\n op = opts.op = method\n args = config.adapterArgs ? config.adapterArgs(this, ...args) : args\n this.dbg(op, ...args)\n return utils.resolve(this.getAdapter(adapter)[op](this, ...args))\n }).then((result) => {\n result = this._end(result, opts, !!config.skip)\n args.push(result)\n // after lifecycle hook\n op = opts.op = after\n return utils.resolve(this[op](...args)).then((_result) => {\n // Allow for re-assignment from lifecycle hook\n return _result === undefined ? result : _result\n })\n })\n },\n\n /**\n * Fired during {@link Mapper#destroy}. See\n * {@link Mapper~beforeDestroyListener} for how to listen for this event.\n *\n * @event Mapper#beforeDestroy\n * @see Mapper~beforeDestroyListener\n * @see Mapper#destroy\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeDestroy} event.\n *\n * @example\n * function onBeforeDestroy (id, opts) {\n * // do something\n * }\n * store.on('beforeDestroy', onBeforeDestroy);\n *\n * @callback Mapper~beforeDestroyListener\n * @param {string|number} id The `id` argument passed to {@link Mapper#beforeDestroy}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#beforeDestroy}.\n * @see Mapper#event:beforeDestroy\n * @see Mapper#destroy\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#destroy}. See\n * {@link Mapper~afterDestroyListener} for how to listen for this event.\n *\n * @event Mapper#afterDestroy\n * @see Mapper~afterDestroyListener\n * @see Mapper#destroy\n */\n /**\n * Callback signature for the {@link Mapper#event:afterDestroy} event.\n *\n * @example\n * function onAfterDestroy (id, opts, result) {\n * // do something\n * }\n * store.on('afterDestroy', onAfterDestroy);\n *\n * @callback Mapper~afterDestroyListener\n * @param {string|number} id The `id` argument passed to {@link Mapper#afterDestroy}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#afterDestroy}.\n * @param {object} result The `result` argument passed to {@link Mapper#afterDestroy}.\n * @see Mapper#event:afterDestroy\n * @see Mapper#destroy\n * @since 3.0.0\n */\n /**\n * Using an adapter, destroy the record with the given primary key.\n *\n * {@link Mapper#beforeDestroy} will be called before destroying the record.\n * {@link Mapper#afterDestroy} will be called after destroying the record.\n *\n * @example\n * // Destroy a specific blog post\n * PostMapper.destroy(1234).then(() => {\n * // Blog post #1234 has been destroyed\n * });\n *\n * @example\n * // Get full response\n * PostMapper.destroy(1234, { raw: true }).then((result) => {\n * console.log(result.deleted); e.g. 1\n * console.log(...); // etc., more metadata can be found on the result\n * });\n *\n * @fires Mapper#beforeDestroy\n * @fires Mapper#afterDestroy\n * @method Mapper#destroy\n * @param {(string|number)} id The primary key of the record to destroy.\n * @param {object} [opts] Configuration options. Refer to the `destroy` method\n * of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @returns {Promise} Resolves when the record has been destroyed. Resolves\n * even if no record was found to be destroyed.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/saving-data\",\"Saving data\"]\n */\n destroy (id, opts) {\n return this.crud('destroy', id, opts)\n },\n\n /**\n * Fired during {@link Mapper#destroyAll}. See\n * {@link Mapper~beforeDestroyAllListener} for how to listen for this event.\n *\n * @event Mapper#beforeDestroyAll\n * @see Mapper~beforeDestroyAllListener\n * @see Mapper#destroyAll\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeDestroyAll} event.\n *\n * @example\n * function onBeforeDestroyAll (query, opts) {\n * // do something\n * }\n * store.on('beforeDestroyAll', onBeforeDestroyAll);\n *\n * @callback Mapper~beforeDestroyAllListener\n * @param {object} query The `query` argument passed to {@link Mapper#beforeDestroyAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#beforeDestroyAll}.\n * @see Mapper#event:beforeDestroyAll\n * @see Mapper#destroyAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#destroyAll}. See\n * {@link Mapper~afterDestroyAllListener} for how to listen for this event.\n *\n * @event Mapper#afterDestroyAll\n * @see Mapper~afterDestroyAllListener\n * @see Mapper#destroyAll\n */\n /**\n * Callback signature for the {@link Mapper#event:afterDestroyAll} event.\n *\n * @example\n * function onAfterDestroyAll (query, opts, result) {\n * // do something\n * }\n * store.on('afterDestroyAll', onAfterDestroyAll);\n *\n * @callback Mapper~afterDestroyAllListener\n * @param {object} query The `query` argument passed to {@link Mapper#afterDestroyAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#afterDestroyAll}.\n * @param {object} result The `result` argument passed to {@link Mapper#afterDestroyAll}.\n * @see Mapper#event:afterDestroyAll\n * @see Mapper#destroyAll\n * @since 3.0.0\n */\n /**\n * Destroy the records selected by `query` via an adapter. If no `query` is\n * provided then all records will be destroyed.\n *\n * {@link Mapper#beforeDestroyAll} will be called before destroying the records.\n * {@link Mapper#afterDestroyAll} will be called after destroying the records.\n *\n * @example\n * // Destroy all blog posts\n * PostMapper.destroyAll().then(() => {\n * // All blog posts have been destroyed\n * });\n *\n * @example\n * // Destroy all \"draft\" blog posts\n * PostMapper.destroyAll({ status: 'draft' }).then(() => {\n * // All \"draft\" blog posts have been destroyed\n * });\n *\n * @example\n * // Get full response\n * const query = null;\n * const options = { raw: true };\n * PostMapper.destroyAll(query, options).then((result) => {\n * console.log(result.deleted); e.g. 14\n * console.log(...); // etc., more metadata can be found on the result\n * });\n *\n * @fires Mapper#beforeDestroyAll\n * @fires Mapper#afterDestroyAll\n * @method Mapper#destroyAll\n * @param {object} [query={}] Selection query. See {@link query}.\n * @param {object} [query.where] See {@link query.where}.\n * @param {number} [query.offset] See {@link query.offset}.\n * @param {number} [query.limit] See {@link query.limit}.\n * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}.\n * @param {object} [opts] Configuration options. Refer to the `destroyAll`\n * method of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @returns {Promise} Resolves when the records have been destroyed. Resolves\n * even if no records were found to be destroyed.\n * @see query\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/saving-data\",\"Saving data\"]\n */\n destroyAll (query, opts) {\n return this.crud('destroyAll', query, opts)\n },\n\n /**\n * Fired during {@link Mapper#find}. See\n * {@link Mapper~beforeFindListener} for how to listen for this event.\n *\n * @event Mapper#beforeFind\n * @see Mapper~beforeFindListener\n * @see Mapper#find\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeFind} event.\n *\n * @example\n * function onBeforeFind (id, opts) {\n * // do something\n * }\n * store.on('beforeFind', onBeforeFind);\n *\n * @callback Mapper~beforeFindListener\n * @param {string|number} id The `id` argument passed to {@link Mapper#beforeFind}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#beforeFind}.\n * @see Mapper#event:beforeFind\n * @see Mapper#find\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#find}. See\n * {@link Mapper~afterFindListener} for how to listen for this event.\n *\n * @event Mapper#afterFind\n * @see Mapper~afterFindListener\n * @see Mapper#find\n */\n /**\n * Callback signature for the {@link Mapper#event:afterFind} event.\n *\n * @example\n * function onAfterFind (id, opts, result) {\n * // do something\n * }\n * store.on('afterFind', onAfterFind);\n *\n * @callback Mapper~afterFindListener\n * @param {string|number} id The `id` argument passed to {@link Mapper#afterFind}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#afterFind}.\n * @param {object} result The `result` argument passed to {@link Mapper#afterFind}.\n * @see Mapper#event:afterFind\n * @see Mapper#find\n * @since 3.0.0\n */\n /**\n * Retrieve via an adapter the record with the given primary key.\n *\n * {@link Mapper#beforeFind} will be called before calling the adapter.\n * {@link Mapper#afterFind} will be called after calling the adapter.\n *\n * @example\n * PostMapper.find(1).then((post) => {\n * console.log(post); // { id: 1, ...}\n * });\n *\n * @example\n * // Get full response\n * PostMapper.find(1, { raw: true }).then((result) => {\n * console.log(result.data); // { id: 1, ...}\n * console.log(result.found); // 1\n * console.log(...); // etc., more metadata can be found on the result\n * });\n *\n * @fires Mapper#beforeFind\n * @fires Mapper#afterFind\n * @method Mapper#find\n * @param {(string|number)} id The primary key of the record to retrieve.\n * @param {object} [opts] Configuration options. Refer to the `find` method\n * of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @param {string[]} [opts.with=[]] Relations to eager load in the request.\n * @returns {Promise} Resolves with the found record. Resolves with\n * `undefined` if no record was found.\n * @see http://www.js-data.io/v3.0/docs/reading-data\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/reading-data\",\"Reading data\"]\n */\n find (id, opts) {\n return this.crud('find', id, opts)\n },\n\n /**\n * Fired during {@link Mapper#findAll}. See\n * {@link Mapper~beforeFindAllListener} for how to listen for this event.\n *\n * @event Mapper#beforeFindAll\n * @see Mapper~beforeFindAllListener\n * @see Mapper#findAll\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeFindAll} event.\n *\n * @example\n * function onBeforeFindAll (query, opts) {\n * // do something\n * }\n * store.on('beforeFindAll', onBeforeFindAll);\n *\n * @callback Mapper~beforeFindAllListener\n * @param {object} query The `query` argument passed to {@link Mapper#beforeFindAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#beforeFindAll}.\n * @see Mapper#event:beforeFindAll\n * @see Mapper#findAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#findAll}. See\n * {@link Mapper~afterFindAllListener} for how to listen for this event.\n *\n * @event Mapper#afterFindAll\n * @see Mapper~afterFindAllListener\n * @see Mapper#findAll\n */\n /**\n * Callback signature for the {@link Mapper#event:afterFindAll} event.\n *\n * @example\n * function onAfterFindAll (query, opts, result) {\n * // do something\n * }\n * store.on('afterFindAll', onAfterFindAll);\n *\n * @callback Mapper~afterFindAllListener\n * @param {object} query The `query` argument passed to {@link Mapper#afterFindAll}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#afterFindAll}.\n * @param {object} result The `result` argument passed to {@link Mapper#afterFindAll}.\n * @see Mapper#event:afterFindAll\n * @see Mapper#findAll\n * @since 3.0.0\n */\n /**\n * Using the `query` argument, select records to retrieve via an adapter.\n *\n * {@link Mapper#beforeFindAll} will be called before calling the adapter.\n * {@link Mapper#afterFindAll} will be called after calling the adapter.\n *\n * @example\n * // Find all \"published\" blog posts\n * PostMapper.findAll({ status: 'published' }).then((posts) => {\n * console.log(posts); // [{ id: 1, status: 'published', ...}, ...]\n * });\n *\n * @example\n * // Get full response\n * PostMapper.findAll({ status: 'published' }, { raw: true }).then((result) => {\n * console.log(result.data); // [{ id: 1, status: 'published', ...}, ...]\n * console.log(result.found); // e.g. 13\n * console.log(...); // etc., more metadata can be found on the result\n * });\n *\n * @fires Mapper#beforeFindAll\n * @fires Mapper#afterFindAll\n * @method Mapper#findAll\n * @param {object} [query={}] Selection query. See {@link query}.\n * @param {object} [query.where] See {@link query.where}.\n * @param {number} [query.offset] See {@link query.offset}.\n * @param {number} [query.limit] See {@link query.limit}.\n * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}.\n * @param {object} [opts] Configuration options. Refer to the `findAll` method\n * of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @param {string[]} [opts.with=[]] Relations to eager load in the request.\n * @returns {Promise} Resolves with the found records, if any.\n * @see query\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/reading-data\",\"Reading data\"]\n */\n findAll (query, opts) {\n return this.crud('findAll', query, opts)\n },\n\n /**\n * Return the registered adapter with the given name or the default adapter if\n * no name is provided.\n *\n * @method Mapper#getAdapter\n * @param {string} [name] The name of the adapter to retrieve.\n * @returns {Adapter} The adapter.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/connecting-to-a-data-source\",\"Connecting to a data source\"]\n */\n getAdapter (name) {\n this.dbg('getAdapter', 'name:', name)\n const adapter = this.getAdapterName(name)\n if (!adapter) {\n throw utils.err(`${DOMAIN}#getAdapter`, 'name')(400, 'string', name)\n }\n return this.getAdapters()[adapter]\n },\n\n /**\n * Return the name of a registered adapter based on the given name or options,\n * or the name of the default adapter if no name provided.\n *\n * @method Mapper#getAdapterName\n * @param {(Object|string)} [opts] The name of an adapter or options, if any.\n * @returns {string} The name of the adapter.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/connecting-to-a-data-source\",\"Connecting to a data source\"]\n */\n getAdapterName (opts) {\n opts || (opts = {})\n if (utils.isString(opts)) {\n opts = { adapter: opts }\n }\n return opts.adapter || opts.defaultAdapter\n },\n\n /**\n * Get the object of registered adapters for this Mapper.\n *\n * @method Mapper#getAdapters\n * @returns {Object} {@link Mapper#_adapters}\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/connecting-to-a-data-source\",\"Connecting to a data source\"]\n */\n getAdapters () {\n return this._adapters\n },\n\n /**\n * Returns this Mapper's {@link Schema}.\n *\n * @method Mapper#getSchema\n * @returns {Schema} This Mapper's {@link Schema}.\n * @see Mapper#schema\n * @since 3.0.0\n */\n getSchema () {\n return this.schema\n },\n\n /**\n * Defines a hasMany relationship. Only useful if you're managing your\n * Mappers manually and not using a Container or DataStore component.\n *\n * @example\n * UserMapper.hasMany(PostMapper, {\n * // post.user_id points to user.id\n * foreignKey: 'user_id'\n * // post records will be attached to user records at \"user.posts\"\n * localField: 'posts'\n * });\n *\n * @method Mapper#hasMany\n * @see http://www.js-data.io/v3.0/docs/relations\n * @since 3.0.0\n */\n hasMany (relatedMapper, opts) {\n return hasMany(relatedMapper, opts)(this)\n },\n\n /**\n * Defines a hasOne relationship. Only useful if you're managing your Mappers\n * manually and not using a {@link Container} or {@link DataStore} component.\n *\n * @example\n * UserMapper.hasOne(ProfileMapper, {\n * // profile.user_id points to user.id\n * foreignKey: 'user_id'\n * // profile records will be attached to user records at \"user.profile\"\n * localField: 'profile'\n * });\n *\n * @method Mapper#hasOne\n * @see http://www.js-data.io/v3.0/docs/relations\n * @since 3.0.0\n */\n hasOne (relatedMapper, opts) {\n return hasOne(relatedMapper, opts)(this)\n },\n\n /**\n * Return whether `record` is an instance of this Mapper's recordClass.\n *\n * @example\n * const post = PostMapper.createRecord();\n *\n * console.log(PostMapper.is(post)); // true\n * // Equivalent to what's above\n * console.log(post instanceof PostMapper.recordClass); // true\n *\n * @method Mapper#is\n * @param {Object|Record} record The record to check.\n * @returns {boolean} Whether `record` is an instance of this Mapper's\n * {@link Mapper#recordClass}.\n * @since 3.0.0\n */\n is (record) {\n const recordClass = this.recordClass\n return recordClass ? record instanceof recordClass : false\n },\n\n /**\n * Register an adapter on this Mapper under the given name.\n *\n * @method Mapper#registerAdapter\n * @param {string} name The name of the adapter to register.\n * @param {Adapter} adapter The adapter to register.\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.default=false] Whether to make the adapter the\n * default adapter for this Mapper.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/connecting-to-a-data-source\",\"Connecting to a data source\"]\n */\n registerAdapter (name, adapter, opts) {\n opts || (opts = {})\n this.getAdapters()[name] = adapter\n // Optionally make it the default adapter for the target.\n if (opts === true || opts.default) {\n this.defaultAdapter = name\n }\n },\n\n _runHook (hookName, ...hookArgs) {\n const defaultValueIndex = hookName.indexOf('after') === 0 ? hookArgs.length - 1 : 0\n\n return utils.resolve(this[hookName](...hookArgs))\n .then((overridenResult) => overridenResult === undefined ? hookArgs[defaultValueIndex] : overridenResult)\n },\n\n _invokeAdapterMethod (method, propsOrRecords, opts) {\n const conversionOptions = { with: opts.pass || [] }\n let object\n\n this.dbg(opts.op, propsOrRecords, opts)\n\n if (utils.isArray(propsOrRecords)) {\n object = propsOrRecords.map(record => this.toJSON(record, conversionOptions))\n } else {\n object = this.toJSON(propsOrRecords, conversionOptions)\n }\n\n return this.getAdapter(opts.adapter)[method](this, object, opts)\n },\n\n /**\n * Select records according to the `query` argument, and aggregate the sum\n * value of the property specified by `field`.\n *\n * {@link Mapper#beforeSum} will be called before calling the adapter.\n * {@link Mapper#afterSum} will be called after calling the adapter.\n *\n * @example\n * PurchaseOrderMapper.sum('amount', { status: 'paid' }).then((amountPaid) => {\n * console.log(amountPaid); // e.g. 451125.34\n * });\n *\n * @method Mapper#sum\n * @param {string} field The field to sum.\n * @param {object} [query={}] Selection query. See {@link query}.\n * @param {object} [query.where] See {@link query.where}.\n * @param {number} [query.offset] See {@link query.offset}.\n * @param {number} [query.limit] See {@link query.limit}.\n * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}.\n * @param {object} [opts] Configuration options. Refer to the `sum` method\n * of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @returns {Promise} Resolves with the aggregated sum.\n * @since 3.0.0\n */\n sum (field, query, opts) {\n return this.crud('sum', field, query, opts)\n },\n\n /**\n * Return a plain object representation of the given record. Relations can\n * be optionally be included. Non-schema properties can be excluded.\n *\n * @example\n * import { Mapper, Schema } from 'js-data';\n * const PersonMapper = new Mapper({\n * name: 'person',\n * schema: {\n * properties: {\n * name: { type: 'string' },\n * id: { type: 'string' }\n * }\n * }\n * });\n * const person = PersonMapper.createRecord({ id: 1, name: 'John', foo: 'bar' });\n * // \"foo\" is stripped by toJSON()\n * console.log(PersonMapper.toJSON(person)); // {\"id\":1,\"name\":\"John\"}\n *\n * const PersonRelaxedMapper = new Mapper({\n * name: 'personRelaxed',\n * schema: {\n * properties: {\n * name: { type: 'string' },\n * id: { type: 'string' }\n * },\n * additionalProperties: true\n * }\n * });\n * const person2 = PersonRelaxedMapper.createRecord({ id: 1, name: 'John', foo: 'bar' });\n * // \"foo\" is not stripped by toJSON\n * console.log(PersonRelaxedMapper.toJSON(person2)); // {\"id\":1,\"name\":\"John\",\"foo\":\"bar\"}\n *\n * @method Mapper#toJSON\n * @param {Record|Record[]} records Record or records from which to create a\n * POJO representation.\n * @param {object} [opts] Configuration options.\n * @param {string[]} [opts.with] Array of relation names or relation fields\n * to include in the POJO representation.\n * @param {boolean} [opts.withAll] Whether to simply include all relations in\n * the representation. Overrides `opts.with`.\n * @returns {Object|Object[]} POJO representation of the record or records.\n * @since 3.0.0\n */\n toJSON (records, opts) {\n let record\n opts || (opts = {})\n if (utils.isArray(records)) {\n return records.map((record) => this.toJSON(record, opts))\n } else {\n record = records\n }\n const relationFields = (this ? this.relationFields : []) || []\n let json = {}\n\n // Copy properties defined in the schema\n if (this && this.schema) {\n json = this.schema.pick(record)\n } else {\n for (var key in record) {\n if (relationFields.indexOf(key) === -1) {\n json[key] = utils.plainCopy(record[key])\n }\n }\n }\n\n // The user wants to include relations in the resulting plain object representation\n if (this && opts.withAll) {\n opts.with = relationFields.slice()\n }\n if (this && opts.with) {\n if (utils.isString(opts.with)) {\n opts.with = [opts.with]\n }\n utils.forEachRelation(this, opts, (def, optsCopy) => {\n const relationData = def.getLocalField(record)\n if (relationData) {\n // The actual recursion\n if (utils.isArray(relationData)) {\n def.setLocalField(json, relationData.map((item) => {\n return def.getRelation().toJSON(item, optsCopy)\n }))\n } else {\n def.setLocalField(json, def.getRelation().toJSON(relationData, optsCopy))\n }\n }\n })\n }\n return json\n },\n\n /**\n * Fired during {@link Mapper#update}. See\n * {@link Mapper~beforeUpdateListener} for how to listen for this event.\n *\n * @event Mapper#beforeUpdate\n * @see Mapper~beforeUpdateListener\n * @see Mapper#update\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeUpdate} event.\n *\n * @example\n * function onBeforeUpdate (id, props, opts) {\n * // do something\n * }\n * store.on('beforeUpdate', onBeforeUpdate);\n *\n * @callback Mapper~beforeUpdateListener\n * @param {string|number} id The `id` argument passed to {@link Mapper#beforeUpdate}.\n * @param {object} props The `props` argument passed to {@link Mapper#beforeUpdate}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#beforeUpdate}.\n * @see Mapper#event:beforeUpdate\n * @see Mapper#update\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#update}. See\n * {@link Mapper~afterUpdateListener} for how to listen for this event.\n *\n * @event Mapper#afterUpdate\n * @see Mapper~afterUpdateListener\n * @see Mapper#update\n */\n /**\n * Callback signature for the {@link Mapper#event:afterUpdate} event.\n *\n * @example\n * function onAfterUpdate (id, props, opts, result) {\n * // do something\n * }\n * store.on('afterUpdate', onAfterUpdate);\n *\n * @callback Mapper~afterUpdateListener\n * @param {string|number} id The `id` argument passed to {@link Mapper#afterUpdate}.\n * @param {object} props The `props` argument passed to {@link Mapper#afterUpdate}.\n * @param {object} opts The `opts` argument passed to {@link Mapper#afterUpdate}.\n * @param {object} result The `result` argument passed to {@link Mapper#afterUpdate}.\n * @see Mapper#event:afterUpdate\n * @see Mapper#update\n * @since 3.0.0\n */\n /**\n * Using an adapter, update the record with the primary key specified by the\n * `id` argument.\n *\n * {@link Mapper#beforeUpdate} will be called before updating the record.\n * {@link Mapper#afterUpdate} will be called after updating the record.\n *\n * @example\n * // Update a specific post\n * PostMapper.update(1234, {\n * status: 'published',\n * published_at: new Date()\n * }).then((post) => {\n * console.log(post); // { id: 1234, status: 'published', ... }\n * });\n *\n * @fires Mapper#beforeUpdate\n * @fires Mapper#afterUpdate\n * @method Mapper#update\n * @param {(string|number)} id The primary key of the record to update.\n * @param {object} props The update to apply to the record.\n * @param {object} [opts] Configuration options. Refer to the `update` method\n * of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * transaction.\n * @returns {Promise} Resolves with the updated record. Rejects if the record\n * could not be found.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/saving-data\",\"Saving data\"]\n */\n update (id, props, opts) {\n return this.crud('update', id, props, opts)\n },\n\n /**\n * Fired during {@link Mapper#updateAll}. See\n * {@link Mapper~beforeUpdateAllListener} for how to listen for this event.\n *\n * @event Mapper#beforeUpdateAll\n * @see Mapper~beforeUpdateAllListener\n * @see Mapper#updateAll\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeUpdateAll} event.\n *\n * @example\n * function onBeforeUpdateAll (props, query, opts) {\n * // do something\n * }\n * store.on('beforeUpdateAll', onBeforeUpdateAll);\n *\n * @callback Mapper~beforeUpdateAllListener\n * @param {object} props The `props` argument received by {@link Mapper#beforeUpdateAll}.\n * @param {object} query The `query` argument received by {@link Mapper#beforeUpdateAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateAll}.\n * @see Mapper#event:beforeUpdateAll\n * @see Mapper#updateAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#updateAll}. See\n * {@link Mapper~afterUpdateAllListener} for how to listen for this event.\n *\n * @event Mapper#afterUpdateAll\n * @see Mapper~afterUpdateAllListener\n * @see Mapper#updateAll\n */\n /**\n * Callback signature for the {@link Mapper#event:afterUpdateAll} event.\n *\n * @example\n * function onAfterUpdateAll (props, query, opts, result) {\n * // do something\n * }\n * store.on('afterUpdateAll', onAfterUpdateAll);\n *\n * @callback Mapper~afterUpdateAllListener\n * @param {object} props The `props` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} query The `query` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} result The `result` argument received by {@link Mapper#afterUpdateAll}.\n * @see Mapper#event:afterUpdateAll\n * @see Mapper#updateAll\n * @since 3.0.0\n */\n /**\n * Using the `query` argument, perform the a single updated to the selected\n * records.\n *\n * {@link Mapper#beforeUpdateAll} will be called before making the update.\n * {@link Mapper#afterUpdateAll} will be called after making the update.\n *\n * @example\n * // Turn all of John's blog posts into drafts.\n * const update = { status: draft: published_at: null };\n * const query = { userId: 1234 };\n * PostMapper.updateAll(update, query).then((posts) => {\n * console.log(posts); // [...]\n * });\n *\n * @fires Mapper#beforeUpdateAll\n * @fires Mapper#afterUpdateAll\n * @method Mapper#updateAll\n * @param {object} props Update to apply to selected records.\n * @param {object} [query={}] Selection query. See {@link query}.\n * @param {object} [query.where] See {@link query.where}.\n * @param {number} [query.offset] See {@link query.offset}.\n * @param {number} [query.limit] See {@link query.limit}.\n * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}.\n * @param {object} [opts] Configuration options. Refer to the `updateAll`\n * method of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @returns {Promise} Resolves with the update records, if any.\n * @see query\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/saving-data\",\"Saving data\"]\n */\n updateAll (props, query, opts) {\n return this.crud('updateAll', props, query, opts)\n },\n\n /**\n * Fired during {@link Mapper#updateMany}. See\n * {@link Mapper~beforeUpdateManyListener} for how to listen for this event.\n *\n * @event Mapper#beforeUpdateMany\n * @see Mapper~beforeUpdateManyListener\n * @see Mapper#updateMany\n */\n /**\n * Callback signature for the {@link Mapper#event:beforeUpdateMany} event.\n *\n * @example\n * function onBeforeUpdateMany (records, opts) {\n * // do something\n * }\n * store.on('beforeUpdateMany', onBeforeUpdateMany);\n *\n * @callback Mapper~beforeUpdateManyListener\n * @param {object} records The `records` argument received by {@link Mapper#beforeUpdateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateMany}.\n * @see Mapper#event:beforeUpdateMany\n * @see Mapper#updateMany\n * @since 3.0.0\n */\n /**\n * Fired during {@link Mapper#updateMany}. See\n * {@link Mapper~afterUpdateManyListener} for how to listen for this event.\n *\n * @event Mapper#afterUpdateMany\n * @see Mapper~afterUpdateManyListener\n * @see Mapper#updateMany\n */\n /**\n * Callback signature for the {@link Mapper#event:afterUpdateMany} event.\n *\n * @example\n * function onAfterUpdateMany (records, opts, result) {\n * // do something\n * }\n * store.on('afterUpdateMany', onAfterUpdateMany);\n *\n * @callback Mapper~afterUpdateManyListener\n * @param {object} records The `records` argument received by {@link Mapper#afterUpdateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateMany}.\n * @param {object} result The `result` argument received by {@link Mapper#afterUpdateMany}.\n * @see Mapper#event:afterUpdateMany\n * @see Mapper#updateMany\n * @since 3.0.0\n */\n /**\n * Given an array of updates, perform each of the updates via an adapter. Each\n * \"update\" is a hash of properties with which to update an record. Each\n * update must contain the primary key of the record to be updated.\n *\n * {@link Mapper#beforeUpdateMany} will be called before making the update.\n * {@link Mapper#afterUpdateMany} will be called after making the update.\n *\n * @example\n * PostMapper.updateMany([\n * { id: 1234, status: 'draft' },\n * { id: 2468, status: 'published', published_at: new Date() }\n * ]).then((posts) => {\n * console.log(posts); // [...]\n * });\n *\n * @fires Mapper#beforeUpdateMany\n * @fires Mapper#afterUpdateMany\n * @method Mapper#updateMany\n * @param {Record[]} records Array up record updates.\n * @param {object} [opts] Configuration options. Refer to the `updateMany`\n * method of whatever adapter you're using for more configuration options.\n * @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the\n * adapter to use.\n * @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.\n * @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}.\n * @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.\n * @returns {Promise} Resolves with the updated records. Rejects if any of the\n * records could be found.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/saving-data\",\"Saving data\"]\n */\n updateMany (records, opts) {\n return this.crud('updateMany', records, opts)\n },\n\n /**\n * Validate the given record or records according to this Mapper's\n * {@link Schema}. If there are no validation errors then the return value\n * will be `undefined`.\n *\n * @example\n * import {Mapper, Schema} from 'js-data'\n * const PersonSchema = new Schema({\n * properties: {\n * name: { type: 'string' },\n * id: { type: 'string' }\n * }\n * });\n * const PersonMapper = new Mapper({\n * name: 'person',\n * schema: PersonSchema\n * });\n * let errors = PersonMapper.validate({ name: 'John' });\n * console.log(errors); // undefined\n * errors = PersonMapper.validate({ name: 123 });\n * console.log(errors); // [{ expected: 'one of (string)', actual: 'number', path: 'name' }]\n *\n * @method Mapper#validate\n * @param {Object|Object[]} record The record or records to validate.\n * @param {object} [opts] Configuration options. Passed to\n * {@link Schema#validate}.\n * @returns {Object[]} Array of errors or `undefined` if no errors.\n * @since 3.0.0\n */\n validate (record, opts) {\n opts || (opts = {})\n const schema = this.getSchema()\n if (!schema) {\n return\n }\n const _opts = utils.pick(opts, ['existingOnly'])\n if (utils.isArray(record)) {\n const errors = record.map((_record) => schema.validate(_record, utils.pick(_opts, ['existingOnly'])))\n\n return errors.some(Boolean) ? errors : undefined\n }\n return schema.validate(record, _opts)\n },\n\n /**\n * Method used to wrap data returned by an adapter with this Mapper's\n * {@link Mapper#recordClass}. This method is used by all of a Mapper's CRUD\n * methods. The provided implementation of this method assumes that the `data`\n * passed to it is a record or records that need to be wrapped with\n * {@link Mapper#createRecord}. Override with care.\n *\n * Provided implementation of {@link Mapper#wrap}:\n *\n * ```\n * function (data, opts) {\n * return this.createRecord(data, opts);\n * }\n * ```\n *\n * @example\n * const PostMapper = new Mapper({\n * name: 'post',\n * // Override to customize behavior\n * wrap (data, opts) {\n * const originalWrap = this.constructor.prototype.wrap;\n * // Let's say \"GET /post\" doesn't return JSON quite like JSData expects,\n * // but the actual post records are nested under a \"posts\" field. So,\n * // we override Mapper#wrap to handle this special case.\n * if (opts.op === 'findAll') {\n * return originalWrap.call(this, data.posts, opts);\n * }\n * // Otherwise perform original behavior\n * return originalWrap.call(this, data, opts);\n * }\n * });\n *\n * @method Mapper#wrap\n * @param {Object|Object[]} data The record or records to be wrapped.\n * @param {object} [opts] Configuration options. Passed to {@link Mapper#createRecord}.\n * @returns {Record|Record[]} The wrapped record or records.\n * @since 3.0.0\n */\n wrap (data, opts) {\n return this.createRecord(data, opts)\n },\n\n /**\n * @ignore\n */\n defineRelations () {\n // Setup the mapper's relations, including generating Mapper#relationList\n // and Mapper#relationFields\n utils.forOwn(this.relations, (group, type) => {\n utils.forOwn(group, (relations, _name) => {\n if (utils.isObject(relations)) {\n relations = [relations]\n }\n relations.forEach((def) => {\n const relatedMapper = this.datastore.getMapperByName(_name) || _name\n def.getRelation = () => this.datastore.getMapper(_name)\n\n if (typeof Relation[type] !== 'function') {\n throw utils.err(DOMAIN, 'defineRelations')(400, 'relation type (hasOne, hasMany, etc)', type, true)\n }\n\n this[type](relatedMapper, def)\n })\n })\n })\n }\n})\n\n/**\n * Create a subclass of this Mapper:\n *\n * @example Mapper.extend\n * const JSData = require('js-data');\n * const { Mapper } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomMapperClass extends Mapper {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * };\n * const customMapper = new CustomMapperClass();\n * console.log(customMapper.foo());\n * console.log(CustomMapperClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherMapperClass = Mapper.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherMapper = new OtherMapperClass();\n * console.log(otherMapper.foo());\n * console.log(OtherMapperClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherMapperClass () {\n * Mapper.call(this);\n * this.created_at = new Date().getTime();\n * }\n * Mapper.extend({\n * constructor: AnotherMapperClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * })\n * const anotherMapper = new AnotherMapperClass();\n * console.log(anotherMapper.created_at);\n * console.log(anotherMapper.foo());\n * console.log(AnotherMapperClass.beep());\n *\n * @method Mapper.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this Mapper class.\n * @since 3.0.0\n */\n","import utils from './utils'\nimport Component from './Component'\nimport Mapper from './Mapper'\n\nconst DOMAIN = 'Container'\n\nexport const proxiedMapperMethods = [\n /**\n * Wrapper for {@link Mapper#count}.\n *\n * @example\n * // Get the number of published blog posts\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.count('post', { status: 'published' }).then((numPublished) => {\n * console.log(numPublished); // e.g. 45\n * });\n *\n * @method Container#count\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} [query] See {@link Mapper#count}.\n * @param {object} [opts] See {@link Mapper#count}.\n * @returns {Promise} See {@link Mapper#count}.\n * @see Mapper#count\n * @since 3.0.0\n */\n 'count',\n\n /**\n * Fired during {@link Container#create}. See\n * {@link Container~beforeCreateListener} for how to listen for this event.\n *\n * @event Container#beforeCreate\n * @see Container~beforeCreateListener\n * @see Container#create\n */\n /**\n * Callback signature for the {@link Container#event:beforeCreate} event.\n *\n * @example\n * function onBeforeCreate (mapperName, props, opts) {\n * // do something\n * }\n * store.on('beforeCreate', onBeforeCreate);\n *\n * @callback Container~beforeCreateListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeCreate}.\n * @param {object} props The `props` argument received by {@link Mapper#beforeCreate}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreate}.\n * @see Container#event:beforeCreate\n * @see Container#create\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#create}. See\n * {@link Container~afterCreateListener} for how to listen for this event.\n *\n * @event Container#afterCreate\n * @see Container~afterCreateListener\n * @see Container#create\n */\n /**\n * Callback signature for the {@link Container#event:afterCreate} event.\n *\n * @example\n * function onAfterCreate (mapperName, props, opts, result) {\n * // do something\n * }\n * store.on('afterCreate', onAfterCreate);\n *\n * @callback Container~afterCreateListener\n * @param {string} name The `name` argument received by {@link Mapper#afterCreate}.\n * @param {object} props The `props` argument received by {@link Mapper#afterCreate}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterCreate}.\n * @param {object} result The `result` argument received by {@link Mapper#afterCreate}.\n * @see Container#event:afterCreate\n * @see Container#create\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#create}.\n *\n * @example\n * // Create and save a new blog post\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.create('post', {\n * title: 'Modeling your data',\n * status: 'draft'\n * }).then((post) => {\n * console.log(post); // { id: 1234, status: 'draft', ... }\n * });\n *\n * @fires Container#beforeCreate\n * @fires Container#afterCreate\n * @method Container#create\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} props See {@link Mapper#create}.\n * @param {object} [opts] See {@link Mapper#create}.\n * @returns {Promise} See {@link Mapper#create}.\n * @see Mapper#create\n * @since 3.0.0\n */\n 'create',\n\n /**\n * Fired during {@link Container#createMany}. See\n * {@link Container~beforeCreateManyListener} for how to listen for this event.\n *\n * @event Container#beforeCreateMany\n * @see Container~beforeCreateManyListener\n * @see Container#createMany\n */\n /**\n * Callback signature for the {@link Container#event:beforeCreateMany} event.\n *\n * @example\n * function onBeforeCreateMany (mapperName, records, opts) {\n * // do something\n * }\n * store.on('beforeCreateMany', onBeforeCreateMany);\n *\n * @callback Container~beforeCreateManyListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeCreateMany}.\n * @param {object} records The `records` argument received by {@link Mapper#beforeCreateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreateMany}.\n * @see Container#event:beforeCreateMany\n * @see Container#createMany\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#createMany}. See\n * {@link Container~afterCreateManyListener} for how to listen for this event.\n *\n * @event Container#afterCreateMany\n * @see Container~afterCreateManyListener\n * @see Container#createMany\n */\n /**\n * Callback signature for the {@link Container#event:afterCreateMany} event.\n *\n * @example\n * function onAfterCreateMany (mapperName, records, opts, result) {\n * // do something\n * }\n * store.on('afterCreateMany', onAfterCreateMany);\n *\n * @callback Container~afterCreateManyListener\n * @param {string} name The `name` argument received by {@link Mapper#afterCreateMany}.\n * @param {object} records The `records` argument received by {@link Mapper#afterCreateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterCreateMany}.\n * @param {object} result The `result` argument received by {@link Mapper#afterCreateMany}.\n * @see Container#event:afterCreateMany\n * @see Container#createMany\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#createMany}.\n *\n * @example\n * // Create and save several new blog posts\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.createMany('post', [{\n * title: 'Modeling your data',\n * status: 'draft'\n * }, {\n * title: 'Reading data',\n * status: 'draft'\n * }]).then((posts) => {\n * console.log(posts[0]); // { id: 1234, status: 'draft', ... }\n * console.log(posts[1]); // { id: 1235, status: 'draft', ... }\n * });\n *\n * @fires Container#beforeCreateMany\n * @fires Container#afterCreateMany\n * @method Container#createMany\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {Record[]} records See {@link Mapper#createMany}.\n * @param {object} [opts] See {@link Mapper#createMany}.\n * @returns {Promise} See {@link Mapper#createMany}.\n * @see Mapper#createMany\n * @since 3.0.0\n */\n 'createMany',\n\n /**\n * Wrapper for {@link Mapper#createRecord}.\n *\n * __Note:__ This method does __not__ interact with any adapter, and does\n * __not__ save any data. It only creates new objects in memory.\n *\n * @example\n * // Create empty unsaved record instance\n * import { Container } from 'js-data';\n * const store = new Container();\n * store.defineMapper('post');\n * const post = PostMapper.createRecord();\n *\n * @method Container#createRecord\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {Object|Object[]} props See {@link Mapper#createRecord}.\n * @param {object} [opts] See {@link Mapper#createRecord}.\n * @returns {Promise} See {@link Mapper#createRecord}.\n * @see Mapper#createRecord\n * @since 3.0.0\n */\n 'createRecord',\n\n /**\n * Fired during {@link Container#destroy}. See\n * {@link Container~beforeDestroyListener} for how to listen for this event.\n *\n * @event Container#beforeDestroy\n * @see Container~beforeDestroyListener\n * @see Container#destroy\n */\n /**\n * Callback signature for the {@link Container#event:beforeDestroy} event.\n *\n * @example\n * function onBeforeDestroy (mapperName, id, opts) {\n * // do something\n * }\n * store.on('beforeDestroy', onBeforeDestroy);\n *\n * @callback Container~beforeDestroyListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeDestroy}.\n * @param {string|number} id The `id` argument received by {@link Mapper#beforeDestroy}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroy}.\n * @see Container#event:beforeDestroy\n * @see Container#destroy\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#destroy}. See\n * {@link Container~afterDestroyListener} for how to listen for this event.\n *\n * @event Container#afterDestroy\n * @see Container~afterDestroyListener\n * @see Container#destroy\n */\n /**\n * Callback signature for the {@link Container#event:afterDestroy} event.\n *\n * @example\n * function onAfterDestroy (mapperName, id, opts, result) {\n * // do something\n * }\n * store.on('afterDestroy', onAfterDestroy);\n *\n * @callback Container~afterDestroyListener\n * @param {string} name The `name` argument received by {@link Mapper#afterDestroy}.\n * @param {string|number} id The `id` argument received by {@link Mapper#afterDestroy}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterDestroy}.\n * @param {object} result The `result` argument received by {@link Mapper#afterDestroy}.\n * @see Container#event:afterDestroy\n * @see Container#destroy\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#destroy}.\n *\n * @example\n * // Destroy a specific blog post\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.destroy('post', 1234).then(() => {\n * // Blog post #1234 has been destroyed\n * });\n *\n * @fires Container#beforeDestroy\n * @fires Container#afterDestroy\n * @method Container#destroy\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(string|number)} id See {@link Mapper#destroy}.\n * @param {object} [opts] See {@link Mapper#destroy}.\n * @returns {Promise} See {@link Mapper#destroy}.\n * @see Mapper#destroy\n * @since 3.0.0\n */\n 'destroy',\n\n /**\n * Fired during {@link Container#destroyAll}. See\n * {@link Container~beforeDestroyAllListener} for how to listen for this event.\n *\n * @event Container#beforeDestroyAll\n * @see Container~beforeDestroyAllListener\n * @see Container#destroyAll\n */\n /**\n * Callback signature for the {@link Container#event:beforeDestroyAll} event.\n *\n * @example\n * function onBeforeDestroyAll (mapperName, query, opts) {\n * // do something\n * }\n * store.on('beforeDestroyAll', onBeforeDestroyAll);\n *\n * @callback Container~beforeDestroyAllListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeDestroyAll}.\n * @param {object} query The `query` argument received by {@link Mapper#beforeDestroyAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroyAll}.\n * @see Container#event:beforeDestroyAll\n * @see Container#destroyAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#destroyAll}. See\n * {@link Container~afterDestroyAllListener} for how to listen for this event.\n *\n * @event Container#afterDestroyAll\n * @see Container~afterDestroyAllListener\n * @see Container#destroyAll\n */\n /**\n * Callback signature for the {@link Container#event:afterDestroyAll} event.\n *\n * @example\n * function onAfterDestroyAll (mapperName, query, opts, result) {\n * // do something\n * }\n * store.on('afterDestroyAll', onAfterDestroyAll);\n *\n * @callback Container~afterDestroyAllListener\n * @param {string} name The `name` argument received by {@link Mapper#afterDestroyAll}.\n * @param {object} query The `query` argument received by {@link Mapper#afterDestroyAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterDestroyAll}.\n * @param {object} result The `result` argument received by {@link Mapper#afterDestroyAll}.\n * @see Container#event:afterDestroyAll\n * @see Container#destroyAll\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#destroyAll}.\n *\n * @example\n * // Destroy all \"draft\" blog posts\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.destroyAll('post', { status: 'draft' }).then(() => {\n * // All \"draft\" blog posts have been destroyed\n * });\n *\n * @fires Container#beforeDestroyAll\n * @fires Container#afterDestroyAll\n * @method Container#destroyAll\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} [query] See {@link Mapper#destroyAll}.\n * @param {object} [opts] See {@link Mapper#destroyAll}.\n * @returns {Promise} See {@link Mapper#destroyAll}.\n * @see Mapper#destroyAll\n * @since 3.0.0\n */\n 'destroyAll',\n\n /**\n * Fired during {@link Container#find}. See\n * {@link Container~beforeFindListener} for how to listen for this event.\n *\n * @event Container#beforeFind\n * @see Container~beforeFindListener\n * @see Container#find\n */\n /**\n * Callback signature for the {@link Container#event:beforeFind} event.\n *\n * @example\n * function onBeforeFind (mapperName, id, opts) {\n * // do something\n * }\n * store.on('beforeFind', onBeforeFind);\n *\n * @callback Container~beforeFindListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeFind}.\n * @param {string|number} id The `id` argument received by {@link Mapper#beforeFind}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeFind}.\n * @see Container#event:beforeFind\n * @see Container#find\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#find}. See\n * {@link Container~afterFindListener} for how to listen for this event.\n *\n * @event Container#afterFind\n * @see Container~afterFindListener\n * @see Container#find\n */\n /**\n * Callback signature for the {@link Container#event:afterFind} event.\n *\n * @example\n * function onAfterFind (mapperName, id, opts, result) {\n * // do something\n * }\n * store.on('afterFind', onAfterFind);\n *\n * @callback Container~afterFindListener\n * @param {string} name The `name` argument received by {@link Mapper#afterFind}.\n * @param {string|number} id The `id` argument received by {@link Mapper#afterFind}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterFind}.\n * @param {object} result The `result` argument received by {@link Mapper#afterFind}.\n * @see Container#event:afterFind\n * @see Container#find\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#find}.\n *\n * @example\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.find('post', 1).then((post) => {\n * console.log(post) // { id: 1, ...}\n * });\n *\n * @fires Container#beforeFind\n * @fires Container#afterFind\n * @method Container#find\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(string|number)} id See {@link Mapper#find}.\n * @param {object} [opts] See {@link Mapper#find}.\n * @returns {Promise} See {@link Mapper#find}.\n * @see Mapper#find\n * @since 3.0.0\n */\n 'find',\n\n /**\n * Fired during {@link Container#findAll}. See\n * {@link Container~beforeFindAllListener} for how to listen for this event.\n *\n * @event Container#beforeFindAll\n * @see Container~beforeFindAllListener\n * @see Container#findAll\n */\n /**\n * Callback signature for the {@link Container#event:beforeFindAll} event.\n *\n * @example\n * function onBeforeFindAll (mapperName, query, opts) {\n * // do something\n * }\n * store.on('beforeFindAll', onBeforeFindAll);\n *\n * @callback Container~beforeFindAllListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeFindAll}.\n * @param {object} query The `query` argument received by {@link Mapper#beforeFindAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeFindAll}.\n * @see Container#event:beforeFindAll\n * @see Container#findAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#findAll}. See\n * {@link Container~afterFindAllListener} for how to listen for this event.\n *\n * @event Container#afterFindAll\n * @see Container~afterFindAllListener\n * @see Container#findAll\n */\n /**\n * Callback signature for the {@link Container#event:afterFindAll} event.\n *\n * @example\n * function onAfterFindAll (mapperName, query, opts, result) {\n * // do something\n * }\n * store.on('afterFindAll', onAfterFindAll);\n *\n * @callback Container~afterFindAllListener\n * @param {string} name The `name` argument received by {@link Mapper#afterFindAll}.\n * @param {object} query The `query` argument received by {@link Mapper#afterFindAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterFindAll}.\n * @param {object} result The `result` argument received by {@link Mapper#afterFindAll}.\n * @see Container#event:afterFindAll\n * @see Container#findAll\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#createRecord}.\n *\n * @example\n * // Find all \"published\" blog posts\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.findAll('post', { status: 'published' }).then((posts) => {\n * console.log(posts); // [{ id: 1, ...}, ...]\n * });\n *\n * @fires Container#beforeFindAll\n * @fires Container#afterFindAll\n * @method Container#findAll\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} [query] See {@link Mapper#findAll}.\n * @param {object} [opts] See {@link Mapper#findAll}.\n * @returns {Promise} See {@link Mapper#findAll}.\n * @see Mapper#findAll\n * @since 3.0.0\n */\n 'findAll',\n\n /**\n * Wrapper for {@link Mapper#getSchema}.\n *\n * @method Container#getSchema\n * @param {string} name Name of the {@link Mapper} to target.\n * @returns {Schema} See {@link Mapper#getSchema}.\n * @see Mapper#getSchema\n * @since 3.0.0\n */\n 'getSchema',\n\n /**\n * Wrapper for {@link Mapper#is}.\n *\n * @example\n * import { Container } from 'js-data';\n * const store = new Container();\n * store.defineMapper('post');\n * const post = store.createRecord();\n *\n * console.log(store.is('post', post)); // true\n * // Equivalent to what's above\n * console.log(post instanceof store.getMapper('post').recordClass); // true\n *\n * @method Container#is\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {Object|Record} record See {@link Mapper#is}.\n * @returns {boolean} See {@link Mapper#is}.\n * @see Mapper#is\n * @since 3.0.0\n */\n 'is',\n\n /**\n * Wrapper for {@link Mapper#sum}.\n *\n * @example\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('purchase_order');\n *\n * store.sum('purchase_order', 'amount', { status: 'paid' }).then((amountPaid) => {\n * console.log(amountPaid); // e.g. 451125.34\n * });\n *\n * @method Container#sum\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {string} field See {@link Mapper#sum}.\n * @param {object} [query] See {@link Mapper#sum}.\n * @param {object} [opts] See {@link Mapper#sum}.\n * @returns {Promise} See {@link Mapper#sum}.\n * @see Mapper#sum\n * @since 3.0.0\n */\n 'sum',\n\n /**\n * Wrapper for {@link Mapper#toJSON}.\n *\n * @example\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('person', {\n * schema: {\n * properties: {\n * name: { type: 'string' },\n * id: { type: 'string' }\n * }\n * }\n * });\n * const person = store.createRecord('person', { id: 1, name: 'John', foo: 'bar' });\n * // \"foo\" is stripped by toJSON()\n * console.log(store.toJSON('person', person)); // {\"id\":1,\"name\":\"John\"}\n *\n * store.defineMapper('personRelaxed', {\n * schema: {\n * properties: {\n * name: { type: 'string' },\n * id: { type: 'string' }\n * },\n * additionalProperties: true\n * }\n * });\n * const person2 = store.createRecord('personRelaxed', { id: 1, name: 'John', foo: 'bar' });\n * // \"foo\" is not stripped by toJSON\n * console.log(store.toJSON('personRelaxed', person2)); // {\"id\":1,\"name\":\"John\",\"foo\":\"bar\"}\n *\n * @method Container#toJSON\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {Record|Record[]} records See {@link Mapper#toJSON}.\n * @param {object} [opts] See {@link Mapper#toJSON}.\n * @returns {Object|Object[]} See {@link Mapper#toJSON}.\n * @see Mapper#toJSON\n * @since 3.0.0\n */\n 'toJSON',\n\n /**\n * Fired during {@link Container#update}. See\n * {@link Container~beforeUpdateListener} for how to listen for this event.\n *\n * @event Container#beforeUpdate\n * @see Container~beforeUpdateListener\n * @see Container#update\n */\n /**\n * Callback signature for the {@link Container#event:beforeUpdate} event.\n *\n * @example\n * function onBeforeUpdate (mapperName, id, props, opts) {\n * // do something\n * }\n * store.on('beforeUpdate', onBeforeUpdate);\n *\n * @callback Container~beforeUpdateListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeUpdate}.\n * @param {string|number} id The `id` argument received by {@link Mapper#beforeUpdate}.\n * @param {object} props The `props` argument received by {@link Mapper#beforeUpdate}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdate}.\n * @see Container#event:beforeUpdate\n * @see Container#update\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#update}. See\n * {@link Container~afterUpdateListener} for how to listen for this event.\n *\n * @event Container#afterUpdate\n * @see Container~afterUpdateListener\n * @see Container#update\n */\n /**\n * Callback signature for the {@link Container#event:afterUpdate} event.\n *\n * @example\n * function onAfterUpdate (mapperName, id, props, opts, result) {\n * // do something\n * }\n * store.on('afterUpdate', onAfterUpdate);\n *\n * @callback Container~afterUpdateListener\n * @param {string} name The `name` argument received by {@link Mapper#afterUpdate}.\n * @param {string|number} id The `id` argument received by {@link Mapper#afterUpdate}.\n * @param {object} props The `props` argument received by {@link Mapper#afterUpdate}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdate}.\n * @param {object} result The `result` argument received by {@link Mapper#afterUpdate}.\n * @see Container#event:afterUpdate\n * @see Container#update\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#update}.\n *\n * @example\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.update('post', 1234, {\n * status: 'published',\n * published_at: new Date()\n * }).then((post) => {\n * console.log(post); // { id: 1234, status: 'published', ... }\n * });\n *\n * @fires Container#beforeUpdate\n * @fires Container#afterUpdate\n * @method Container#update\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(string|number)} id See {@link Mapper#update}.\n * @param {object} record See {@link Mapper#update}.\n * @param {object} [opts] See {@link Mapper#update}.\n * @returns {Promise} See {@link Mapper#update}.\n * @see Mapper#update\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/saving-data\",\"Saving data\"]\n */\n 'update',\n\n /**\n * Fired during {@link Container#updateAll}. See\n * {@link Container~beforeUpdateAllListener} for how to listen for this event.\n *\n * @event Container#beforeUpdateAll\n * @see Container~beforeUpdateAllListener\n * @see Container#updateAll\n */\n /**\n * Callback signature for the {@link Container#event:beforeUpdateAll} event.\n *\n * @example\n * function onBeforeUpdateAll (mapperName, props, query, opts) {\n * // do something\n * }\n * store.on('beforeUpdateAll', onBeforeUpdateAll);\n *\n * @callback Container~beforeUpdateAllListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeUpdateAll}.\n * @param {object} props The `props` argument received by {@link Mapper#beforeUpdateAll}.\n * @param {object} query The `query` argument received by {@link Mapper#beforeUpdateAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateAll}.\n * @see Container#event:beforeUpdateAll\n * @see Container#updateAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#updateAll}. See\n * {@link Container~afterUpdateAllListener} for how to listen for this event.\n *\n * @event Container#afterUpdateAll\n * @see Container~afterUpdateAllListener\n * @see Container#updateAll\n */\n /**\n * Callback signature for the {@link Container#event:afterUpdateAll} event.\n *\n * @example\n * function onAfterUpdateAll (mapperName, props, query, opts, result) {\n * // do something\n * }\n * store.on('afterUpdateAll', onAfterUpdateAll);\n *\n * @callback Container~afterUpdateAllListener\n * @param {string} name The `name` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} props The `props` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} query The `query` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} result The `result` argument received by {@link Mapper#afterUpdateAll}.\n * @see Container#event:afterUpdateAll\n * @see Container#updateAll\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#updateAll}.\n *\n * @example\n * // Turn all of John's blog posts into drafts.\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * const update = { status: draft: published_at: null };\n * const query = { userId: 1234 };\n * store.updateAll('post', update, query).then((posts) => {\n * console.log(posts); // [...]\n * });\n *\n * @fires Container#beforeUpdateAll\n * @fires Container#afterUpdateAll\n * @method Container#updateAll\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} update See {@link Mapper#updateAll}.\n * @param {object} [query] See {@link Mapper#updateAll}.\n * @param {object} [opts] See {@link Mapper#updateAll}.\n * @returns {Promise} See {@link Mapper#updateAll}.\n * @see Mapper#updateAll\n * @since 3.0.0\n */\n 'updateAll',\n\n /**\n * Fired during {@link Container#updateMany}. See\n * {@link Container~beforeUpdateManyListener} for how to listen for this event.\n *\n * @event Container#beforeUpdateMany\n * @see Container~beforeUpdateManyListener\n * @see Container#updateMany\n */\n /**\n * Callback signature for the {@link Container#event:beforeUpdateMany} event.\n *\n * @example\n * function onBeforeUpdateMany (mapperName, records, opts) {\n * // do something\n * }\n * store.on('beforeUpdateMany', onBeforeUpdateMany);\n *\n * @callback Container~beforeUpdateManyListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeUpdateMany}.\n * @param {object} records The `records` argument received by {@link Mapper#beforeUpdateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateMany}.\n * @see Container#event:beforeUpdateMany\n * @see Container#updateMany\n * @since 3.0.0\n */\n /**\n * Fired during {@link Container#updateMany}. See\n * {@link Container~afterUpdateManyListener} for how to listen for this event.\n *\n * @event Container#afterUpdateMany\n * @see Container~afterUpdateManyListener\n * @see Container#updateMany\n */\n /**\n * Callback signature for the {@link Container#event:afterUpdateMany} event.\n *\n * @example\n * function onAfterUpdateMany (mapperName, records, opts, result) {\n * // do something\n * }\n * store.on('afterUpdateMany', onAfterUpdateMany);\n *\n * @callback Container~afterUpdateManyListener\n * @param {string} name The `name` argument received by {@link Mapper#afterUpdateMany}.\n * @param {object} records The `records` argument received by {@link Mapper#afterUpdateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateMany}.\n * @param {object} result The `result` argument received by {@link Mapper#afterUpdateMany}.\n * @see Container#event:afterUpdateMany\n * @see Container#updateMany\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#updateMany}.\n *\n * @example\n * import { Container } from 'js-data';\n * import RethinkDBAdapter from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n * store.defineMapper('post');\n *\n * store.updateMany('post', [\n * { id: 1234, status: 'draft' },\n * { id: 2468, status: 'published', published_at: new Date() }\n * ]).then((posts) => {\n * console.log(posts); // [...]\n * });\n *\n * @fires Container#beforeUpdateMany\n * @fires Container#afterUpdateMany\n * @method Container#updateMany\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(Object[]|Record[])} records See {@link Mapper#updateMany}.\n * @param {object} [opts] See {@link Mapper#updateMany}.\n * @returns {Promise} See {@link Mapper#updateMany}.\n * @see Mapper#updateMany\n * @since 3.0.0\n */\n 'updateMany',\n\n /**\n * Wrapper for {@link Mapper#validate}.\n *\n * @example\n * import { Container } from 'js-data';\n * const store = new Container();\n * store.defineMapper('post', {\n * schema: {\n * properties: {\n * name: { type: 'string' },\n * id: { type: 'string' }\n * }\n * }\n * });\n * let errors = store.validate('post', { name: 'John' });\n * console.log(errors); // undefined\n * errors = store.validate('post', { name: 123 });\n * console.log(errors); // [{ expected: 'one of (string)', actual: 'number', path: 'name' }]\n *\n * @method Container#validate\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(Object[]|Record[])} records See {@link Mapper#validate}.\n * @param {object} [opts] See {@link Mapper#validate}.\n * @returns {Promise} See {@link Mapper#validate}.\n * @see Mapper#validate\n * @since 3.0.0\n */\n 'validate'\n]\n\n/**\n * The `Container` class is a place to define and store {@link Mapper} instances.\n *\n * `Container` makes it easy to manage your Mappers. Without a container, you\n * need to manage Mappers yourself, including resolving circular dependencies\n * among relations. All Mappers in a container share the same adapters, so you\n * don't have to register adapters for every single Mapper.\n *\n * @example Container#constructor\n * // import { Container } from 'js-data';\n * const JSData = require('js-data');\n * const {Container} = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n *\n * @class Container\n * @extends Component\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.debug=false] See {@link Component#debug}.\n * @param {Constructor} [opts.mapperClass] See {@link Container#mapperClass}.\n * @param {object} [opts.mapperDefaults] See {@link Container#mapperDefaults}.\n * @since 3.0.0\n */\nexport function Container (opts) {\n utils.classCallCheck(this, Container)\n Component.call(this)\n opts || (opts = {})\n\n Object.defineProperties(this, {\n /**\n * The adapters registered with this Container, which are also shared by all\n * Mappers in this Container.\n *\n * @name Container#_adapters\n * @see Container#registerAdapter\n * @since 3.0.0\n * @type {Object}\n */\n _adapters: {\n value: {}\n },\n\n /**\n * The the mappers in this container\n *\n * @name Container#_mappers\n * @see Mapper\n * @since 3.0.0\n * @type {Object}\n */\n _mappers: {\n value: {}\n },\n\n /**\n * Constructor function to use in {@link Container#defineMapper} to create new\n * {@link Mapper} instances. {@link Container#mapperClass} should extend\n * {@link Mapper}. By default {@link Mapper} is used to instantiate Mappers.\n *\n * @example Container#mapperClass\n * // import { Container, Mapper } from 'js-data';\n * const JSData = require('js-data');\n * const { Container, Mapper } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * class MyMapperClass extends Mapper {\n * foo () { return 'bar' }\n * }\n * const store = new Container({\n * mapperClass: MyMapperClass\n * });\n * store.defineMapper('user');\n * console.log(store.getMapper('user').foo());\n *\n * @name Container#mapperClass\n * @see Mapper\n * @since 3.0.0\n * @type {Constructor}\n */\n mapperClass: {\n value: undefined,\n writable: true\n }\n })\n\n // Apply options provided by the user\n utils.fillIn(this, opts)\n\n /**\n * Defaults options to pass to {@link Container#mapperClass} when creating a\n * new {@link Mapper}.\n *\n * @example Container#mapperDefaults\n * // import { Container } from 'js-data';\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container({\n * mapperDefaults: {\n * idAttribute: '_id'\n * }\n * });\n * store.defineMapper('user');\n * console.log(store.getMapper('user').idAttribute);\n *\n * @default {}\n * @name Container#mapperDefaults\n * @since 3.0.0\n * @type {Object}\n */\n this.mapperDefaults = this.mapperDefaults || {}\n\n // Use the Mapper class if the user didn't provide a mapperClass\n this.mapperClass || (this.mapperClass = Mapper)\n}\n\nconst props = {\n constructor: Container,\n\n /**\n * Register a new event listener on this Container.\n *\n * Proxy for {@link Component#on}. If an event was emitted by a {@link Mapper}\n * in the Container, then the name of the {@link Mapper} will be prepended to\n * the arugments passed to the listener.\n *\n * @example Container#on\n * // import { Container } from 'js-data';\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * store.on('foo', function (...args) { console.log(args.join(':')) });\n * store.defineMapper('user');\n * store.emit('foo', 'arg1', 'arg2');\n * store.getMapper('user').emit('foo', 'arg1', 'arg2');\n *\n * @method Container#on\n * @param {string} event Name of event to subsribe to.\n * @param {Function} listener Listener function to handle the event.\n * @param {*} [ctx] Optional content in which to invoke the listener.\n * @since 3.0.0\n */\n\n /**\n * Used to bind to events emitted by mappers in this container.\n *\n * @method Container#_onMapperEvent\n * @param {string} name Name of the mapper that emitted the event.\n * @param {...*} [args] Args See {@link Mapper#emit}.\n * @private\n * @since 3.0.0\n */\n _onMapperEvent (name, ...args) {\n const type = args.shift()\n this.emit(type, name, ...args)\n },\n\n /**\n * Return a container scoped to a particular mapper.\n *\n * @example Container#as\n * // import { Container } from 'js-data';\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * const UserMapper = store.defineMapper('user');\n * const UserStore = store.as('user');\n *\n * const user1 = store.createRecord('user', { name: 'John' });\n * const user2 = UserStore.createRecord({ name: 'John' });\n * const user3 = UserMapper.createRecord({ name: 'John' });\n * console.log(user1 === user2);\n * console.log(user2 === user3);\n * console.log(user1 === user3);\n *\n * @method Container#as\n * @param {string} name Name of the {@link Mapper}.\n * @returns {Object} A container scoped to a particular mapper.\n * @since 3.0.0\n */\n as (name) {\n const props = {}\n const original = this\n proxiedMapperMethods.forEach(function (method) {\n props[method] = {\n writable: true,\n value (...args) {\n return original[method](name, ...args)\n }\n }\n })\n props.getMapper = {\n writable: true,\n value () {\n return original.getMapper(name)\n }\n }\n return Object.create(this, props)\n },\n\n /**\n * Create a new mapper and register it in this container.\n *\n * @example Container#defineMapper\n * // import { Container } from 'js-data';\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container({\n * mapperDefaults: { foo: 'bar' }\n * });\n * // Container#defineMapper returns a direct reference to the newly created\n * // Mapper.\n * const UserMapper = store.defineMapper('user');\n * console.log(UserMapper === store.getMapper('user'));\n * console.log(UserMapper === store.as('user').getMapper());\n * console.log(UserMapper.foo);\n *\n * @method Container#defineMapper\n * @param {string} name Name under which to register the new {@link Mapper}.\n * {@link Mapper#name} will be set to this value.\n * @param {object} [opts] Configuration options. Passed to\n * {@link Container#mapperClass} when creating the new {@link Mapper}.\n * @returns {Mapper} The newly created instance of {@link Mapper}.\n * @see Container#as\n * @since 3.0.0\n */\n defineMapper (name, opts) {\n // For backwards compatibility with defineResource\n if (utils.isObject(name)) {\n opts = name\n name = opts.name\n }\n if (!utils.isString(name)) {\n throw utils.err(`${DOMAIN}#defineMapper`, 'name')(400, 'string', name)\n }\n\n // Default values for arguments\n opts || (opts = {})\n // Set Mapper#name\n opts.name = name\n opts.relations || (opts.relations = {})\n\n // Check if the user is overriding the datastore's default mapperClass\n const mapperClass = opts.mapperClass || this.mapperClass\n delete opts.mapperClass\n\n // Apply the datastore's defaults to the options going into the mapper\n utils.fillIn(opts, this.mapperDefaults)\n\n // Instantiate a mapper\n const mapper = this._mappers[name] = new mapperClass(opts) // eslint-disable-line\n mapper.relations || (mapper.relations = {})\n // Make sure the mapper's name is set\n mapper.name = name\n // All mappers in this datastore will share adapters\n mapper._adapters = this.getAdapters()\n\n mapper.datastore = this\n\n mapper.on('all', (...args) => this._onMapperEvent(name, ...args))\n mapper.defineRelations()\n\n return mapper\n },\n\n defineResource (name, opts) {\n console.warn('DEPRECATED: defineResource is deprecated, use defineMapper instead')\n return this.defineMapper(name, opts)\n },\n\n /**\n * Return the registered adapter with the given name or the default adapter if\n * no name is provided.\n *\n * @method Container#getAdapter\n * @param {string} [name] The name of the adapter to retrieve.\n * @returns {Adapter} The adapter.\n * @since 3.0.0\n */\n getAdapter (name) {\n const adapter = this.getAdapterName(name)\n if (!adapter) {\n throw utils.err(`${DOMAIN}#getAdapter`, 'name')(400, 'string', name)\n }\n return this.getAdapters()[adapter]\n },\n\n /**\n * Return the name of a registered adapter based on the given name or options,\n * or the name of the default adapter if no name provided.\n *\n * @method Container#getAdapterName\n * @param {(Object|string)} [opts] The name of an adapter or options, if any.\n * @returns {string} The name of the adapter.\n * @since 3.0.0\n */\n getAdapterName (opts) {\n opts || (opts = {})\n if (utils.isString(opts)) {\n opts = { adapter: opts }\n }\n return opts.adapter || this.mapperDefaults.defaultAdapter\n },\n\n /**\n * Return the registered adapters of this container.\n *\n * @method Container#getAdapters\n * @returns {Adapter}\n * @since 3.0.0\n */\n getAdapters () {\n return this._adapters\n },\n\n /**\n * Return the mapper registered under the specified name.\n *\n * @example Container#getMapper\n * // import { Container } from 'js-data';\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * // Container#defineMapper returns a direct reference to the newly created\n * // Mapper.\n * const UserMapper = store.defineMapper('user');\n * console.log(UserMapper === store.getMapper('user'));\n * console.log(UserMapper === store.as('user').getMapper());\n * store.getMapper('profile'); // throws Error, there is no mapper with name \"profile\"\n *\n * @method Container#getMapper\n * @param {string} name {@link Mapper#name}.\n * @returns {Mapper}\n * @since 3.0.0\n */\n getMapper (name) {\n const mapper = this.getMapperByName(name)\n if (!mapper) {\n throw utils.err(`${DOMAIN}#getMapper`, name)(404, 'mapper')\n }\n return mapper\n },\n\n /**\n * Return the mapper registered under the specified name.\n * Doesn't throw error if mapper doesn't exist.\n *\n * @example Container#getMapperByName\n * // import { Container } from 'js-data';\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new Container();\n * // Container#defineMapper returns a direct reference to the newly created\n * // Mapper.\n * const UserMapper = store.defineMapper('user');\n * console.log(UserMapper === store.getMapper('user'));\n * console.log(UserMapper === store.as('user').getMapper());\n * console.log(store.getMapper('profile')); // Does NOT throw an error\n *\n * @method Container#getMapperByName\n * @param {string} name {@link Mapper#name}.\n * @returns {Mapper}\n * @since 3.0.0\n */\n getMapperByName (name) {\n return this._mappers[name]\n },\n\n /**\n * Register an adapter on this container under the given name. Adapters\n * registered on a container are shared by all mappers in the container.\n *\n * @example\n * import { Container } from 'js-data';\n * import { RethinkDBAdapter } from 'js-data-rethinkdb';\n * const store = new Container();\n * store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true });\n *\n * @method Container#registerAdapter\n * @param {string} name The name of the adapter to register.\n * @param {Adapter} adapter The adapter to register.\n * @param {object} [opts] Configuration options.\n * @param {boolean} [opts.default=false] Whether to make the adapter the\n * default adapter for all Mappers in this container.\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/connecting-to-a-data-source\",\"Connecting to a data source\"]\n */\n registerAdapter (name, adapter, opts) {\n opts || (opts = {})\n this.getAdapters()[name] = adapter\n // Optionally make it the default adapter for the target.\n if (opts === true || opts.default) {\n this.mapperDefaults.defaultAdapter = name\n utils.forOwn(this._mappers, function (mapper) {\n mapper.defaultAdapter = name\n })\n }\n }\n}\n\nproxiedMapperMethods.forEach(function (method) {\n props[method] = function (name, ...args) {\n return this.getMapper(name)[method](...args)\n }\n})\n\nComponent.extend(props)\n\n/**\n * Create a subclass of this Container:\n * @example Container.extend\n * const JSData = require('js-data');\n * const { Container } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomContainerClass extends Container {\n * foo () { return 'bar' }\n * static beep () { return 'boop' }\n * }\n * const customContainer = new CustomContainerClass();\n * console.log(customContainer.foo());\n * console.log(CustomContainerClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherContainerClass = Container.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherContainer = new OtherContainerClass();\n * console.log(otherContainer.foo());\n * console.log(OtherContainerClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherContainerClass () {\n * Container.call(this);\n * this.created_at = new Date().getTime();\n * }\n * Container.extend({\n * constructor: AnotherContainerClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * })\n * const anotherContainer = new AnotherContainerClass();\n * console.log(anotherContainer.created_at);\n * console.log(anotherContainer.foo());\n * console.log(AnotherContainerClass.beep());\n *\n * @method Container.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this Container class.\n * @since 3.0.0\n */\n","import utils from './utils'\n\nimport {\n belongsToType,\n hasManyType,\n hasOneType\n} from './decorators'\nimport {proxiedMapperMethods, Container} from './Container'\nimport Collection from './Collection'\n\nconst DOMAIN = 'SimpleStore'\nconst proxiedCollectionMethods = [\n /**\n * Wrapper for {@link Collection#add}.\n *\n * @example SimpleStore#add\n * const JSData = require('js-data');\n * const { SimpleStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new SimpleStore();\n * store.defineMapper('book');\n *\n * // Add one book to the in-memory store:\n * store.add('book', { id: 1, title: 'Respect your Data' });\n * // Add multiple books to the in-memory store:\n * store.add('book', [\n * { id: 2, title: 'Easy data recipes' },\n * { id: 3, title: 'Active Record 101' }\n * ]);\n *\n * @fires SimpleStore#add\n * @method SimpleStore#add\n * @param {(string|number)} name Name of the {@link Mapper} to target.\n * @param {(Object|Object[]|Record|Record[])} data See {@link Collection#add}.\n * @param {object} [opts] Configuration options. See {@link Collection#add}.\n * @returns {(Object|Object[]|Record|Record[])} See {@link Collection#add}.\n * @see Collection#add\n * @see Collection#add\n * @since 3.0.0\n */\n 'add',\n\n /**\n * Wrapper for {@link Collection#between}.\n *\n * @example\n * // Get all users ages 18 to 30\n * const users = store.between('user', 18, 30, { index: 'age' });\n *\n * @example\n * // Same as above\n * const users = store.between('user', [18], [30], { index: 'age' });\n *\n * @method SimpleStore#between\n * @param {(string|number)} name Name of the {@link Mapper} to target.\n * @param {array} leftKeys See {@link Collection#between}.\n * @param {array} rightKeys See {@link Collection#between}.\n * @param {object} [opts] Configuration options. See {@link Collection#between}.\n * @returns {Object[]|Record[]} See {@link Collection#between}.\n * @see Collection#between\n * @see Collection#between\n * @since 3.0.0\n */\n 'between',\n\n /**\n * Wrapper for {@link Collection#createIndex}.\n *\n * @example\n * // Index users by age\n * store.createIndex('user', 'age');\n *\n * @example\n * // Index users by status and role\n * store.createIndex('user', 'statusAndRole', ['status', 'role']);\n *\n * @method SimpleStore#createIndex\n * @param {(string|number)} name Name of the {@link Mapper} to target.\n * @param {string} name See {@link Collection#createIndex}.\n * @param {string[]} [fieldList] See {@link Collection#createIndex}.\n * @see Collection#createIndex\n * @see Collection#createIndex\n * @since 3.0.0\n */\n 'createIndex',\n\n /**\n * Wrapper for {@link Collection#filter}.\n *\n * @example SimpleStore#filter\n * const JSData = require('js-data');\n * const { SimpleStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new SimpleStore();\n * store.defineMapper('post');\n * store.add('post', [\n * { id: 1, status: 'draft', created_at_timestamp: new Date().getTime() }\n * ]);\n *\n * // Get the draft posts created less than three months ago\n * let posts = store.filter('post', {\n * where: {\n * status: {\n * '==': 'draft'\n * },\n * created_at_timestamp: {\n * '>=': (new Date().getTime() - (1000 \\* 60 \\* 60 \\* 24 \\* 30 \\* 3)) // 3 months ago\n * }\n * }\n * });\n * console.log(posts);\n *\n * // Use a custom filter function\n * posts = store.filter('post', function (post) { return post.id % 2 === 0 });\n *\n * @method SimpleStore#filter\n * @param {(string|number)} name Name of the {@link Mapper} to target.\n * @param {(Object|Function)} [queryOrFn={}] See {@link Collection#filter}.\n * @param {object} [thisArg] See {@link Collection#filter}.\n * @returns {Array} See {@link Collection#filter}.\n * @see Collection#filter\n * @see Collection#filter\n * @since 3.0.0\n */\n 'filter',\n\n /**\n * Wrapper for {@link Collection#get}.\n *\n * @example SimpleStore#get\n * const JSData = require('js-data');\n * const { SimpleStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new SimpleStore();\n * store.defineMapper('post');\n * store.add('post', [\n * { id: 1, status: 'draft', created_at_timestamp: new Date().getTime() }\n * ]);\n *\n * console.log(store.get('post', 1)); // {...}\n * console.log(store.get('post', 2)); // undefined\n *\n * @method SimpleStore#get\n * @param {(string|number)} name Name of the {@link Mapper} to target.\n * @param {(string|number)} id See {@link Collection#get}.\n * @returns {(Object|Record)} See {@link Collection#get}.\n * @see Collection#get\n * @see Collection#get\n * @since 3.0.0\n */\n 'get',\n\n /**\n * Wrapper for {@link Collection#getAll}.\n *\n * @example\n * // Get the posts where \"status\" is \"draft\" or \"inReview\"\n * const posts = store.getAll('post', 'draft', 'inReview', { index: 'status' });\n *\n * @example\n * // Same as above\n * const posts = store.getAll('post', ['draft'], ['inReview'], { index: 'status' });\n *\n * @method SimpleStore#getAll\n * @param {(string|number)} name Name of the {@link Mapper} to target.\n * @param {...Array} [keyList] See {@link Collection#getAll}.\n * @param {object} [opts] See {@link Collection#getAll}.\n * @returns {Array} See {@link Collection#getAll}.\n * @see Collection#getAll\n * @see Collection#getAll\n * @since 3.0.0\n */\n 'getAll',\n\n /**\n * Wrapper for {@link Collection#prune}.\n *\n * @method SimpleStore#prune\n * @param {object} [opts] See {@link Collection#prune}.\n * @returns {Array} See {@link Collection#prune}.\n * @see Collection#prune\n * @see Collection#prune\n * @since 3.0.0\n */\n 'prune',\n\n /**\n * Wrapper for {@link Collection#query}.\n *\n * @example\n * // Grab page 2 of users between ages 18 and 30\n * store.query('user')\n * .between(18, 30, { index: 'age' }) // between ages 18 and 30\n * .skip(10) // second page\n * .limit(10) // page size\n * .run();\n *\n * @method SimpleStore#query\n * @param {(string|number)} name Name of the {@link Mapper} to target.\n * @returns {Query} See {@link Collection#query}.\n * @see Collection#query\n * @see Collection#query\n * @since 3.0.0\n */\n 'query',\n\n /**\n * Wrapper for {@link Collection#toJSON}.\n *\n * @example\n * store.defineMapper('post', {\n * schema: {\n * properties: {\n * id: { type: 'number' },\n * title: { type: 'string' }\n * }\n * }\n * });\n * store.add('post', [\n * { id: 1, status: 'published', title: 'Respect your Data' },\n * { id: 2, status: 'draft', title: 'Connecting to a data source' }\n * ]);\n * console.log(store.toJSON('post'));\n * const draftsJSON = store.query('post')\n * .filter({ status: 'draft' })\n * .mapCall('toJSON')\n * .run();\n *\n * @method SimpleStore#toJSON\n * @param {(string|number)} name Name of the {@link Mapper} to target.\n * @param {object} [opts] See {@link Collection#toJSON}.\n * @returns {Array} See {@link Collection#toJSON}.\n * @see Collection#toJSON\n * @see Collection#toJSON\n * @since 3.0.0\n */\n 'toJSON',\n\n /**\n * Wrapper for {@link Collection#unsaved}.\n *\n * @method SimpleStore#unsaved\n * @returns {Array} See {@link Collection#unsaved}.\n * @see Collection#unsaved\n * @see Collection#unsaved\n * @since 3.0.0\n */\n 'unsaved'\n]\nconst ownMethodsForScoping = [\n 'addToCache',\n 'cachedFind',\n 'cachedFindAll',\n 'cacheFind',\n 'cacheFindAll',\n 'hashQuery'\n]\n\nconst cachedFn = function (name, hashOrId, opts) {\n const cached = this._completedQueries[name][hashOrId]\n if (utils.isFunction(cached)) {\n return cached(name, hashOrId, opts)\n }\n return cached\n}\n\nconst SIMPLESTORE_DEFAULTS = {\n /**\n * Whether to use the pending query if a `find` request for the specified\n * record is currently underway. Can be set to `true`, `false`, or to a\n * function that returns `true` or `false`.\n *\n * @default true\n * @name SimpleStore#usePendingFind\n * @since 3.0.0\n * @type {boolean|Function}\n */\n usePendingFind: true,\n\n /**\n * Whether to use the pending query if a `findAll` request for the given query\n * is currently underway. Can be set to `true`, `false`, or to a function that\n * returns `true` or `false`.\n *\n * @default true\n * @name SimpleStore#usePendingFindAll\n * @since 3.0.0\n * @type {boolean|Function}\n */\n usePendingFindAll: true\n}\n\n/**\n * The `SimpleStore` class is an extension of {@link Container}. Not only does\n * `SimpleStore` manage mappers, but also collections. `SimpleStore` implements the\n * asynchronous {@link Mapper} methods, such as {@link Mapper#find} and\n * {@link Mapper#create}. If you use the asynchronous `SimpleStore` methods\n * instead of calling them directly on the mappers, then the results of the\n * method calls will be inserted into the store's collections. You can think of\n * a `SimpleStore` as an [Identity Map](https://en.wikipedia.org/wiki/Identity_map_pattern)\n * for the [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping)\n * (the Mappers).\n *\n * ```javascript\n * import { SimpleStore } from 'js-data';\n * ```\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n * const store = new SimpleStore();\n *\n * // SimpleStore#defineMapper returns a direct reference to the newly created\n * // Mapper.\n * const UserMapper = store.defineMapper('user');\n *\n * // SimpleStore#as returns the store scoped to a particular Mapper.\n * const UserStore = store.as('user');\n *\n * // Call \"find\" on \"UserMapper\" (Stateless ORM)\n * UserMapper.find(1).then((user) => {\n * // retrieved a \"user\" record via the http adapter, but that's it\n *\n * // Call \"find\" on \"store\" targeting \"user\" (Stateful SimpleStore)\n * return store.find('user', 1); // same as \"UserStore.find(1)\"\n * }).then((user) => {\n * // not only was a \"user\" record retrieved, but it was added to the\n * // store's \"user\" collection\n * const cachedUser = store.getCollection('user').get(1);\n * console.log(user === cachedUser); // true\n * });\n *\n * @class SimpleStore\n * @extends Container\n * @param {object} [opts] Configuration options. See {@link Container}.\n * @param {boolean} [opts.collectionClass={@link Collection}] See {@link SimpleStore#collectionClass}.\n * @param {boolean} [opts.debug=false] See {@link Component#debug}.\n * @param {boolean|Function} [opts.usePendingFind=true] See {@link SimpleStore#usePendingFind}.\n * @param {boolean|Function} [opts.usePendingFindAll=true] See {@link SimpleStore#usePendingFindAll}.\n * @returns {SimpleStore}\n * @see Container\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#SimpleStore\",\"Components of JSData: SimpleStore\"]\n * @tutorial [\"http://www.js-data.io/v3.0/docs/working-with-the-SimpleStore\",\"Working with the SimpleStore\"]\n * @tutorial [\"http://www.js-data.io/v3.0/docs/jsdata-and-the-browser\",\"Notes on using JSData in the Browser\"]\n */\nfunction SimpleStore (opts) {\n utils.classCallCheck(this, SimpleStore)\n\n opts || (opts = {})\n // Fill in any missing options with the defaults\n utils.fillIn(opts, SIMPLESTORE_DEFAULTS)\n Container.call(this, opts)\n\n this.collectionClass = this.collectionClass || Collection\n this._collections = {}\n this._pendingQueries = {}\n this._completedQueries = {}\n}\n\nconst props = {\n constructor: SimpleStore,\n\n /**\n * Internal method used to handle Mapper responses.\n *\n * @method SimpleStore#_end\n * @private\n * @param {string} name Name of the {@link Collection} to which to\n * add the data.\n * @param {object} result The result from a Mapper.\n * @param {object} [opts] Configuration options.\n * @returns {(Object|Array)} Result.\n */\n _end (name, result, opts) {\n let data = opts.raw ? result.data : result\n if (data && utils.isFunction(this.addToCache)) {\n data = this.addToCache(name, data, opts)\n if (opts.raw) {\n result.data = data\n } else {\n result = data\n }\n }\n return result\n },\n\n /**\n * Register a new event listener on this SimpleStore.\n *\n * Proxy for {@link Container#on}. If an event was emitted by a Mapper or\n * Collection in the SimpleStore, then the name of the Mapper or Collection will\n * be prepended to the arugments passed to the provided event handler.\n *\n * @example\n * // Listen for all \"afterCreate\" events in a SimpleStore\n * store.on('afterCreate', (mapperName, props, opts, result) => {\n * console.log(mapperName); // \"post\"\n * console.log(props.id); // undefined\n * console.log(result.id); // 1234\n * });\n * store.create('post', { title: 'Modeling your data' }).then((post) => {\n * console.log(post.id); // 1234\n * });\n *\n * @example\n * // Listen for the \"add\" event on a collection\n * store.on('add', (mapperName, records) => {\n * console.log(records); // [...]\n * });\n *\n * @example\n * // Listen for \"change\" events on a record\n * store.on('change', (mapperName, record, changes) => {\n * console.log(changes); // { changed: { title: 'Modeling your data' } }\n * });\n * post.title = 'Modeling your data';\n *\n * @method SimpleStore#on\n * @param {string} event Name of event to subsribe to.\n * @param {Function} listener Listener function to handle the event.\n * @param {*} [ctx] Optional content in which to invoke the listener.\n */\n\n /**\n * Used to bind to events emitted by collections in this store.\n *\n * @method SimpleStore#_onCollectionEvent\n * @private\n * @param {string} name Name of the collection that emitted the event.\n * @param {...*} [args] Args passed to {@link Collection#emit}.\n */\n _onCollectionEvent (name, ...args) {\n const type = args.shift()\n this.emit(type, name, ...args)\n },\n\n /**\n * This method takes the data received from {@link SimpleStore#find},\n * {@link SimpleStore#findAll}, {@link SimpleStore#update}, etc., and adds the\n * data to the store. _You don't need to call this method directly._\n *\n * If you're using the http adapter and your response data is in an unexpected\n * format, you may need to override this method so the right data gets added\n * to the store.\n *\n * @example\n * const store = new SimpleStore({\n * addToCache (mapperName, data, opts) {\n * // Let's say for a particular Resource, response data is in a weird format\n * if (name === 'comment') {\n * // Re-assign the variable to add the correct records into the stores\n * data = data.items;\n * }\n * // Now perform default behavior\n * return SimpleStore.prototype.addToCache.call(this, mapperName, data, opts);\n * }\n * });\n *\n * @example\n * // Extend using ES2015 class syntax.\n * class MyStore extends SimpleStore {\n * addToCache (mapperName, data, opts) {\n * // Let's say for a particular Resource, response data is in a weird format\n * if (name === 'comment') {\n * // Re-assign the variable to add the correct records into the stores\n * data = data.items;\n * }\n * // Now perform default behavior\n * return super.addToCache(mapperName, data, opts);\n * }\n * }\n * const store = new MyStore();\n *\n * @method SimpleStore#addToCache\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {*} data Data from which data should be selected for add.\n * @param {object} [opts] Configuration options.\n */\n addToCache (name, data, opts) {\n return this.getCollection(name).add(data, opts)\n },\n\n /**\n * Return the store scoped to a particular mapper/collection pair.\n *\n * @example SimpleStore.as\n * const JSData = require('js-data');\n * const { SimpleStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new SimpleStore();\n * const UserMapper = store.defineMapper('user');\n * const UserStore = store.as('user');\n *\n * const user1 = store.createRecord('user', { name: 'John' });\n * const user2 = UserStore.createRecord({ name: 'John' });\n * const user3 = UserMapper.createRecord({ name: 'John' });\n * console.log(user1 === user2);\n * console.log(user2 === user3);\n * console.log(user1 === user3);\n *\n * @method SimpleStore#as\n * @param {string} name Name of the {@link Mapper}.\n * @returns {Object} The store, scoped to a particular Mapper/Collection pair.\n * @since 3.0.0\n */\n as (name) {\n const props = {}\n const original = this\n const methods = ownMethodsForScoping\n .concat(proxiedMapperMethods)\n .concat(proxiedCollectionMethods)\n\n methods.forEach(function (method) {\n props[method] = {\n writable: true,\n value (...args) {\n return original[method](name, ...args)\n }\n }\n })\n props.getMapper = {\n writable: true,\n value () {\n return original.getMapper(name)\n }\n }\n props.getCollection = {\n writable: true,\n value () {\n return original.getCollection(name)\n }\n }\n return Object.create(this, props)\n },\n\n /**\n * Retrieve a cached `find` result, if any. This method is called during\n * {@link SimpleStore#find} to determine if {@link Mapper#find} needs to be\n * called. If this method returns `undefined` then {@link Mapper#find} will\n * be called. Otherwise {@link SimpleStore#find} will immediately resolve with\n * the return value of this method.\n *\n * When using {@link SimpleStore} in the browser, you can override this method\n * to implement your own cache-busting strategy.\n *\n * @example\n * const store = new SimpleStore({\n * cachedFind (mapperName, id, opts) {\n * // Let's say for a particular Resource, we always want to pull fresh from the server\n * if (mapperName === 'schedule') {\n * // Return undefined to trigger a Mapper#find call\n * return;\n * }\n * // Otherwise perform default behavior\n * return SimpleStore.prototype.cachedFind.call(this, mapperName, id, opts);\n * }\n * });\n *\n * @example\n * // Extend using ES2015 class syntax.\n * class MyStore extends SimpleStore {\n * cachedFind (mapperName, id, opts) {\n * // Let's say for a particular Resource, we always want to pull fresh from the server\n * if (mapperName === 'schedule') {\n * // Return undefined to trigger a Mapper#find call\n * return;\n * }\n * // Otherwise perform default behavior\n * return super.cachedFind(mapperName, id, opts);\n * }\n * }\n * const store = new MyStore();\n *\n * @method SimpleStore#cachedFind\n * @param {string} name The `name` argument passed to {@link SimpleStore#find}.\n * @param {(string|number)} id The `id` argument passed to {@link SimpleStore#find}.\n * @param {object} opts The `opts` argument passed to {@link SimpleStore#find}.\n * @since 3.0.0\n */\n cachedFind: cachedFn,\n\n /**\n * Retrieve a cached `findAll` result, if any. This method is called during\n * {@link SimpleStore#findAll} to determine if {@link Mapper#findAll} needs to be\n * called. If this method returns `undefined` then {@link Mapper#findAll} will\n * be called. Otherwise {@link SimpleStore#findAll} will immediately resolve with\n * the return value of this method.\n *\n * When using {@link SimpleStore} in the browser, you can override this method\n * to implement your own cache-busting strategy.\n *\n * @example\n * const store = new SimpleStore({\n * cachedFindAll (mapperName, hash, opts) {\n * // Let's say for a particular Resource, we always want to pull fresh from the server\n * if (mapperName === 'schedule') {\n * // Return undefined to trigger a Mapper#findAll call\n * return undefined;\n * }\n * // Otherwise perform default behavior\n * return SimpleStore.prototype.cachedFindAll.call(this, mapperName, hash, opts);\n * }\n * });\n *\n * @example\n * // Extend using ES2015 class syntax.\n * class MyStore extends SimpleStore {\n * cachedFindAll (mapperName, hash, opts) {\n * // Let's say for a particular Resource, we always want to pull fresh from the server\n * if (mapperName === 'schedule') {\n * // Return undefined to trigger a Mapper#findAll call\n * return undefined;\n * }\n * // Otherwise perform default behavior\n * return super.cachedFindAll(mapperName, hash, opts);\n * }\n * }\n * const store = new MyStore();\n *\n * @method SimpleStore#cachedFindAll\n * @param {string} name The `name` argument passed to {@link SimpleStore#findAll}.\n * @param {string} hash The result of calling {@link SimpleStore#hashQuery} on\n * the `query` argument passed to {@link SimpleStore#findAll}.\n * @param {object} opts The `opts` argument passed to {@link SimpleStore#findAll}.\n * @since 3.0.0\n */\n cachedFindAll: cachedFn,\n\n /**\n * Mark a {@link Mapper#find} result as cached by adding an entry to\n * {@link SimpleStore#_completedQueries}. By default, once a `find` entry is\n * added it means subsequent calls to the same Resource with the same `id`\n * argument will immediately resolve with the result of calling\n * {@link SimpleStore#get} instead of delegating to {@link Mapper#find}.\n *\n * As part of implementing your own caching strategy, you may choose to\n * override this method.\n *\n * @example\n * const store = new SimpleStore({\n * cacheFind (mapperName, data, id, opts) {\n * // Let's say for a particular Resource, we always want to pull fresh from the server\n * if (mapperName === 'schedule') {\n * // Return without saving an entry to SimpleStore#_completedQueries\n * return;\n * }\n * // Otherwise perform default behavior\n * return SimpleStore.prototype.cacheFind.call(this, mapperName, data, id, opts);\n * }\n * });\n *\n * @example\n * // Extend using ES2015 class syntax.\n * class MyStore extends SimpleStore {\n * cacheFind (mapperName, data, id, opts) {\n * // Let's say for a particular Resource, we always want to pull fresh from the server\n * if (mapperName === 'schedule') {\n * // Return without saving an entry to SimpleStore#_completedQueries\n * return;\n * }\n * // Otherwise perform default behavior\n * return super.cacheFind(mapperName, data, id, opts);\n * }\n * }\n * const store = new MyStore();\n *\n * @method SimpleStore#cacheFind\n * @param {string} name The `name` argument passed to {@link SimpleStore#find}.\n * @param {*} data The result to cache.\n * @param {(string|number)} id The `id` argument passed to {@link SimpleStore#find}.\n * @param {object} opts The `opts` argument passed to {@link SimpleStore#find}.\n * @since 3.0.0\n */\n cacheFind (name, data, id, opts) {\n this._completedQueries[name][id] = (name, id, opts) => this.get(name, id)\n },\n\n /**\n * Mark a {@link Mapper#findAll} result as cached by adding an entry to\n * {@link SimpleStore#_completedQueries}. By default, once a `findAll` entry is\n * added it means subsequent calls to the same Resource with the same `query`\n * argument will immediately resolve with the result of calling\n * {@link SimpleStore#filter} instead of delegating to {@link Mapper#findAll}.\n *\n * As part of implementing your own caching strategy, you may choose to\n * override this method.\n *\n * @example\n * const store = new SimpleStore({\n * cachedFindAll (mapperName, data, hash, opts) {\n * // Let's say for a particular Resource, we always want to pull fresh from the server\n * if (mapperName === 'schedule') {\n * // Return without saving an entry to SimpleStore#_completedQueries\n * return;\n * }\n * // Otherwise perform default behavior.\n * return SimpleStore.prototype.cachedFindAll.call(this, mapperName, data, hash, opts);\n * }\n * });\n *\n * @example\n * // Extend using ES2015 class syntax.\n * class MyStore extends SimpleStore {\n * cachedFindAll (mapperName, data, hash, opts) {\n * // Let's say for a particular Resource, we always want to pull fresh from the server\n * if (mapperName === 'schedule') {\n * // Return without saving an entry to SimpleStore#_completedQueries\n * return;\n * }\n * // Otherwise perform default behavior.\n * return super.cachedFindAll(mapperName, data, hash, opts);\n * }\n * }\n * const store = new MyStore();\n *\n * @method SimpleStore#cacheFindAll\n * @param {string} name The `name` argument passed to {@link SimpleStore#findAll}.\n * @param {*} data The result to cache.\n * @param {string} hash The result of calling {@link SimpleStore#hashQuery} on\n * the `query` argument passed to {@link SimpleStore#findAll}.\n * @param {object} opts The `opts` argument passed to {@link SimpleStore#findAll}.\n * @since 3.0.0\n */\n cacheFindAll (name, data, hash, opts) {\n this._completedQueries[name][hash] = (name, hash, opts) => this.filter(name, utils.fromJson(hash))\n },\n\n /**\n * Remove __all__ records from the in-memory store and reset\n * {@link SimpleStore#_completedQueries}.\n *\n * @method SimpleStore#clear\n * @returns {Object} Object containing all records that were in the store.\n * @see SimpleStore#remove\n * @see SimpleStore#removeAll\n * @since 3.0.0\n */\n clear () {\n const removed = {}\n utils.forOwn(this._collections, (collection, name) => {\n removed[name] = collection.removeAll()\n this._completedQueries[name] = {}\n })\n return removed\n },\n\n /**\n * Fired during {@link SimpleStore#create}. See\n * {@link SimpleStore~beforeCreateListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeCreate\n * @see SimpleStore~beforeCreateListener\n * @see SimpleStore#create\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeCreate} event.\n *\n * @example\n * function onBeforeCreate (mapperName, props, opts) {\n * // do something\n * }\n * store.on('beforeCreate', onBeforeCreate);\n *\n * @callback SimpleStore~beforeCreateListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeCreate}.\n * @param {object} props The `props` argument received by {@link Mapper#beforeCreate}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreate}.\n * @see SimpleStore#event:beforeCreate\n * @see SimpleStore#create\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#create}. See\n * {@link SimpleStore~afterCreateListener} for how to listen for this event.\n *\n * @event SimpleStore#afterCreate\n * @see SimpleStore~afterCreateListener\n * @see SimpleStore#create\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterCreate} event.\n *\n * @example\n * function onAfterCreate (mapperName, props, opts, result) {\n * // do something\n * }\n * store.on('afterCreate', onAfterCreate);\n *\n * @callback SimpleStore~afterCreateListener\n * @param {string} name The `name` argument received by {@link Mapper#afterCreate}.\n * @param {object} props The `props` argument received by {@link Mapper#afterCreate}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterCreate}.\n * @param {object} result The `result` argument received by {@link Mapper#afterCreate}.\n * @see SimpleStore#event:afterCreate\n * @see SimpleStore#create\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#create}. Adds the created record to the store.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('book');\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // POST /book {\"author_id\":1234,...}\n * store.create('book', {\n * author_id: 1234,\n * edition: 'First Edition',\n * title: 'Respect your Data'\n * }).then((book) => {\n * console.log(book.id); // 120392\n * console.log(book.title); // \"Respect your Data\"\n * });\n *\n * @fires SimpleStore#beforeCreate\n * @fires SimpleStore#afterCreate\n * @fires SimpleStore#add\n * @method SimpleStore#create\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} record Passed to {@link Mapper#create}.\n * @param {object} [opts] Passed to {@link Mapper#create}. See\n * {@link Mapper#create} for more configuration options.\n * @returns {Promise} Resolves with the result of the create.\n * @since 3.0.0\n */\n create (name, record, opts) {\n opts || (opts = {})\n return Container.prototype.create.call(this, name, record, opts)\n .then((result) => this._end(name, result, opts))\n },\n\n /**\n * Fired during {@link SimpleStore#createMany}. See\n * {@link SimpleStore~beforeCreateManyListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeCreateMany\n * @see SimpleStore~beforeCreateManyListener\n * @see SimpleStore#createMany\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeCreateMany} event.\n *\n * @example\n * function onBeforeCreateMany (mapperName, records, opts) {\n * // do something\n * }\n * store.on('beforeCreateMany', onBeforeCreateMany);\n *\n * @callback SimpleStore~beforeCreateManyListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeCreateMany}.\n * @param {object} records The `records` argument received by {@link Mapper#beforeCreateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeCreateMany}.\n * @see SimpleStore#event:beforeCreateMany\n * @see SimpleStore#createMany\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#createMany}. See\n * {@link SimpleStore~afterCreateManyListener} for how to listen for this event.\n *\n * @event SimpleStore#afterCreateMany\n * @see SimpleStore~afterCreateManyListener\n * @see SimpleStore#createMany\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterCreateMany} event.\n *\n * @example\n * function onAfterCreateMany (mapperName, records, opts, result) {\n * // do something\n * }\n * store.on('afterCreateMany', onAfterCreateMany);\n *\n * @callback SimpleStore~afterCreateManyListener\n * @param {string} name The `name` argument received by {@link Mapper#afterCreateMany}.\n * @param {object} records The `records` argument received by {@link Mapper#afterCreateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterCreateMany}.\n * @param {object} result The `result` argument received by {@link Mapper#afterCreateMany}.\n * @see SimpleStore#event:afterCreateMany\n * @see SimpleStore#createMany\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#createMany}. Adds the created records to the\n * store.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('book');\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // POST /book [{\"author_id\":1234,...},{...}]\n * store.createMany('book', [{\n * author_id: 1234,\n * edition: 'First Edition',\n * title: 'Respect your Data'\n * }, {\n * author_id: 1234,\n * edition: 'Second Edition',\n * title: 'Respect your Data'\n * }]).then((books) => {\n * console.log(books[0].id); // 142394\n * console.log(books[0].title); // \"Respect your Data\"\n * });\n *\n * @fires SimpleStore#beforeCreateMany\n * @fires SimpleStore#afterCreateMany\n * @fires SimpleStore#add\n * @method SimpleStore#createMany\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {array} records Passed to {@link Mapper#createMany}.\n * @param {object} [opts] Passed to {@link Mapper#createMany}. See\n * {@link Mapper#createMany} for more configuration options.\n * @returns {Promise} Resolves with the result of the create.\n * @since 3.0.0\n */\n createMany (name, records, opts) {\n opts || (opts = {})\n return Container.prototype.createMany.call(this, name, records, opts)\n .then((result) => this._end(name, result, opts))\n },\n\n defineMapper (name, opts) {\n const self = this\n const mapper = Container.prototype.defineMapper.call(self, name, opts)\n self._pendingQueries[name] = {}\n self._completedQueries[name] = {}\n mapper.relationList || Object.defineProperty(mapper, 'relationList', { value: [] })\n\n let collectionOpts = {\n // Make sure the collection has somewhere to store \"added\" timestamps\n _added: {},\n // Give the collection a reference to this SimpleStore\n datastore: self,\n // The mapper tied to the collection\n mapper\n }\n\n if (opts && ('onConflict' in opts)) {\n collectionOpts.onConflict = opts.onConflict\n }\n\n // The SimpleStore uses a subclass of Collection that is \"SimpleStore-aware\"\n const collection = self._collections[name] = new self.collectionClass(null, collectionOpts) // eslint-disable-line\n\n const schema = mapper.schema || {}\n const properties = schema.properties || {}\n // TODO: Make it possible index nested properties?\n utils.forOwn(properties, function (opts, prop) {\n if (opts.indexed) {\n collection.createIndex(prop)\n }\n })\n\n // Create a secondary index on the \"added\" timestamps of records in the\n // collection\n collection.createIndex('addedTimestamps', ['$'], {\n fieldGetter (obj) {\n return collection._added[collection.recordId(obj)]\n }\n })\n\n collection.on('all', function (...args) {\n self._onCollectionEvent(name, ...args)\n })\n\n return mapper\n },\n\n /**\n * Fired during {@link SimpleStore#destroy}. See\n * {@link SimpleStore~beforeDestroyListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeDestroy\n * @see SimpleStore~beforeDestroyListener\n * @see SimpleStore#destroy\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeDestroy} event.\n *\n * @example\n * function onBeforeDestroy (mapperName, id, opts) {\n * // do something\n * }\n * store.on('beforeDestroy', onBeforeDestroy);\n *\n * @callback SimpleStore~beforeDestroyListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeDestroy}.\n * @param {string|number} id The `id` argument received by {@link Mapper#beforeDestroy}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroy}.\n * @see SimpleStore#event:beforeDestroy\n * @see SimpleStore#destroy\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#destroy}. See\n * {@link SimpleStore~afterDestroyListener} for how to listen for this event.\n *\n * @event SimpleStore#afterDestroy\n * @see SimpleStore~afterDestroyListener\n * @see SimpleStore#destroy\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterDestroy} event.\n *\n * @example\n * function onAfterDestroy (mapperName, id, opts, result) {\n * // do something\n * }\n * store.on('afterDestroy', onAfterDestroy);\n *\n * @callback SimpleStore~afterDestroyListener\n * @param {string} name The `name` argument received by {@link Mapper#afterDestroy}.\n * @param {string|number} id The `id` argument received by {@link Mapper#afterDestroy}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterDestroy}.\n * @param {object} result The `result` argument received by {@link Mapper#afterDestroy}.\n * @see SimpleStore#event:afterDestroy\n * @see SimpleStore#destroy\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#destroy}. Removes any destroyed record from the\n * in-memory store. Clears out any {@link SimpleStore#_completedQueries} entries\n * associated with the provided `id`.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('book');\n *\n * store.add('book', { id: 1234, title: 'Data Management is Hard' });\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // DELETE /book/1234\n * store.destroy('book', 1234).then(() => {\n * // The book record is no longer in the in-memory store\n * console.log(store.get('book', 1234)); // undefined\n *\n * return store.find('book', 1234);\n * }).then((book) {\n * // The book was deleted from the database too\n * console.log(book); // undefined\n * });\n *\n * @fires SimpleStore#beforeDestroy\n * @fires SimpleStore#afterDestroy\n * @fires SimpleStore#remove\n * @method SimpleStore#destroy\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(string|number)} id Passed to {@link Mapper#destroy}.\n * @param {object} [opts] Passed to {@link Mapper#destroy}. See\n * {@link Mapper#destroy} for more configuration options.\n * @returns {Promise} Resolves when the destroy operation completes.\n * @since 3.0.0\n */\n destroy (name, id, opts) {\n opts || (opts = {})\n return Container.prototype.destroy.call(this, name, id, opts).then((result) => {\n const record = this.getCollection(name).remove(id, opts)\n\n if (opts.raw) {\n result.data = record\n } else {\n result = record\n }\n delete this._pendingQueries[name][id]\n delete this._completedQueries[name][id]\n return result\n })\n },\n\n /**\n * Fired during {@link SimpleStore#destroyAll}. See\n * {@link SimpleStore~beforeDestroyAllListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeDestroyAll\n * @see SimpleStore~beforeDestroyAllListener\n * @see SimpleStore#destroyAll\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeDestroyAll} event.\n *\n * @example\n * function onBeforeDestroyAll (mapperName, query, opts) {\n * // do something\n * }\n * store.on('beforeDestroyAll', onBeforeDestroyAll);\n *\n * @callback SimpleStore~beforeDestroyAllListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeDestroyAll}.\n * @param {object} query The `query` argument received by {@link Mapper#beforeDestroyAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroyAll}.\n * @see SimpleStore#event:beforeDestroyAll\n * @see SimpleStore#destroyAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#destroyAll}. See\n * {@link SimpleStore~afterDestroyAllListener} for how to listen for this event.\n *\n * @event SimpleStore#afterDestroyAll\n * @see SimpleStore~afterDestroyAllListener\n * @see SimpleStore#destroyAll\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterDestroyAll} event.\n *\n * @example\n * function onAfterDestroyAll (mapperName, query, opts, result) {\n * // do something\n * }\n * store.on('afterDestroyAll', onAfterDestroyAll);\n *\n * @callback SimpleStore~afterDestroyAllListener\n * @param {string} name The `name` argument received by {@link Mapper#afterDestroyAll}.\n * @param {object} query The `query` argument received by {@link Mapper#afterDestroyAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterDestroyAll}.\n * @param {object} result The `result` argument received by {@link Mapper#afterDestroyAll}.\n * @see SimpleStore#event:afterDestroyAll\n * @see SimpleStore#destroyAll\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#destroyAll}. Removes any destroyed records from\n * the in-memory store.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('book');\n *\n * store.add('book', { id: 1234, title: 'Data Management is Hard' });\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // DELETE /book/1234\n * store.destroy('book', 1234).then(() => {\n * // The book record is gone from the in-memory store\n * console.log(store.get('book', 1234)); // undefined\n * return store.find('book', 1234);\n * }).then((book) {\n * // The book was deleted from the database too\n * console.log(book); // undefined\n * });\n *\n * @fires SimpleStore#beforeDestroyAll\n * @fires SimpleStore#afterDestroyAll\n * @fires SimpleStore#remove\n * @method SimpleStore#destroyAll\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} [query] Passed to {@link Mapper#destroyAll}.\n * @param {object} [opts] Passed to {@link Mapper#destroyAll}. See\n * {@link Mapper#destroyAll} for more configuration options.\n * @returns {Promise} Resolves when the delete completes.\n * @since 3.0.0\n */\n destroyAll (name, query, opts) {\n opts || (opts = {})\n return Container.prototype.destroyAll.call(this, name, query, opts).then((result) => {\n const records = this.getCollection(name).removeAll(query, opts)\n\n if (opts.raw) {\n result.data = records\n } else {\n result = records\n }\n const hash = this.hashQuery(name, query, opts)\n delete this._pendingQueries[name][hash]\n delete this._completedQueries[name][hash]\n return result\n })\n },\n\n eject (name, id, opts) {\n console.warn('DEPRECATED: \"eject\" is deprecated, use \"remove\" instead')\n return this.remove(name, id, opts)\n },\n\n ejectAll (name, query, opts) {\n console.warn('DEPRECATED: \"ejectAll\" is deprecated, use \"removeAll\" instead')\n return this.removeAll(name, query, opts)\n },\n\n /**\n * Fired during {@link SimpleStore#find}. See\n * {@link SimpleStore~beforeFindListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeFind\n * @see SimpleStore~beforeFindListener\n * @see SimpleStore#find\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeFind} event.\n *\n * @example\n * function onBeforeFind (mapperName, id, opts) {\n * // do something\n * }\n * store.on('beforeFind', onBeforeFind);\n *\n * @callback SimpleStore~beforeFindListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeFind}.\n * @param {string|number} id The `id` argument received by {@link Mapper#beforeFind}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeFind}.\n * @see SimpleStore#event:beforeFind\n * @see SimpleStore#find\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#find}. See\n * {@link SimpleStore~afterFindListener} for how to listen for this event.\n *\n * @event SimpleStore#afterFind\n * @see SimpleStore~afterFindListener\n * @see SimpleStore#find\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterFind} event.\n *\n * @example\n * function onAfterFind (mapperName, id, opts, result) {\n * // do something\n * }\n * store.on('afterFind', onAfterFind);\n *\n * @callback SimpleStore~afterFindListener\n * @param {string} name The `name` argument received by {@link Mapper#afterFind}.\n * @param {string|number} id The `id` argument received by {@link Mapper#afterFind}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterFind}.\n * @param {object} result The `result` argument received by {@link Mapper#afterFind}.\n * @see SimpleStore#event:afterFind\n * @see SimpleStore#find\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#find}. Adds any found record to the store.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('book');\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // GET /book/1234\n * store.find('book', 1234).then((book) => {\n * // The book record is now in the in-memory store\n * console.log(store.get('book', 1234) === book); // true\n * });\n *\n * @fires SimpleStore#beforeFind\n * @fires SimpleStore#afterFind\n * @fires SimpleStore#add\n * @method SimpleStore#find\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(string|number)} id Passed to {@link Mapper#find}.\n * @param {object} [opts] Passed to {@link Mapper#find}.\n * @param {boolean} [opts.force] Bypass cacheFind\n * @param {boolean|Function} [opts.usePendingFind] See {@link SimpleStore#usePendingFind}\n * @returns {Promise} Resolves with the result, if any.\n * @since 3.0.0\n */\n find (name, id, opts) {\n opts || (opts = {})\n const mapper = this.getMapper(name)\n const pendingQuery = this._pendingQueries[name][id]\n const usePendingFind = opts.usePendingFind === undefined ? this.usePendingFind : opts.usePendingFind\n utils._(opts, mapper)\n\n if (pendingQuery && (utils.isFunction(usePendingFind) ? usePendingFind.call(this, name, id, opts) : usePendingFind)) {\n return pendingQuery\n }\n const item = this.cachedFind(name, id, opts)\n\n if (opts.force || !item) {\n const promise = this._pendingQueries[name][id] = Container.prototype.find.call(this, name, id, opts)\n return promise\n .then((result) => {\n delete this._pendingQueries[name][id]\n result = this._end(name, result, opts)\n this.cacheFind(name, result, id, opts)\n return result\n }, (err) => {\n delete this._pendingQueries[name][id]\n return utils.reject(err)\n })\n }\n\n return utils.resolve(item)\n },\n\n /**\n * Fired during {@link SimpleStore#findAll}. See\n * {@link SimpleStore~beforeFindAllListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeFindAll\n * @see SimpleStore~beforeFindAllListener\n * @see SimpleStore#findAll\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeFindAll} event.\n *\n * @example\n * function onBeforeFindAll (mapperName, query, opts) {\n * // do something\n * }\n * store.on('beforeFindAll', onBeforeFindAll);\n *\n * @callback SimpleStore~beforeFindAllListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeFindAll}.\n * @param {object} query The `query` argument received by {@link Mapper#beforeFindAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeFindAll}.\n * @see SimpleStore#event:beforeFindAll\n * @see SimpleStore#findAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#findAll}. See\n * {@link SimpleStore~afterFindAllListener} for how to listen for this event.\n *\n * @event SimpleStore#afterFindAll\n * @see SimpleStore~afterFindAllListener\n * @see SimpleStore#findAll\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterFindAll} event.\n *\n * @example\n * function onAfterFindAll (mapperName, query, opts, result) {\n * // do something\n * }\n * store.on('afterFindAll', onAfterFindAll);\n *\n * @callback SimpleStore~afterFindAllListener\n * @param {string} name The `name` argument received by {@link Mapper#afterFindAll}.\n * @param {object} query The `query` argument received by {@link Mapper#afterFindAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterFindAll}.\n * @param {object} result The `result` argument received by {@link Mapper#afterFindAll}.\n * @see SimpleStore#event:afterFindAll\n * @see SimpleStore#findAll\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#findAll}. Adds any found records to the store.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('movie');\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // GET /movie?rating=PG\n * store.find('movie', { rating: 'PG' }).then((movies) => {\n * // The movie records are now in the in-memory store\n * console.log(store.filter('movie'));\n * });\n *\n * @fires SimpleStore#beforeFindAll\n * @fires SimpleStore#afterFindAll\n * @fires SimpleStore#add\n * @method SimpleStore#findAll\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} [query] Passed to {@link Mapper.findAll}.\n * @param {object} [opts] Passed to {@link Mapper.findAll}.\n * @param {boolean} [opts.force] Bypass cacheFindAll\n * @param {boolean|Function} [opts.usePendingFindAll] See {@link SimpleStore#usePendingFindAll}\n * @returns {Promise} Resolves with the result, if any.\n * @since 3.0.0\n */\n findAll (name, query, opts) {\n opts || (opts = {})\n const mapper = this.getMapper(name)\n const hash = this.hashQuery(name, query, opts)\n const pendingQuery = this._pendingQueries[name][hash]\n const usePendingFindAll = opts.usePendingFindAll === undefined ? this.usePendingFindAll : opts.usePendingFindAll\n utils._(opts, mapper)\n\n if (pendingQuery && (utils.isFunction(usePendingFindAll) ? usePendingFindAll.call(this, name, query, opts) : usePendingFindAll)) {\n return pendingQuery\n }\n\n const items = this.cachedFindAll(name, hash, opts)\n\n if (opts.force || !items) {\n const promise = this._pendingQueries[name][hash] = Container.prototype.findAll.call(this, name, query, opts)\n return promise\n .then((result) => {\n delete this._pendingQueries[name][hash]\n result = this._end(name, result, opts)\n this.cacheFindAll(name, result, hash, opts)\n return result\n }, (err) => {\n delete this._pendingQueries[name][hash]\n return utils.reject(err)\n })\n }\n\n return utils.resolve(items)\n },\n\n /**\n * Return the {@link Collection} with the given name, if for some\n * reason you need a direct reference to the collection.\n *\n * @method SimpleStore#getCollection\n * @param {string} name Name of the {@link Collection} to retrieve.\n * @returns {Collection}\n * @since 3.0.0\n * @throws {Error} Thrown if the specified {@link Collection} does not\n * exist.\n */\n getCollection (name) {\n const collection = this._collections[name]\n if (!collection) {\n throw utils.err(`${DOMAIN}#getCollection`, name)(404, 'collection')\n }\n return collection\n },\n\n /**\n * Hashing function used to cache {@link SimpleStore#find} and\n * {@link SimpleStore#findAll} requests. This method simply JSONifies the\n * `query` argument passed to {@link SimpleStore#find} or\n * {@link SimpleStore#findAll}.\n *\n * Override this method for custom hashing behavior.\n * @method SimpleStore#hashQuery\n * @param {string} name The `name` argument passed to {@link SimpleStore#find}\n * or {@link SimpleStore#findAll}.\n * @param {object} query The `query` argument passed to {@link SimpleStore#find}\n * or {@link SimpleStore#findAll}.\n * @returns {string} The JSONified `query`.\n * @since 3.0.0\n */\n hashQuery (name, query, opts) {\n return utils.toJson(query || {})\n },\n\n inject (name, records, opts) {\n console.warn('DEPRECATED: \"inject\" is deprecated, use \"add\" instead')\n return this.add(name, records, opts)\n },\n\n /**\n * Wrapper for {@link Collection#remove}. Removes the specified\n * {@link Record} from the store.\n *\n * @example SimpleStore#remove\n * const JSData = require('js-data');\n * const { SimpleStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new SimpleStore();\n * store.defineMapper('book');\n * console.log(store.getAll('book').length);\n * store.add('book', { id: 1234 });\n * console.log(store.getAll('book').length);\n * store.remove('book', 1234);\n * console.log(store.getAll('book').length);\n *\n * @fires SimpleStore#remove\n * @method SimpleStore#remove\n * @param {string} name The name of the {@link Collection} to target.\n * @param {string|number} id The primary key of the {@link Record} to remove.\n * @param {object} [opts] Configuration options.\n * @param {string[]} [opts.with] Relations of the {@link Record} to also\n * remove from the store.\n * @returns {Record} The removed {@link Record}, if any.\n * @see Collection#add\n * @see Collection#add\n * @since 3.0.0\n */\n remove (name, id, opts) {\n const record = this.getCollection(name).remove(id, opts)\n if (record) {\n this.removeRelated(name, [record], opts)\n }\n return record\n },\n\n /**\n * Wrapper for {@link Collection#removeAll}. Removes the selected\n * {@link Record}s from the store.\n *\n * @example SimpleStore#removeAll\n * const JSData = require('js-data');\n * const { SimpleStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * const store = new SimpleStore();\n * store.defineMapper('movie');\n * console.log(store.getAll('movie').length);\n * store.add('movie', [{ id: 3, rating: 'R' }, { id: 4, rating: 'PG-13' });\n * console.log(store.getAll('movie').length);\n * store.removeAll('movie', { rating: 'R' });\n * console.log(store.getAll('movie').length);\n *\n * @fires SimpleStore#remove\n * @method SimpleStore#removeAll\n * @param {string} name The name of the {@link Collection} to target.\n * @param {object} [query={}] Selection query. See {@link query}.\n * @param {object} [query.where] See {@link query.where}.\n * @param {number} [query.offset] See {@link query.offset}.\n * @param {number} [query.limit] See {@link query.limit}.\n * @param {string|Array[]} [query.orderBy] See {@link query.orderBy}.\n * @param {object} [opts] Configuration options.\n * @param {string[]} [opts.with] Relations of the {@link Record} to also\n * remove from the store.\n * @returns {Record} The removed {@link Record}s, if any.\n * @see Collection#add\n * @see Collection#add\n * @since 3.0.0\n */\n removeAll (name, query, opts) {\n if (!query || !Object.keys(query).length) {\n this._completedQueries[name] = {}\n } else {\n this._completedQueries[name][this.hashQuery(name, query, opts)] = undefined\n }\n const records = this.getCollection(name).removeAll(query, opts)\n if (records.length) {\n this.removeRelated(name, records, opts)\n }\n return records\n },\n\n /**\n * Remove from the store {@link Record}s that are related to the provided\n * {@link Record}(s).\n *\n * @fires SimpleStore#remove\n * @method SimpleStore#removeRelated\n * @param {string} name The name of the {@link Collection} to target.\n * @param {Record|Record[]} records {@link Record}s whose relations are to be\n * removed.\n * @param {object} [opts] Configuration options.\n * @param {string[]} [opts.with] Relations of the {@link Record}(s) to remove\n * from the store.\n * @since 3.0.0\n */\n removeRelated (name, records, opts) {\n if (!utils.isArray(records)) {\n records = [records]\n }\n utils.forEachRelation(this.getMapper(name), opts, (def, optsCopy) => {\n records.forEach((record) => {\n let relatedData\n let query\n if (def.foreignKey && (def.type === hasOneType || def.type === hasManyType)) {\n query = { [def.foreignKey]: def.getForeignKey(record) }\n } else if (def.type === hasManyType && def.localKeys) {\n query = {\n where: {\n [def.getRelation().idAttribute]: {\n 'in': utils.get(record, def.localKeys)\n }\n }\n }\n } else if (def.type === hasManyType && def.foreignKeys) {\n query = {\n where: {\n [def.foreignKeys]: {\n 'contains': def.getForeignKey(record)\n }\n }\n }\n } else if (def.type === belongsToType) {\n relatedData = this.remove(def.relation, def.getForeignKey(record), optsCopy)\n }\n if (query) {\n relatedData = this.removeAll(def.relation, query, optsCopy)\n }\n if (relatedData) {\n if (utils.isArray(relatedData) && !relatedData.length) {\n return\n }\n if (def.type === hasOneType) {\n relatedData = relatedData[0]\n }\n def.setLocalField(record, relatedData)\n }\n })\n })\n },\n\n /**\n * Fired during {@link SimpleStore#update}. See\n * {@link SimpleStore~beforeUpdateListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeUpdate\n * @see SimpleStore~beforeUpdateListener\n * @see SimpleStore#update\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeUpdate} event.\n *\n * @example\n * function onBeforeUpdate (mapperName, id, props, opts) {\n * // do something\n * }\n * store.on('beforeUpdate', onBeforeUpdate);\n *\n * @callback SimpleStore~beforeUpdateListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeUpdate}.\n * @param {string|number} id The `id` argument received by {@link Mapper#beforeUpdate}.\n * @param {object} props The `props` argument received by {@link Mapper#beforeUpdate}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdate}.\n * @see SimpleStore#event:beforeUpdate\n * @see SimpleStore#update\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#update}. See\n * {@link SimpleStore~afterUpdateListener} for how to listen for this event.\n *\n * @event SimpleStore#afterUpdate\n * @see SimpleStore~afterUpdateListener\n * @see SimpleStore#update\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterUpdate} event.\n *\n * @example\n * function onAfterUpdate (mapperName, id, props, opts, result) {\n * // do something\n * }\n * store.on('afterUpdate', onAfterUpdate);\n *\n * @callback SimpleStore~afterUpdateListener\n * @param {string} name The `name` argument received by {@link Mapper#afterUpdate}.\n * @param {string|number} id The `id` argument received by {@link Mapper#afterUpdate}.\n * @param {object} props The `props` argument received by {@link Mapper#afterUpdate}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdate}.\n * @param {object} result The `result` argument received by {@link Mapper#afterUpdate}.\n * @see SimpleStore#event:afterUpdate\n * @see SimpleStore#update\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#update}. Adds the updated {@link Record} to the\n * store.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('post');\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // PUT /post/1234 {\"status\":\"published\"}\n * store.update('post', 1, { status: 'published' }).then((post) => {\n * // The post record has also been updated in the in-memory store\n * console.log(store.get('post', 1234));\n * });\n *\n * @fires SimpleStore#beforeUpdate\n * @fires SimpleStore#afterUpdate\n * @fires SimpleStore#add\n * @method SimpleStore#update\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(string|number)} id Passed to {@link Mapper#update}.\n * @param {object} record Passed to {@link Mapper#update}.\n * @param {object} [opts] Passed to {@link Mapper#update}. See\n * {@link Mapper#update} for more configuration options.\n * @returns {Promise} Resolves with the result of the update.\n * @since 3.0.0\n */\n update (name, id, record, opts) {\n opts || (opts = {})\n return Container.prototype.update.call(this, name, id, record, opts)\n .then((result) => this._end(name, result, opts))\n },\n\n /**\n * Fired during {@link SimpleStore#updateAll}. See\n * {@link SimpleStore~beforeUpdateAllListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeUpdateAll\n * @see SimpleStore~beforeUpdateAllListener\n * @see SimpleStore#updateAll\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeUpdateAll} event.\n *\n * @example\n * function onBeforeUpdateAll (mapperName, props, query, opts) {\n * // do something\n * }\n * store.on('beforeUpdateAll', onBeforeUpdateAll);\n *\n * @callback SimpleStore~beforeUpdateAllListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeUpdateAll}.\n * @param {object} props The `props` argument received by {@link Mapper#beforeUpdateAll}.\n * @param {object} query The `query` argument received by {@link Mapper#beforeUpdateAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateAll}.\n * @see SimpleStore#event:beforeUpdateAll\n * @see SimpleStore#updateAll\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#updateAll}. See\n * {@link SimpleStore~afterUpdateAllListener} for how to listen for this event.\n *\n * @event SimpleStore#afterUpdateAll\n * @see SimpleStore~afterUpdateAllListener\n * @see SimpleStore#updateAll\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterUpdateAll} event.\n *\n * @example\n * function onAfterUpdateAll (mapperName, props, query, opts, result) {\n * // do something\n * }\n * store.on('afterUpdateAll', onAfterUpdateAll);\n *\n * @callback SimpleStore~afterUpdateAllListener\n * @param {string} name The `name` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} props The `props` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} query The `query` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateAll}.\n * @param {object} result The `result` argument received by {@link Mapper#afterUpdateAll}.\n * @see SimpleStore#event:afterUpdateAll\n * @see SimpleStore#updateAll\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#updateAll}. Adds the updated {@link Record}s to\n * the store.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('post');\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // PUT /post?author_id=1234 {\"status\":\"published\"}\n * store.updateAll('post', { author_id: 1234 }, { status: 'published' }).then((posts) => {\n * // The post records have also been updated in the in-memory store\n * console.log(store.filter('posts', { author_id: 1234 }));\n * });\n *\n * @fires SimpleStore#beforeUpdateAll\n * @fires SimpleStore#afterUpdateAll\n * @fires SimpleStore#add\n * @method SimpleStore#updateAll\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {object} props Passed to {@link Mapper#updateAll}.\n * @param {object} [query] Passed to {@link Mapper#updateAll}.\n * @param {object} [opts] Passed to {@link Mapper#updateAll}. See\n * {@link Mapper#updateAll} for more configuration options.\n * @returns {Promise} Resolves with the result of the update.\n * @since 3.0.0\n */\n updateAll (name, props, query, opts) {\n opts || (opts = {})\n return Container.prototype.updateAll.call(this, name, props, query, opts)\n .then((result) => this._end(name, result, opts))\n },\n\n /**\n * Fired during {@link SimpleStore#updateMany}. See\n * {@link SimpleStore~beforeUpdateManyListener} for how to listen for this event.\n *\n * @event SimpleStore#beforeUpdateMany\n * @see SimpleStore~beforeUpdateManyListener\n * @see SimpleStore#updateMany\n */\n /**\n * Callback signature for the {@link SimpleStore#event:beforeUpdateMany} event.\n *\n * @example\n * function onBeforeUpdateMany (mapperName, records, opts) {\n * // do something\n * }\n * store.on('beforeUpdateMany', onBeforeUpdateMany);\n *\n * @callback SimpleStore~beforeUpdateManyListener\n * @param {string} name The `name` argument received by {@link Mapper#beforeUpdateMany}.\n * @param {object} records The `records` argument received by {@link Mapper#beforeUpdateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#beforeUpdateMany}.\n * @see SimpleStore#event:beforeUpdateMany\n * @see SimpleStore#updateMany\n * @since 3.0.0\n */\n /**\n * Fired during {@link SimpleStore#updateMany}. See\n * {@link SimpleStore~afterUpdateManyListener} for how to listen for this event.\n *\n * @event SimpleStore#afterUpdateMany\n * @see SimpleStore~afterUpdateManyListener\n * @see SimpleStore#updateMany\n */\n /**\n * Callback signature for the {@link SimpleStore#event:afterUpdateMany} event.\n *\n * @example\n * function onAfterUpdateMany (mapperName, records, opts, result) {\n * // do something\n * }\n * store.on('afterUpdateMany', onAfterUpdateMany);\n *\n * @callback SimpleStore~afterUpdateManyListener\n * @param {string} name The `name` argument received by {@link Mapper#afterUpdateMany}.\n * @param {object} records The `records` argument received by {@link Mapper#afterUpdateMany}.\n * @param {object} opts The `opts` argument received by {@link Mapper#afterUpdateMany}.\n * @param {object} result The `result` argument received by {@link Mapper#afterUpdateMany}.\n * @see SimpleStore#event:afterUpdateMany\n * @see SimpleStore#updateMany\n * @since 3.0.0\n */\n /**\n * Wrapper for {@link Mapper#updateMany}. Adds the updated {@link Record}s to\n * the store.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * import { HttpAdapter } from 'js-data-http';\n *\n * const store = new SimpleStore();\n * store.registerAdapter('http', new HttpAdapter(), { default: true });\n *\n * store.defineMapper('post');\n *\n * // Since this example uses the http adapter, we'll get something like:\n * //\n * // PUT /post [{\"id\":3,status\":\"published\"},{\"id\":4,status\":\"published\"}]\n * store.updateMany('post', [\n * { id: 3, status: 'published' },\n * { id: 4, status: 'published' }\n * ]).then((posts) => {\n * // The post records have also been updated in the in-memory store\n * console.log(store.getAll('post', 3, 4));\n * });\n *\n * @fires SimpleStore#beforeUpdateMany\n * @fires SimpleStore#afterUpdateMany\n * @fires SimpleStore#add\n * @method SimpleStore#updateMany\n * @param {string} name Name of the {@link Mapper} to target.\n * @param {(Object[]|Record[])} records Passed to {@link Mapper#updateMany}.\n * @param {object} [opts] Passed to {@link Mapper#updateMany}. See\n * {@link Mapper#updateMany} for more configuration options.\n * @returns {Promise} Resolves with the result of the update.\n * @since 3.0.0\n */\n updateMany (name, records, opts) {\n opts || (opts = {})\n return Container.prototype.updateMany.call(this, name, records, opts)\n .then((result) => this._end(name, result, opts))\n }\n}\n\nproxiedCollectionMethods.forEach(function (method) {\n props[method] = function (name, ...args) {\n return this.getCollection(name)[method](...args)\n }\n})\n\nexport default Container.extend(props)\n\n/**\n * Fired when a record changes. Only works for records that have tracked fields.\n * See {@link SimpleStore~changeListener} on how to listen for this event.\n *\n * @event SimpleStore#change\n * @see SimpleStore~changeListener\n */\n\n/**\n * Callback signature for the {@link SimpleStore#event:change} event.\n *\n * @example\n * function onChange (mapperName, record, changes) {\n * // do something\n * }\n * store.on('change', onChange);\n *\n * @callback SimpleStore~changeListener\n * @param {string} name The name of the associated {@link Mapper}.\n * @param {Record} record The Record that changed.\n * @param {object} changes The changes.\n * @see SimpleStore#event:change\n * @since 3.0.0\n */\n\n/**\n * Fired when one or more records are added to the in-memory store. See\n * {@link SimpleStore~addListener} on how to listen for this event.\n *\n * @event SimpleStore#add\n * @see SimpleStore~addListener\n * @see SimpleStore#event:add\n * @see SimpleStore#add\n * @see SimpleStore#create\n * @see SimpleStore#createMany\n * @see SimpleStore#find\n * @see SimpleStore#findAll\n * @see SimpleStore#update\n * @see SimpleStore#updateAll\n * @see SimpleStore#updateMany\n */\n\n/**\n * Callback signature for the {@link SimpleStore#event:add} event.\n *\n * @example\n * function onAdd (mapperName, recordOrRecords) {\n * // do something\n * }\n * store.on('add', onAdd);\n *\n * @callback SimpleStore~addListener\n * @param {string} name The name of the associated {@link Mapper}.\n * @param {Record|Record[]} The Record or Records that were added.\n * @see SimpleStore#event:add\n * @see SimpleStore#add\n * @see SimpleStore#create\n * @see SimpleStore#createMany\n * @see SimpleStore#find\n * @see SimpleStore#findAll\n * @see SimpleStore#update\n * @see SimpleStore#updateAll\n * @see SimpleStore#updateMany\n * @since 3.0.0\n */\n\n/**\n * Fired when one or more records are removed from the in-memory store. See\n * {@link SimpleStore~removeListener} for how to listen for this event.\n *\n * @event SimpleStore#remove\n * @see SimpleStore~removeListener\n * @see SimpleStore#event:remove\n * @see SimpleStore#clear\n * @see SimpleStore#destroy\n * @see SimpleStore#destroyAll\n * @see SimpleStore#remove\n * @see SimpleStore#removeAll\n */\n\n/**\n * Callback signature for the {@link SimpleStore#event:remove} event.\n *\n * @example\n * function onRemove (mapperName, recordsOrRecords) {\n * // do something\n * }\n * store.on('remove', onRemove);\n *\n * @callback SimpleStore~removeListener\n * @param {string} name The name of the associated {@link Mapper}.\n * @param {Record|Record[]} Record or Records that were removed.\n * @see SimpleStore#event:remove\n * @see SimpleStore#clear\n * @see SimpleStore#destroy\n * @see SimpleStore#destroyAll\n * @see SimpleStore#remove\n * @see SimpleStore#removeAll\n * @since 3.0.0\n */\n\n/**\n * Create a subclass of this SimpleStore:\n * @example SimpleStore.extend\n * const JSData = require('js-data');\n * const { SimpleStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomSimpleStoreClass extends SimpleStore {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customSimpleStore = new CustomSimpleStoreClass();\n * console.log(customSimpleStore.foo());\n * console.log(CustomSimpleStoreClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherSimpleStoreClass = SimpleStore.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * })\n * const otherSimpleStore = new OtherSimpleStoreClass();\n * console.log(otherSimpleStore.foo());\n * console.log(OtherSimpleStoreClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherSimpleStoreClass () {\n * SimpleStore.call(this)\n * this.created_at = new Date().getTime()\n * }\n * SimpleStore.extend({\n * constructor: AnotherSimpleStoreClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * })\n * const anotherSimpleStore = new AnotherSimpleStoreClass();\n * console.log(anotherSimpleStore.created_at);\n * console.log(anotherSimpleStore.foo());\n * console.log(AnotherSimpleStoreClass.beep());\n *\n * @method SimpleStore.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this SimpleStore class.\n * @since 3.0.0\n */\n","import utils from './utils'\nimport './decorators'\nimport Collection from './Collection'\n\nconst DOMAIN = 'LinkedCollection'\n\n/**\n * Extends {@link Collection}. Used by a {@link DataStore} to implement an\n * Identity Map.\n *\n * ```javascript\n * import {LinkedCollection} from 'js-data'\n * ```\n *\n * @class LinkedCollection\n * @extends Collection\n * @param {array} [records] Initial set of records to insert into the\n * collection. See {@link Collection}.\n * @param {object} [opts] Configuration options. See {@link Collection}.\n * @returns {Mapper}\n */\nfunction LinkedCollection (records, opts) {\n utils.classCallCheck(this, LinkedCollection)\n // Make sure this collection has somewhere to store \"added\" timestamps\n Object.defineProperties(this, {\n _added: {\n value: {}\n },\n datastore: {\n writable: true,\n value: undefined\n }\n })\n\n Collection.call(this, records, opts)\n\n // Make sure this collection has a reference to a datastore\n if (!this.datastore) {\n throw utils.err(`new ${DOMAIN}`, 'opts.datastore')(400, 'DataStore', this.datastore)\n }\n}\n\nexport default Collection.extend({\n constructor: LinkedCollection,\n\n _addMeta (record, timestamp) {\n // Track when this record was added\n this._added[this.recordId(record)] = timestamp\n\n if (utils.isFunction(record._set)) {\n record._set('$', timestamp)\n }\n },\n\n _clearMeta (record) {\n delete this._added[this.recordId(record)]\n if (utils.isFunction(record._set)) {\n record._set('$') // unset\n }\n },\n\n _onRecordEvent (...args) {\n Collection.prototype._onRecordEvent.apply(this, args)\n const event = args[0]\n // This is a very brute force method\n // Lots of room for optimization\n if (utils.isString(event) && event.indexOf('change') === 0) {\n this.updateIndexes(args[1])\n }\n },\n\n add (records, opts) {\n const mapper = this.mapper\n const timestamp = new Date().getTime()\n const singular = utils.isObject(records) && !utils.isArray(records)\n\n if (singular) {\n records = [records]\n }\n records = Collection.prototype.add.call(this, records, opts)\n\n if (mapper.relationList.length && records.length) {\n // Check the currently visited record for relations that need to be\n // inserted into their respective collections.\n mapper.relationList.forEach(function (def) {\n def.addLinkedRecords(records)\n })\n }\n\n records.forEach((record) => this._addMeta(record, timestamp))\n\n return singular ? records[0] : records\n },\n\n remove (idOrRecord, opts) {\n const mapper = this.mapper\n const record = Collection.prototype.remove.call(this, idOrRecord, opts)\n if (record) {\n this._clearMeta(record)\n }\n\n if (mapper.relationList.length && record) {\n mapper.relationList.forEach(function (def) {\n def.removeLinkedRecords(mapper, [record])\n })\n }\n\n return record\n },\n\n removeAll (query, opts) {\n const mapper = this.mapper\n const records = Collection.prototype.removeAll.call(this, query, opts)\n records.forEach(this._clearMeta, this)\n\n if (mapper.relationList.length && records.length) {\n mapper.relationList.forEach(function (def) {\n def.removeLinkedRecords(mapper, records)\n })\n }\n\n return records\n }\n})\n\n/**\n * Create a subclass of this LinkedCollection:\n *\n * @example LinkedCollection.extend\n * const JSData = require('js-data');\n * const { LinkedCollection } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomLinkedCollectionClass extends LinkedCollection {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customLinkedCollection = new CustomLinkedCollectionClass();\n * console.log(customLinkedCollection.foo());\n * console.log(CustomLinkedCollectionClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherLinkedCollectionClass = LinkedCollection.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherLinkedCollection = new OtherLinkedCollectionClass();\n * console.log(otherLinkedCollection.foo());\n * console.log(OtherLinkedCollectionClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherLinkedCollectionClass () {\n * LinkedCollection.call(this);\n * this.created_at = new Date().getTime();\n * }\n * LinkedCollection.extend({\n * constructor: AnotherLinkedCollectionClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const anotherLinkedCollection = new AnotherLinkedCollectionClass();\n * console.log(anotherLinkedCollection.created_at);\n * console.log(anotherLinkedCollection.foo());\n * console.log(AnotherLinkedCollectionClass.beep());\n *\n * @method LinkedCollection.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this LinkedCollection class.\n * @since 3.0.0\n */\n","import utils, { safeSetLink, safeSetProp } from './utils'\n\nimport {\n belongsToType,\n hasManyType,\n hasOneType\n} from './decorators'\nimport SimpleStore from './SimpleStore'\nimport LinkedCollection from './LinkedCollection'\n\nconst DATASTORE_DEFAULTS = {\n /**\n * Whether in-memory relations should be unlinked from records after they are\n * destroyed.\n *\n * @default true\n * @name DataStore#unlinkOnDestroy\n * @since 3.0.0\n * @type {boolean}\n */\n unlinkOnDestroy: true\n}\n\n/**\n * The `DataStore` class is an extension of {@link SimpleStore}. Not only does\n * `DataStore` manage mappers and store data in collections, it uses the\n * {@link LinkedCollection} class to link related records together in memory.\n *\n * ```javascript\n * import { DataStore } from 'js-data';\n * ```\n *\n * @example\n * import { DataStore } from 'js-data';\n * import HttpAdapter from 'js-data-http';\n * const store = new DataStore();\n *\n * // DataStore#defineMapper returns a direct reference to the newly created\n * // Mapper.\n * const UserMapper = store.defineMapper('user');\n *\n * // DataStore#as returns the store scoped to a particular Mapper.\n * const UserStore = store.as('user');\n *\n * // Call \"find\" on \"UserMapper\" (Stateless ORM)\n * UserMapper.find(1).then((user) => {\n * // retrieved a \"user\" record via the http adapter, but that's it\n *\n * // Call \"find\" on \"store\" targeting \"user\" (Stateful DataStore)\n * return store.find('user', 1); // same as \"UserStore.find(1)\"\n * }).then((user) => {\n * // not only was a \"user\" record retrieved, but it was added to the\n * // store's \"user\" collection\n * const cachedUser = store.getCollection('user').get(1);\n * console.log(user === cachedUser); // true\n * });\n *\n * @class DataStore\n * @extends SimpleStore\n * @param {object} [opts] Configuration options. See {@link SimpleStore}.\n * @param {boolean} [opts.collectionClass={@link LinkedCollection}] See {@link DataStore#collectionClass}.\n * @param {boolean} [opts.debug=false] See {@link Component#debug}.\n * @param {boolean} [opts.unlinkOnDestroy=true] See {@link DataStore#unlinkOnDestroy}.\n * @param {boolean|Function} [opts.usePendingFind=true] See {@link DataStore#usePendingFind}.\n * @param {boolean|Function} [opts.usePendingFindAll=true] See {@link DataStore#usePendingFindAll}.\n * @returns {DataStore}\n * @see SimpleStore\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#datastore\",\"Components of JSData: DataStore\"]\n * @tutorial [\"http://www.js-data.io/v3.0/docs/working-with-the-datastore\",\"Working with the DataStore\"]\n * @tutorial [\"http://www.js-data.io/v3.0/docs/jsdata-and-the-browser\",\"Notes on using JSData in the Browser\"]\n */\nfunction DataStore (opts) {\n utils.classCallCheck(this, DataStore)\n\n opts || (opts = {})\n // Fill in any missing options with the defaults\n utils.fillIn(opts, DATASTORE_DEFAULTS)\n opts.collectionClass || (opts.collectionClass = LinkedCollection)\n SimpleStore.call(this, opts)\n}\n\nconst props = {\n constructor: DataStore,\n\n defineMapper (name, opts) {\n // Complexity of this method is beyond simply using => functions to bind context\n const self = this\n const mapper = SimpleStore.prototype.defineMapper.call(self, name, opts)\n const idAttribute = mapper.idAttribute\n const collection = this.getCollection(name)\n\n mapper.relationList.forEach(function (def) {\n const relation = def.relation\n const localField = def.localField\n const path = `links.${localField}`\n const foreignKey = def.foreignKey\n const type = def.type\n const updateOpts = { index: foreignKey }\n let descriptor\n\n const getter = function () { return this._get(path) }\n\n if (type === belongsToType) {\n if (!collection.indexes[foreignKey]) {\n collection.createIndex(foreignKey)\n }\n\n descriptor = {\n get: getter,\n // e.g. profile.user = someUser\n // or comment.post = somePost\n set (record) {\n // e.g. const otherUser = profile.user\n const currentParent = this._get(path)\n // e.g. profile.user === someUser\n if (record === currentParent) {\n return currentParent\n }\n const id = utils.get(this, idAttribute)\n const inverseDef = def.getInverse(mapper)\n\n // e.g. profile.user !== someUser\n // or comment.post !== somePost\n if (currentParent && inverseDef) {\n this.removeInverseRelation(currentParent, id, inverseDef, idAttribute)\n }\n if (record) {\n // e.g. profile.user = someUser\n const relatedIdAttribute = def.getRelation().idAttribute\n const relatedId = utils.get(record, relatedIdAttribute)\n\n // Prefer store record\n if (relatedId !== undefined && this._get('$')) {\n record = self.get(relation, relatedId) || record\n }\n\n // Set locals\n // e.g. profile.user = someUser\n // or comment.post = somePost\n safeSetLink(this, localField, record)\n safeSetProp(this, foreignKey, relatedId)\n collection.updateIndex(this, updateOpts)\n\n if (inverseDef) {\n this.setupInverseRelation(record, id, inverseDef, idAttribute)\n }\n } else {\n // Unset in-memory link only\n // e.g. profile.user = undefined\n // or comment.post = undefined\n safeSetLink(this, localField, undefined)\n }\n return record\n }\n }\n\n let foreignKeyDescriptor = Object.getOwnPropertyDescriptor(mapper.recordClass.prototype, foreignKey)\n if (!foreignKeyDescriptor) {\n foreignKeyDescriptor = {\n enumerable: true\n }\n }\n const originalGet = foreignKeyDescriptor.get\n foreignKeyDescriptor.get = function () {\n if (originalGet) {\n return originalGet.call(this)\n }\n return this._get(`props.${foreignKey}`)\n }\n const originalSet = foreignKeyDescriptor.set\n foreignKeyDescriptor.set = function (value) {\n if (originalSet) {\n originalSet.call(this, value)\n }\n const currentParent = utils.get(this, localField)\n const id = utils.get(this, idAttribute)\n const inverseDef = def.getInverse(mapper)\n const currentParentId = currentParent ? utils.get(currentParent, def.getRelation().idAttribute) : undefined\n\n if (currentParent && currentParentId !== undefined && currentParentId !== value) {\n if (inverseDef.type === hasOneType) {\n safeSetLink(currentParent, inverseDef.localField, undefined)\n } else if (inverseDef.type === hasManyType) {\n const children = utils.get(currentParent, inverseDef.localField)\n if (id === undefined) {\n utils.remove(children, (child) => child === this)\n } else {\n utils.remove(children, (child) => child === this || id === utils.get(child, idAttribute))\n }\n }\n }\n\n safeSetProp(this, foreignKey, value)\n collection.updateIndex(this, updateOpts)\n\n if ((value === undefined || value === null)) {\n if (currentParentId !== undefined) {\n // Unset locals\n utils.set(this, localField, undefined)\n }\n } else if (this._get('$')) {\n const storeRecord = self.get(relation, value)\n if (storeRecord) {\n utils.set(this, localField, storeRecord)\n }\n }\n }\n Object.defineProperty(mapper.recordClass.prototype, foreignKey, foreignKeyDescriptor)\n } else if (type === hasManyType) {\n const localKeys = def.localKeys\n const foreignKeys = def.foreignKeys\n\n // TODO: Handle case when belongsTo relation isn't ever defined\n if (self._collections[relation] && foreignKey && !self.getCollection(relation).indexes[foreignKey]) {\n self.getCollection(relation).createIndex(foreignKey)\n }\n\n descriptor = {\n get () {\n let current = getter.call(this)\n if (!current) {\n this._set(path, [])\n }\n return getter.call(this)\n },\n // e.g. post.comments = someComments\n // or user.groups = someGroups\n // or group.users = someUsers\n set (records) {\n if (records && !utils.isArray(records)) {\n records = [records]\n }\n const id = utils.get(this, idAttribute)\n const relatedIdAttribute = def.getRelation().idAttribute\n const inverseDef = def.getInverse(mapper)\n const inverseLocalField = inverseDef.localField\n const current = this._get(path) || []\n const toLink = []\n const toLinkIds = {}\n\n if (records) {\n records.forEach((record) => {\n // e.g. comment.id\n const relatedId = utils.get(record, relatedIdAttribute)\n const currentParent = utils.get(record, inverseLocalField)\n if (currentParent && currentParent !== this) {\n const currentChildrenOfParent = utils.get(currentParent, localField)\n // e.g. somePost.comments.remove(comment)\n if (relatedId === undefined) {\n utils.remove(currentChildrenOfParent, (child) => child === record)\n } else {\n utils.remove(currentChildrenOfParent, (child) => child === record || relatedId === utils.get(child, relatedIdAttribute))\n }\n }\n if (relatedId !== undefined) {\n if (this._get('$')) {\n // Prefer store record\n record = self.get(relation, relatedId) || record\n }\n // e.g. toLinkIds[comment.id] = comment\n toLinkIds[relatedId] = record\n }\n toLink.push(record)\n })\n }\n\n // e.g. post.comments = someComments\n if (foreignKey) {\n current.forEach((record) => {\n // e.g. comment.id\n const relatedId = utils.get(record, relatedIdAttribute)\n if ((relatedId === undefined && toLink.indexOf(record) === -1) || (relatedId !== undefined && !(relatedId in toLinkIds))) {\n // Update (unset) inverse relation\n if (records) {\n // e.g. comment.post_id = undefined\n safeSetProp(record, foreignKey, undefined)\n // e.g. CommentCollection.updateIndex(comment, { index: 'post_id' })\n self.getCollection(relation).updateIndex(record, updateOpts)\n }\n // e.g. comment.post = undefined\n safeSetLink(record, inverseLocalField, undefined)\n }\n })\n toLink.forEach((record) => {\n // Update (set) inverse relation\n // e.g. comment.post_id = post.id\n safeSetProp(record, foreignKey, id)\n // e.g. CommentCollection.updateIndex(comment, { index: 'post_id' })\n self.getCollection(relation).updateIndex(record, updateOpts)\n // e.g. comment.post = post\n safeSetLink(record, inverseLocalField, this)\n })\n } else if (localKeys) {\n // Update locals\n // e.g. group.users = someUsers\n // Update (set) inverse relation\n const ids = toLink.map((child) => utils.get(child, relatedIdAttribute)).filter((id) => id !== undefined)\n // e.g. group.user_ids = [1,2,3,...]\n utils.set(this, localKeys, ids)\n // Update (unset) inverse relation\n if (inverseDef.foreignKeys) {\n current.forEach((child) => {\n const relatedId = utils.get(child, relatedIdAttribute)\n if ((relatedId === undefined && toLink.indexOf(child) === -1) || (relatedId !== undefined && !(relatedId in toLinkIds))) {\n // Update inverse relation\n // safeSetLink(child, inverseLocalField, undefined)\n const parents = utils.get(child, inverseLocalField) || []\n // e.g. someUser.groups.remove(group)\n if (id === undefined) {\n utils.remove(parents, (parent) => parent === this)\n } else {\n utils.remove(parents, (parent) => parent === this || id === utils.get(parent, idAttribute))\n }\n }\n })\n toLink.forEach((child) => {\n // Update (set) inverse relation\n const parents = utils.get(child, inverseLocalField)\n // e.g. someUser.groups.push(group)\n if (id === undefined) {\n utils.noDupeAdd(parents, this, (parent) => parent === this)\n } else {\n utils.noDupeAdd(parents, this, (parent) => parent === this || id === utils.get(parent, idAttribute))\n }\n })\n }\n } else if (foreignKeys) {\n // e.g. user.groups = someGroups\n // Update (unset) inverse relation\n current.forEach((parent) => {\n const ids = utils.get(parent, foreignKeys) || []\n // e.g. someGroup.user_ids.remove(user.id)\n utils.remove(ids, (_key) => id === _key)\n const children = utils.get(parent, inverseLocalField)\n // e.g. someGroup.users.remove(user)\n if (id === undefined) {\n utils.remove(children, (child) => child === this)\n } else {\n utils.remove(children, (child) => child === this || id === utils.get(child, idAttribute))\n }\n })\n // Update (set) inverse relation\n toLink.forEach((parent) => {\n const ids = utils.get(parent, foreignKeys) || []\n utils.noDupeAdd(ids, id, (_key) => id === _key)\n const children = utils.get(parent, inverseLocalField)\n if (id === undefined) {\n utils.noDupeAdd(children, this, (child) => child === this)\n } else {\n utils.noDupeAdd(children, this, (child) => child === this || id === utils.get(child, idAttribute))\n }\n })\n }\n\n this._set(path, toLink)\n return toLink\n }\n }\n } else if (type === hasOneType) {\n // TODO: Handle case when belongsTo relation isn't ever defined\n if (self._collections[relation] && foreignKey && !self.getCollection(relation).indexes[foreignKey]) {\n self.getCollection(relation).createIndex(foreignKey)\n }\n descriptor = {\n get: getter,\n // e.g. user.profile = someProfile\n set (record) {\n const current = this._get(path)\n if (record === current) {\n return current\n }\n const inverseLocalField = def.getInverse(mapper).localField\n // Update (unset) inverse relation\n if (current) {\n safeSetProp(current, foreignKey, undefined)\n self.getCollection(relation).updateIndex(current, updateOpts)\n safeSetLink(current, inverseLocalField, undefined)\n }\n if (record) {\n const relatedId = utils.get(record, def.getRelation().idAttribute)\n // Prefer store record\n if (relatedId !== undefined) {\n record = self.get(relation, relatedId) || record\n }\n\n // Set locals\n safeSetLink(this, localField, record)\n\n // Update (set) inverse relation\n safeSetProp(record, foreignKey, utils.get(this, idAttribute))\n self.getCollection(relation).updateIndex(record, updateOpts)\n safeSetLink(record, inverseLocalField, this)\n } else {\n // Unset locals\n safeSetLink(this, localField, undefined)\n }\n return record\n }\n }\n }\n\n if (descriptor) {\n descriptor.enumerable = def.enumerable === undefined ? false : def.enumerable\n if (def.get) {\n let origGet = descriptor.get\n descriptor.get = function () {\n return def.get(def, this, (...args) => origGet.apply(this, args))\n }\n }\n if (def.set) {\n let origSet = descriptor.set\n descriptor.set = function (related) {\n return def.set(def, this, related, (value) => origSet.call(this, value === undefined ? related : value))\n }\n }\n Object.defineProperty(mapper.recordClass.prototype, localField, descriptor)\n }\n })\n\n return mapper\n },\n\n destroy (name, id, opts) {\n opts || (opts = {})\n return SimpleStore.prototype.destroy.call(this, name, id, opts).then((result) => {\n let record\n if (opts.raw) {\n record = result.data\n } else {\n record = result\n }\n\n if (record && this.unlinkOnDestroy) {\n const _opts = utils.plainCopy(opts)\n _opts.withAll = true\n utils.forEachRelation(this.getMapper(name), _opts, (def) => {\n utils.set(record, def.localField, undefined)\n })\n }\n return result\n })\n },\n\n destroyAll (name, query, opts) {\n opts || (opts = {})\n return SimpleStore.prototype.destroyAll.call(this, name, query, opts).then((result) => {\n let records\n if (opts.raw) {\n records = result.data\n } else {\n records = result\n }\n\n if (records && records.length && this.unlinkOnDestroy) {\n const _opts = utils.plainCopy(opts)\n _opts.withAll = true\n utils.forEachRelation(this.getMapper(name), _opts, (def) => {\n records.forEach((record) => {\n utils.set(record, def.localField, undefined)\n })\n })\n }\n return result\n })\n }\n}\n\nexport default SimpleStore.extend(props)\n\n/**\n * Create a subclass of this DataStore:\n * @example DataStore.extend\n * const JSData = require('js-data');\n * const { DataStore } = JSData;\n * console.log('Using JSData v' + JSData.version.full);\n *\n * // Extend the class using ES2015 class syntax.\n * class CustomDataStoreClass extends DataStore {\n * foo () { return 'bar'; }\n * static beep () { return 'boop'; }\n * }\n * const customDataStore = new CustomDataStoreClass();\n * console.log(customDataStore.foo());\n * console.log(CustomDataStoreClass.beep());\n *\n * // Extend the class using alternate method.\n * const OtherDataStoreClass = DataStore.extend({\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const otherDataStore = new OtherDataStoreClass();\n * console.log(otherDataStore.foo());\n * console.log(OtherDataStoreClass.beep());\n *\n * // Extend the class, providing a custom constructor.\n * function AnotherDataStoreClass () {\n * DataStore.call(this);\n * this.created_at = new Date().getTime();\n * }\n * DataStore.extend({\n * constructor: AnotherDataStoreClass,\n * foo () { return 'bar'; }\n * }, {\n * beep () { return 'boop'; }\n * });\n * const anotherDataStore = new AnotherDataStoreClass();\n * console.log(anotherDataStore.created_at);\n * console.log(anotherDataStore.foo());\n * console.log(AnotherDataStoreClass.beep());\n *\n * @method DataStore.extend\n * @param {object} [props={}] Properties to add to the prototype of the\n * subclass.\n * @param {object} [props.constructor] Provide a custom constructor function\n * to be used as the subclass itself.\n * @param {object} [classProps={}] Static properties to add to the subclass.\n * @returns {Constructor} Subclass of this DataStore class.\n * @since 3.0.0\n */\n","/**\n * Registered as `js-data` in NPM and Bower.\n *\n * Also available from CDN.JS and JSDelivr.\n *\n * @module js-data\n *\n * @example Install from NPM\n * npm i --save js-data@beta\n * @example Install from Bower\n * bower i --save js-data@3.0.0-beta.1\n * @example Install from CDN.JS\n * \n * @example Install from JSDelivr\n * \n * @example Load into your app via script tag\n * \n * \n * @example Load into your app via CommonJS\n * var JSData = require('js-data');\n * @example Load into your app via ES2015 Modules\n * import * as JSData from 'js-data';\n * @example Load into your app via AMD\n * define('myApp', ['js-data'], function (JSData) { ... });\n */\n\n/**\n * JSData's utility methods.\n *\n * @example\n * import { utils } from 'js-data';\n * console.log(utils.isString('foo')); // true\n *\n * @name module:js-data.utils\n * @property {Function} Promise See {@link utils.Promise}.\n * @see utils\n * @since 3.0.0\n * @type {Object}\n */\nimport utils from './utils'\n\n/**\n * JSData's {@link Collection} class.\n *\n * @example\n * import { Collection } from 'js-data';\n * const collection = new Collection();\n *\n * @name module:js-data.Collection\n * @see Collection\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#collection\",\"Components of JSData: Collection\"]\n * @type {Constructor}\n */\nimport Collection from './Collection'\n\n/**\n * JSData's {@link Component} class. Most components in JSData extend this\n * class.\n *\n * @example\n * import { Component } from 'js-data';\n * // Make a custom component.\n * const MyComponent = Component.extend({\n * myMethod (someArg) { ... }\n * });\n *\n * @name module:js-data.Component\n * @see Component\n * @since 3.0.0\n * @type {Constructor}\n */\nimport Component from './Component'\n\n/**\n * JSData's {@link Container} class. Defines and manages {@link Mapper}s. Used\n * in Node.js and in the browser, though in the browser you may want to use\n * {@link DataStore} instead.\n *\n * @example\n * import { Container } from 'js-data';\n * const store = new Container();\n *\n * @name module:js-data.Container\n * @see Container\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#container\",\"Components of JSData: Container\"]\n * @type {Constructor}\n */\nimport {Container} from './Container'\n\n/**\n * JSData's {@link DataStore} class. Primarily for use in the browser. In\n * Node.js you probably want to use {@link Container} instead.\n *\n * @example\n * import { DataStore } from 'js-data';\n * const store = new DataStore();\n *\n * @name module:js-data.DataStore\n * @see DataStore\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#datastore\",\"Components of JSData: DataStore\"]\n * @type {Constructor}\n */\nimport DataStore from './DataStore'\n\n/**\n * JSData's {@link Index} class, based on [mindex]{@link https://github.com/internalfx/mindex}.\n *\n * @name module:js-data.Index\n * @see Index\n * @since 3.0.0\n * @type {Constructor}\n */\nimport Index from '../lib/mindex/index'\n\n/**\n * JSData's {@link LinkedCollection} class. Used by the {@link DataStore}\n * component. If you need to create a collection manually, you should probably\n * use the {@link Collection} class.\n *\n * @name module:js-data.LinkedCollection\n * @see DataStore\n * @see LinkedCollection\n * @since 3.0.0\n * @type {Constructor}\n */\nimport LinkedCollection from './LinkedCollection'\n\n/**\n * JSData's {@link Mapper} class. The core of the ORM.\n *\n * @example Recommended use\n * import { Container } from 'js-data';\n * const store = new Container();\n * store.defineMapper('user');\n *\n * @example Create Mapper manually\n * import { Mapper } from 'js-data';\n * const UserMapper = new Mapper({ name: 'user' });\n *\n * @name module:js-data.Mapper\n * @see Container\n * @see Mapper\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/modeling-your-data\",\"Modeling your data\"]\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#mapper\",\"Components of JSData: Mapper\"]\n * @type {Constructor}\n */\nimport Mapper from './Mapper'\n\n/**\n * JSData's {@link Query} class. Used by the {@link Collection} component.\n *\n * @name module:js-data.Query\n * @see Query\n * @since 3.0.0\n * @type {Constructor}\n */\nimport Query from './Query'\n\n/**\n * JSData's {@link Record} class.\n *\n * @example\n * import { Container } from 'js-data';\n * const store = new Container();\n * store.defineMapper('user');\n * const user = store.createRecord('user');\n *\n * @name module:js-data.Record\n * @see Record\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#record\",\"Components of JSData: Record\"]\n * @type {Constructor}\n */\nimport Record from './Record'\n\n/**\n * JSData's {@link Schema} class. Implements http://json-schema.org/draft-04.\n *\n * @example\n * import { Container, Schema } from 'js-data';\n * const userSchema = new Schema({\n * properties: {\n * id: { type: 'string' },\n * name: { type: 'string' }\n * }\n * });\n * const store = new Container();\n * store.defineMapper('user', {\n * schema: userSchema\n * });\n *\n * @name module:js-data.Schema\n * @see Schema\n * @see http://json-schema.org/\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#schema\",\"Components of JSData: schema\"]\n * @tutorial [\"http://www.js-data.io/v3.0/docs/schemas\",\"JSData's Schema Syntax\"]\n * @type {Constructor}\n */\nimport Schema from './Schema'\n\n/**\n * JSData's {@link Settable} class.\n *\n * @example\n * import { Settable } from 'js-data';\n * const obj = new Settable();\n * obj.set('secret', 'value');\n * console.log(JSON.stringify(obj)); // {}\n *\n * @name module:js-data.Settable\n * @see Settable\n * @since 3.0.0\n * @type {Constructor}\n */\nimport Settable from './Settable'\n\n/**\n * JSData's {@link SimpleStore} class. Primarily for use in the browser. In\n * Node.js you probably want to use {@link Container} instead.\n *\n * @example\n * import { SimpleStore } from 'js-data';\n * const store = new SimpleStore();\n *\n * @name module:js-data.SimpleStore\n * @see SimpleStore\n * @since 3.0.0\n * @tutorial [\"http://www.js-data.io/v3.0/docs/components-of-jsdata#SimpleStore\",\"Components of JSData: SimpleStore\"]\n * @type {Constructor}\n */\nimport SimpleStore from './SimpleStore'\n\n/**\n * Describes the version of this `JSData` object.\n *\n * @example\n * console.log(JSData.version.full); // \"3.0.0-beta.1\"\n *\n * @name version\n * @memberof module:js-data\n * @property {string} full The full semver value.\n * @property {number} major The major version number.\n * @property {number} minor The minor version number.\n * @property {number} patch The patch version number.\n * @property {(string|boolean)} alpha The alpha version value, otherwise `false`\n * if the current version is not alpha.\n * @property {(string|boolean)} beta The beta version value, otherwise `false`\n * if the current version is not beta.\n * @since 2.0.0\n * @type {Object}\n */\nexport const version = '<%= version %>'\n\nexport * from './decorators'\n\nexport {\n Collection,\n Component,\n Container,\n DataStore,\n Index,\n LinkedCollection,\n Mapper,\n Query,\n Record,\n Schema,\n Settable,\n SimpleStore,\n utils\n}\n"],"names":["DOMAIN","INFINITY","MAX_INTEGER","BOOL_TAG","DATE_TAG","FUNC_TAG","NUMBER_TAG","OBJECT_TAG","REGEXP_TAG","STRING_TAG","objToString","Object","prototype","toString","PATH","ERRORS","arguments","toInteger","value","sign","remainder","toStr","call","isPlainObject","constructor","mkdirP","object","path","parts","split","forEach","key","utils","Promise","dest","src","forOwn","undefined","isFunction","indexOf","opts","def","fn","thisArg","relationName","relation","containedName","index","with","_getIndex","localField","withAll","optsCopy","fillIn","getRelation","slice","_activeWith","splice","i","length","substr","list","_relation","isObject","target","props","map","keys","propName","descriptor","getOwnPropertyDescriptor","enumerable","defineProperties","newObject","oldObject","diff","diffObjects","diffCount","added","removed","changed","instance","ctor","err","name","from","to","stackFrom","stackTo","blacklist","plain","isArray","copy","isDate","Date","getTime","isRegExp","RegExp","source","match","lastIndex","create","getPrototypeOf","push","result","hasOwnProperty","isBlacklisted","existing","deepFillIn","deepMixIn","equalsFn","ignore","deepEqual","newKeys","filter","oldKeys","oldValue","newValue","a","b","domain","code","prefix","message","apply","Array","Error","getter","setter","_events","events","args","type","shift","listeners","f","c","all","unshift","func","classProps","superClass","subClass","classCallCheck","obj","setPrototypeOf","strictEs6Class","__proto__","defineProperty","addHiddenPropsToTarget","array","record","mapper","relationList","_forRelation","len","json","isString","JSON","parse","prop","last","pop","isCtor","__super__","array1","array2","item","matches","test","isNumber","log","level","debug","toUpperCase","console","findIndex","_props","reduce","reject","resolve","_path","set","exec","_equal","stringify","safeSetProp","field","_set","safeSetLink","Settable","get","unset","extend","Component","writable","logify","eventify","_listeners","INDEX_ERR","reserved","escapeRegExp","percentRegExp","underscoreRegExp","escape","pattern","replace","Query","collection","data","where","fields","ops","predicates","clause","expr","op","groups","_where","prev","parser","_applyWhereFromArray","_applyWhereFromObject","group","isOr","keep","first","charAt","evaluate","_testArrayGroup","_testObjectGroup","leftKeys","rightKeys","getIndex","between","orderBy","cA","cB","temp","compare","predicate","like","query","getData","sort","skip","offset","limit","forEachFn","keyList","concat","getAll","flags","num","Math","min","mapFn","funcName","intersection","belongsToType","hasManyType","hasOneType","Relation","relatedMapper","options","TYPE_NAME","validateOptions","canAutoAddLinks","add","relatedCollection","datastore","getCollection","related","DOMAIN_ERR","foreignKey","localKey","relationFields","idAttribute","relatedRecord","_setForeignKey","relatedRecords","relatedData","inverse","findInverseRelation","isInversedTo","records","getLocalField","linkRecord","isEmptyLinks","canFindLinkFor","findExistingLinksFor","setLocalField","relatedId","unsaved","setForeignKey","id","relationData","is","createRecord","createLinked","then","BelongsToRelation","HasManyRelation","localKeys","foreignKeys","hasForeignKeys","recordId","ids","findExistingLinksByForeignKey","findExistingLinksByLocalKeys","findExistingLinksByForeignKeys","foreignIdField","createMany","HasOneRelation","RelationType","belongsTo","assignTo","hasMany","hasOne","superMethod","store","bind","creatingPath","noValidatePath","keepChangeHistoryPath","previousPath","Record","noValidate","keepChangeHistory","validateOnSet","toJSON","plainCopy","_get","_mapper","quickHasChanges","areDifferent","validate","currentParent","inverseDef","children","remove","child","noDupeAdd","relations","_","adapter","getAdapterName","dbg","tasks","task","forEachRelation","raw","load","isSorN","previous","preserve","commit","postProcess","changesOnly","changes","silent","hashCode","insertAt","removeAt","binarySearch","lo","hi","compared","mid","Index","fieldList","fieldGetter","isIndex","values","pos","found","dataLocation","newIndex","results","order","cb","visitAll","_between","leftKey","rightKey","leftInclusive","rightInclusive","currKey","peek","isUnique","removeRecord","j","insertRecord","COLLECTION_DEFAULTS","Collection","queryClass","emitRecordEvents","emit","beforeAdd","singular","onConflict","existingNoValidate","commitOnMerge","updateIndexes","indexes","on","_onRecordEvent","afterAdd","run","instances","removeAll","Ctor","initialValue","idOrRecord","beforeRemove","off","afterRemove","queryOrRecords","beforeRemoveAll","afterRemoveAll","mapCall","updateRecord","types","isBoolean","isInteger","isNull","segmentToString","segment","str","makePath","segments","makeError","actual","expected","addError","errors","maxLengthCommon","keyword","schema","max","minLengthCommon","validationKeywords","allErrors","allOf","_schema","validated","anyOf","possibleValues","join","items","checkingTuple","maximum","exclusiveMaximum","maxProperties","minimum","exclusiveMinimum","minProperties","multipleOf","not","oneOf","additionalProperties","properties","patternProperties","toValidate","omit","undef","origProp","required","existingOnly","prevProp","validType","_type","validator","typeGroupValidators","uniqueItems","runOps","ANY_OPS","ARRAY_OPS","NUMERIC_OPS","OBJECT_OPS","STRING_OPS","validateAny","ctx","shouldPop","changingPath","changedPath","changeHistoryPath","eventIdPath","silentPath","validationFailureMsg","numeric","Schema","definition","_definition","extends","validationKeyword","unsetter","track","makeDescriptor","hasSet","orig","applyDefaults","keyPath","originalGet","_unset","error","current","changing","setTimeout","changeRecord","timestamp","changeHistory","originalSet","pick","_copy","applyDefaultsHooks","validatingHooks","makeNotify","getSchema","toProcess","originalExistingOnly","notify","notify2","LIFECYCLE_METHODS","MAPPER_DEFAULTS","Mapper","recordClass","methods","isPrototypeOf","applySchema","_data","wrap","crud","originalRecord","parentRelationMap","adapterResponse","_runHook","_createParentRecordIfRequired","relationMap","_invokeAdapterMethod","createdProps","_createOrAssignChildRecordIfRequired","_commitChanges","_end","recordOrRecords","newValues","isRequiresParentId","createParentRecord","context","originalProps","isRequiresChildId","createChildRecord","parent","originalRecords","belongsToRelationData","Boolean","createdRecordsData","belongsToData","createdRecordData","ensureLinkedDataHasProperType","RecordCtor","method","config","lifecycleMethods","upper","before","after","defaults","_value","beforeAssign","adapterArgs","getAdapter","_result","getAdapters","defaultAdapter","_adapters","default","hookName","hookArgs","defaultValueIndex","overridenResult","propsOrRecords","conversionOptions","pass","_opts","_record","some","_name","getMapperByName","getMapper","proxiedMapperMethods","Container","mapperDefaults","mapperClass","original","_mappers","_onMapperEvent","defineRelations","warn","defineMapper","proxiedCollectionMethods","ownMethodsForScoping","cachedFn","hashOrId","cached","_completedQueries","SIMPLESTORE_DEFAULTS","SimpleStore","collectionClass","_collections","_pendingQueries","addToCache","hash","fromJson","self","collectionOpts","indexed","createIndex","_added","_onCollectionEvent","destroy","destroyAll","hashQuery","pendingQuery","usePendingFind","cachedFind","force","promise","find","cacheFind","usePendingFindAll","cachedFindAll","findAll","cacheFindAll","toJson","removeRelated","getForeignKey","update","updateAll","updateMany","LinkedCollection","event","addLinkedRecords","_addMeta","_clearMeta","removeLinkedRecords","DATASTORE_DEFAULTS","DataStore","updateOpts","getInverse","removeInverseRelation","relatedIdAttribute","updateIndex","setupInverseRelation","foreignKeyDescriptor","currentParentId","storeRecord","inverseLocalField","toLink","toLinkIds","currentChildrenOfParent","parents","_key","origGet","origSet","unlinkOnDestroy","version"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;AAW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AAQlO,MAAnB,IAA6B,OAAK8lB,eAAtC,EAAuD;YAC/CjF,QAAQxiB,MAAM2S,SAAN,CAAgBnS,IAAhB,CAAd;cACMW,OAAN,GAAgB,IAAhB;cACM2S,eAAN,CAAsB,OAAK+O,SAAL,CAAezf,IAAf,CAAtB,EAA4Cof,KAA5C,EAAmD,UAAC/hB,GAAD,EAAS;kBAClDX,OAAR,CAAgB,UAACyH,MAAD,EAAY;kBACpB+B,GAAN,CAAU/B,MAAV,EAAkB9G,IAAIS,UAAtB,EAAkCb,SAAlC;WADF;SADF;;aAMKmE,MAAP;KAjBK,CAAP;;CA5WJ;;AAkYA,kBAAeuf,cAAY9Z,MAAZ,CAAmBhI,OAAnB,CAAf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACpdA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,AAEA;;;;;;;;;;;;;AAaA,AAEA;;;;;;;;;;;;;;;;AAgBA,AAEA;;;;;;;;;;;;;;;AAeA,AAEA;;;;;;;;;;;;;;AAcA,AAEA;;;;;;;;AAQA,AAEA;;;;;;;;;;;AAWA,AAEA;;;;;;;;;;;;;;;;;;;;AAoBA,AAEA;;;;;;;;AAQA,AAEA;;;;;;;;;;;;;;;AAeA,AAEA;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,AAEA;;;;;;;;;;;;;;AAcA,AAEA;;;;;;;;;;;;;;AAcA,AAEA;;;;;;;;;;;;;;;;;;;AAmBA,AAAO,IAAMylB,UAAU,gBAAhB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/dist/js-data.min.js b/dist/js-data.min.js new file mode 100644 index 00000000..f90ca653 --- /dev/null +++ b/dist/js-data.min.js @@ -0,0 +1,11 @@ +/*! +* js-data +* @version 3.0.2 - Homepage +* @author js-data project authors +* @copyright (c) 2014-2016 js-data project authors +* @license MIT +* +* @overview js-data is a framework-agnostic, datastore-agnostic ORM/ODM for Node.js and the Browser. +*/ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define("js-data",["exports"],t):t(e.JSData={})}(this,function(e){"use strict";function Settable(){var e={};Object.defineProperties(this,{_get:{value:function value(t){return d.get(e,t)}},_set:{value:function value(t,n){return d.set(e,t,n)}},_unset:{value:function value(t){return d.unset(e,t)}}})}function Component(e){Settable.call(this),e||(e={}),this.debug=!!e.hasOwnProperty("debug")&&!!e.debug,Object.defineProperty(this,"_listeners",{value:{},writable:!0})}function Query(e){d.classCallCheck(this,Query),this.collection=e,this.data=null}function Relation(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};d.classCallCheck(this,Relation),n.type=this.constructor.TYPE_NAME,this.validateOptions(e,n),"object"===(void 0===e?"undefined":t(e))&&Object.defineProperty(this,"relatedMapper",{value:e}),Object.defineProperty(this,"inverse",{writable:!0}),d.fillIn(this,n)}function Record(e,t){d.classCallCheck(this,Record),Settable.call(this),e||(e={}),t||(t={});var n=this._set,i=this.constructor.mapper;n(k,!0),n(I,!!t.noValidate),n(F,void 0===t.keepChangeHistory?!i||i.keepChangeHistory:t.keepChangeHistory);var r=i?d.get(e,i.idAttribute):void 0;void 0!==r&&d.set(this,i.idAttribute,r),d.fillIn(this,e),n(k,!1),void 0!==t.validateOnSet?n(I,!t.validateOnSet):i&&void 0!==i.validateOnSet?n(I,!i.validateOnSet):n(I,!1),n(E,i?i.toJSON(e):d.plainCopy(e))}function sort(e,t,n){return e===t?0:(n&&(e=n(e),t=n(t)),null===e&&null===t||void 0===e&&void 0===t?-1:null===e||void 0===e?-1:null===t||void 0===t?1:et?1:0)}function insertAt(e,t,n){return e.splice(t,0,n),e}function removeAt(e,t){return e.splice(t,1),e}function binarySearch(e,t,n){for(var i=0,r=e.length,o=void 0,a=void 0;i=0?o=r:(a=d._getIndex(e.with,t.localField))>=0&&(o=t.localField),e.withAll)n.call(i,t,{});else if(o){var s={};d.fillIn(s,t.getRelation()),d.fillIn(s,e),s.with=e.with.slice(),s._activeWith=s.with.splice(a,1)[0],s.with.forEach(function(e,t){e&&0===e.indexOf(o)&&e.length>=o.length&&"."===e[o.length]?s.with[t]=e.substr(o.length+1):s.with[t]=""}),n.call(i,t,s)}},_getIndex:function _getIndex(e,t){var n=-1;return e.forEach(function(e,i){return e===t?(n=i,!1):d.isObject(e)&&e.relation===t?(n=i,!1):void 0}),n},addHiddenPropsToTarget:function addHiddenPropsToTarget(e,t){var n={};Object.keys(t).forEach(function(e){var i=Object.getOwnPropertyDescriptor(t,e);i.enumerable=!1,n[e]=i}),Object.defineProperties(e,n)},areDifferent:function areDifferent(e,t,n){n||(n={});var i=d.diffObjects(e,t,n);return Object.keys(i.added).length+Object.keys(i.removed).length+Object.keys(i.changed).length>0},classCallCheck:function classCallCheck$$1(e,t){if(!(e instanceof t))throw d.err(""+t.name)(500,"Cannot call a class as a function")},copy:function copy(e,t,n,i,r,o){if(t){if(e===t)throw d.err("utils.copy")(500,"Cannot copy! Source and destination are identical.");if(n=n||[],i=i||[],d.isObject(e)){var a=n.indexOf(e);if(-1!==a)return i[a];n.push(e),i.push(t)}var s=void 0;if(d.isArray(e)){var c=void 0;for(t.length=0,c=0;c1?t-1:0),i=1;i=0&&e.splice(n,1)}},resolve:function resolve(e){return d.Promise.resolve(e)},set:function set$$1(e,t,n){if(d.isObject(t))d.forOwn(t,function(t,n){d.set(e,n,t)});else{var i=o.exec(t);i?u(e,i[1])[i[2]]=n:e[t]=n}},deepEqual:function deepEqual(e,t){if(e===t)return!0;var n=!0;if(d.isArray(e)&&d.isArray(t)){if(e.length!==t.length)return!1;for(var i=e.length;i--;)if(!d.deepEqual(e[i],t[i]))return!1}else{if(!d.isObject(e)||!d.isObject(t))return!1;d.forOwn(e,function(e,i){if(!(n=d.deepEqual(e,t[i])))return!1}),n&&d.forOwn(t,function(t,i){if(!(n=d.deepEqual(t,e[i])))return!1})}return n},toJson:JSON.stringify,unset:function unset(e,t){for(var n=t.split("."),i=n.pop();t=n.shift();)if(null==(e=e[t]))return;e[i]=void 0}},f=function safeSetProp(e,t,n){e&&e._set?e._set("props."+t,n):d.set(e,t,n)},h=function safeSetLink(e,t,n){e&&e._set?e._set("links."+t,n):d.set(e,t,n)};Settable.extend=d.extend;var p=Settable.extend({constructor:Component});Component.extend=d.extend,d.logify(Component.prototype),d.eventify(Component.prototype,function(){return this._listeners},function(e){this._listeners=e});var v="Index inaccessible after first operation",g={limit:"",offset:"",orderBy:"",skip:"",sort:"",where:""},y=/([.*+?^=!:${}()|[\]/\\])/g,m=/%/g,A=/_/g,b=function escape(e){return e.replace(y,"\\$1")},O=p.extend({constructor:Query,_applyWhereFromObject:function _applyWhereFromObject(e){var t=[],n=[],i=[];return d.forOwn(e,function(e,r){d.isObject(e)||(e={"==":e}),d.forOwn(e,function(e,o){t.push(r),n.push(o),i.push(e)})}),{fields:t,ops:n,predicates:i}},_applyWhereFromArray:function _applyWhereFromArray(e){var t=this,n=[];return e.forEach(function(i,r){if(!d.isString(i)){var o=e[r-1],a=(d.isArray(i)?t._applyWhereFromArray:t._applyWhereFromObject).call(t,i);"or"===o&&(a.isOr=!0),n.push(a)}}),n.isArray=!0,n},_testObjectGroup:function _testObjectGroup(e,t,n,i){var r=void 0,o=n.fields,a=n.ops,s=n.predicates,c=a.length;for(r=0;ra?1:t1?t-1:0),i=1;i":function _(e,t){return e>t},">=":function _(e,t){return e>=t},"<":function _(e,t){return e")(400,"string",r)},canFindLinkFor:function canFindLinkFor(e){return!!(this.foreignKey||this.foreignKeys||this.localKeys&&d.get(e,this.localKeys))},linkRecord:function linkRecord(e,t){var n=this,i=this.relatedCollection,r=this.canAutoAddLinks,o=this.foreignKey,a=this.relatedCollection.unsaved();return t.map(function(t){var s=i.recordId(t);return(void 0===s&&-1===a.indexOf(t)||t!==i.get(s))&&(o&&n.setForeignKey(e,t),r&&(t=i.add(t))),t})},findExistingLinksFor:function findExistingLinksFor(e){var t=d.get(e,this.mapper.idAttribute),n=this.localKeys?d.get(e,this.localKeys):null,i=void 0;if(void 0!==t&&this.foreignKey?i=this.findExistingLinksByForeignKey(t):this.localKeys&&n?i=this.findExistingLinksByLocalKeys(n):void 0!==t&&this.foreignKeys&&(i=this.findExistingLinksByForeignKeys(t)),i&&i.length)return i},findExistingLinksByLocalKeys:function findExistingLinksByLocalKeys(e){return this.relatedCollection.filter({where:n({},this.mapper.idAttribute,{in:e})})},findExistingLinksByForeignKeys:function findExistingLinksByForeignKeys(e){return this.relatedCollection.filter({where:n({},this.foreignKeys,{contains:e})})},isRequiresParentId:function isRequiresParentId(){return!!this.localKeys&&this.localKeys.length>0},isRequiresChildId:function isRequiresChildId(){return!!this.foreignKey},createParentRecord:function createParentRecord(e,t){var n=this,i=this.getLocalField(e),r=this.getRelation().idAttribute;return this.createLinked(i,t).then(function(t){d.set(e,n.localKeys,t.map(function(e){return d.get(e,r)}))})},createLinked:function createLinked(e,t){return this.getRelation().createMany(e,t)}},{TYPE_NAME:"hasMany"}),Relation.extend({findExistingLinksFor:function findExistingLinksFor(e,t){var n=d.get(t,e.idAttribute),i=this.findExistingLinksByForeignKey(n);if(i&&i.length)return i[0]},isRequiresChildId:function isRequiresChildId(){return!0}},{TYPE_NAME:"hasOne"})].forEach(function(e){Relation[e.TYPE_NAME]=function(t,n){return new e(t,n)}});var x=function belongsTo(e,t){return function(n){Relation.belongsTo(e,t).assignTo(n)}},C=function hasMany(e,t){return function(n){Relation.hasMany(e,t).assignTo(n)}},w=function hasOne(e,t){return function(n){Relation.hasOne(e,t).assignTo(n)}},R=function superMethod(e,t){var n=e.datastore;return n&&n[t]?function(){for(var i=arguments.length,r=Array(i),o=0;o=0;i--){var r=n[i];t=r.isIndex?t.concat(r.getAll(e)):t.concat(r)}else for(var o=0;oo)break}else if(this.keys[s]>=o)break;if(i=this.values[s].isIndex?i.concat(this.values[s].getAll()):i.concat(this.values[s]),n.limit&&i.length>=n.limit+n.offset)break}}else for(var c=a.index;co)break;if(i=this.values[c].isIndex?l===r?i.concat(this.values[c]._between(d.copy(e),t.map(function(){}),n)):l===o?i.concat(this.values[c]._between(e.map(function(){}),d.copy(t),n)):i.concat(this.values[c].getAll()):i.concat(this.values[c]),n.limit&&i.length>=n.limit+n.offset)break}return n.limit?i.slice(0,n.limit+n.offset):i},peek:function peek(){return this.values.length?this.values[0].isIndex?this.values[0].peek():this.values[0]:[]},clear:function clear(){this.keys=[],this.values=[]},insertRecord:function insertRecord(e){var t=this.fieldList.map(function(t){return d.isFunction(t)?t(e)||void 0:e[t]||void 0});this.set(t,e)},removeRecord:function removeRecord(e){var t=this,n=void 0,i=void 0!==this.hashCode(e);return this.values.forEach(function(r,o){if(r.isIndex){if(r.removeRecord(e))return 0===r.keys.length&&(removeAt(t.keys,o),removeAt(t.values,o)),n=!0,!1}else{var a={};if(void 0!==t.keys[o]&&i)i&&(a=binarySearch(r,e,t.hashCode));else for(var s=r.length-1;s>=0;s--)if(r[s]===e){a={found:!0,index:s};break}if(a.found)return removeAt(r,a.index),0===r.length&&(removeAt(t.keys,o),removeAt(t.values,o)),n=!0,!1}}),n?e:void 0},updateRecord:function updateRecord(e){void 0!==this.removeRecord(e)&&this.insertRecord(e)}});var S=j.noValidatePath,P={commitOnMerge:!0,emitRecordEvents:!0,idAttribute:"id",onConflict:"merge"},M=p.extend({constructor:Collection,_onRecordEvent:function _onRecordEvent(){this.emitRecordEvents&&this.emit.apply(this,arguments)},add:function add(e,t){var n=this;t||(t={}),d._(t,this),e=this.beforeAdd(e,t)||e;var i=!1,r=this.recordId();if(!d.isArray(e)){if(!d.isObject(e))throw d.err("Collection#add","records")(400,"object or array",e);e=[e],i=!0}e=e.map(function(e){var i=n.recordId(e),o=void 0===i?i:n.get(i);if(e===o)return o;if(o){var a=t.onConflict||n.onConflict;if("merge"!==a&&"replace"!==a&&"skip"!==a)throw d.err("Collection#add","opts.onConflict")(400,"one of (merge, replace, skip)",a,!0);var s=o._get(S);t.noValidate&&o._set(S,!0),"merge"===a?d.deepMixIn(o,e):"replace"===a&&(d.forOwn(o,function(t,n){n!==r&&void 0===e[n]&&(o[n]=void 0)}),o.set(e)),t.noValidate&&o._set(S,s),e=o,t.commitOnMerge&&d.isFunction(e.commit)&&e.commit(),n.updateIndexes(e)}else e=n.mapper?n.mapper.createRecord(e,t):e,n.index.insertRecord(e),d.forOwn(n.indexes,function(t,n){t.insertRecord(e)}),e&&d.isFunction(e.on)&&e.on("all",n._onRecordEvent,n);return e});var o=i?e[0]:e;return t.silent||this.emit("add",o),this.afterAdd(e,t,o)||o},afterAdd:function afterAdd(){},afterRemove:function afterRemove(){},afterRemoveAll:function afterRemoveAll(){},beforeAdd:function beforeAdd(){},beforeRemove:function beforeRemove(){},beforeRemoveAll:function beforeRemoveAll(){},between:function between(e,t,n){return this.query().between(e,t,n).run()},createIndex:function createIndex(e,t,n){var i=this;d.isString(e)&&void 0===t&&(t=[e]),n||(n={}),n.hashCode||(n.hashCode=function(e){return i.recordId(e)});var r=this.indexes[e]=new Index(t,n);this.index.visitAll(r.insertRecord,r)},filter:function filter(e,t){return this.query().filter(e,t).run()},forEach:function forEach(e,t){this.index.visitAll(e,t)},get:function get(e){var t=void 0===e?[]:this.query().get(e).run();return t.length?t[0]:void 0},getAll:function getAll(){var e;return(e=this.query()).getAll.apply(e,arguments).run()},getIndex:function getIndex(e){var t=e?this.indexes[e]:this.index;if(!t)throw d.err("Collection#getIndex",e)(404,"index");return t},limit:function limit(e){return this.query().limit(e).run()},map:function map(e,t){var n=[];return this.index.visitAll(function(i){n.push(e.call(t,i))}),n},mapCall:function mapCall(e){for(var t=arguments.length,n=Array(t>1?t-1:0),i=1;ir)return D(t.length,"length no more than "+r,i)},Q=function minLengthCommon(e,t,n,i){var r=n[e];if(t.lengthe:maximum>=e))return r?D(e,"no more than nor equal to "+maximum,i):D(e,"no more than "+maximum,i)},maxItems:function maxItems(e,t,n){if(d.isArray(e))return q("maxItems",e,t,n)},maxLength:function maxLength(e,t,n){return q("maxLength",e,t,n)},maxProperties:function maxProperties(e,t,n){if(d.isObject(e)){var maxProperties=t.maxProperties,i=Object.keys(e).length;return i>maxProperties?D(i,"no more than "+maxProperties+" properties",n):void 0}},minimum:function minimum(e,n,i){var minimum=n.minimum,r=n.exclusiveMinimum;if((void 0===e?"undefined":t(e))===(void 0===minimum?"undefined":t(minimum))&&!(r?e>minimum:e>=minimum))return r?D(e,"no less than nor equal to "+minimum,i):D(e,"no less than "+minimum,i)},minItems:function minItems(e,t,n){if(d.isArray(e))return Q("minItems",e,t,n)},minLength:function minLength(e,t,n){return Q("minLength",e,t,n)},minProperties:function minProperties(e,t,n){if(d.isObject(e)){var minProperties=t.minProperties,i=Object.keys(e).length;return i0;r--)for(i=e[r],o=r-1;o>=0;o--)if(d.deepEqual(i,e[o]))return D(i,"no duplicates",n)}}},B=function runOps(e,t,n,i){var r=[];return e.forEach(function(e){void 0!==n[e]&&(r=r.concat(J[e](t,n,i)||[]))}),r.length?r:void 0},$=["enum","type","allOf","anyOf","oneOf","not"],H=["items","maxItems","minItems","uniqueItems"],U=["multipleOf","maximum","minimum"],V=["maxProperties","minProperties","required","properties","dependencies"],G=["maxLength","minLength","pattern"],W=function validateAny(e,t,n){return B($,e,t,n)},Y=function _validate(e,t,n){var i=[];n||(n={}),n.ctx||(n.ctx={value:e,schema:t});var r=void 0,o=n.prop;if(void 0!==t){if(!d.isObject(t))throw d.err("Schema#validate")(500,'Invalid schema at path: "'+n.path+'"');return void 0===n.path&&(n.path=[]),void 0!==n.prop&&(r=!0,n.path.push(n.prop),n.prop=void 0),t.extends&&(i=d.isFunction(t.extends.validate)?i.concat(t.extends.validate(e,n)||[]):i.concat(_validate(e,t.extends,n)||[])),void 0===e?(!0!==t.required||n.existingOnly||T(e,"a value",n,i),r&&(n.path.pop(),n.prop=o),i.length?i:void 0):(i=i.concat(W(e,t,n)||[]),r&&(n.path.pop(),n.prop=o),i.length?i:void 0)}},z={array:function array(e,t,n){return B(H,e,t,n)},integer:function integer(e,t,n){return z.numeric(e,t,n)},number:function number(e,t,n){return z.numeric(e,t,n)},numeric:function numeric(e,t,n){return B(U,e,t,n)},object:function object(e,t,n){return B(V,e,t,n)},string:function string(e,t,n){return B(G,e,t,n)}},X=p.extend({constructor:Schema,apply:function apply(e,t){var n=this;t||(t={}),t.getter||(t.getter="_get"),t.setter||(t.setter="_set"),t.unsetter||(t.unsetter="_unset"),t.track||(t.track=this.track);var i=this.properties||{};d.forOwn(i,function(i,r){Object.defineProperty(e,r,n.makeDescriptor(r,i,t))})},applyDefaults:function applyDefaults(e){if(e){var t=this.properties||{},n=d.isFunction(e.set)||d.isFunction(e._set);d.forOwn(t,function(t,i){if(t.hasOwnProperty("default")&&void 0===d.get(e,i)&&(n?e.set(i,d.plainCopy(t.default),{silent:!0}):d.set(e,i,d.plainCopy(t.default))),"object"===t.type&&t.properties){if(n){var r=e._get("noValidate");e._set("noValidate",!0),d.set(e,i,d.get(e,i)||{},{silent:!0}),e._set("noValidate",r)}else d.set(e,i,d.get(e,i)||{});t.applyDefaults(d.get(e,i))}})}},makeDescriptor:function makeDescriptor(e,t,i){var r={configurable:!0,enumerable:void 0===t.enumerable||!!t.enumerable},o="props."+e,a="previous."+e,s=i.getter,c=i.setter,l=i.unsetter,u=d.isBoolean(i.track)?i.track:t.track;if(r.get=function(){return this._get(o)},d.isFunction(t.get)){var f=r.get;r.get=function(){return t.get.call(this,f)}}if(r.set=function(i){var r=this,f=this[s],h=this[c],p=this[l];if(!f("noValidate")){var v=t.validate(i,{path:[e]});if(v){var g=new Error("validation failed");throw g.errors=v,g}}if(u&&!f("creating")){var y=f(a),m=f(o),A=f("changing"),b=f("changed");A||(b=[]);var O=b.indexOf(e);m!==i&&-1===O&&b.push(e),y===i&&O>=0&&b.splice(O,1),b.length||(A=!1,p("changing"),p("changed"),f("eventId")&&(clearTimeout(f("eventId")),p("eventId"))),!A&&b.length&&(h("changed",b),h("changing",!0),h("eventId",setTimeout(function(){if(p("changed"),p("eventId"),p("changing"),!f("silent")){var t=void 0;for(t=0;t1?n-1:0),o=1;o1?t-1:0),i=1;i1?t-1:0),i=1;i1?i-1:0),o=1;o1?t-1:0),i=1;i1?i-1:0),o=1;o",">=","<","<=","isectEmpty","isectNotEmpty","in","_in","notIn","contains","notContains","canAutoAddLinks","relatedCollection","getCollection","related","foreignKey","localKey","assignTo","relationFields","canFindLinkFor","getForeignKey","setForeignKey","relatedRecord","_setForeignKey","relatedRecords","getLocalField","setLocalField","relatedData","getInverse","inverse","findInverseRelation","isInversedTo","addLinkedRecords","linkRecord","findExistingLinksFor","removeLinkedRecords","relatedId","unsaved","findExistingLinksByForeignKey","ensureLinkedDataHasProperType","relationData","is","createRecord","isRequiresParentId","isRequiresChildId","createChildRecord","_this4","createLinked","then","createParentRecord","localKeys","foreignKeys","ids","findExistingLinksByLocalKeys","findExistingLinksByForeignKeys","foreignIdField","createMany","RelationType","belongsTo","hasMany","hasOne","superMethod","store","bind","_mapper","DOMAIN$3","afterLoadRelations","beforeLoadRelations","changeHistory","changes","commit","destroy","hasChanges","isNew","isValid","validate","removeInverseRelation","currentParent","inverseDef","children","child","setupInverseRelation","loadRelations","relations","adapter","getAdapterName","tasks","task","raw","load","previous","revert","preserve","save","_this5","postProcess","changesOnly","silent","noValidatePath","pos","dataLocation","newIndex","results","order","_i","visitAll","cb","leftInclusive","rightInclusive","_between","leftKey","rightKey","_i2","currKey","peek","clear","insertRecord","removeRecord","isUnique","j","updateRecord","commitOnMerge","emitRecordEvents","onConflict","_onRecordEvent","beforeAdd","singular","DOMAIN$1","existingNoValidate","updateIndexes","afterAdd","afterRemove","afterRemoveAll","beforeRemove","beforeRemoveAll","createIndex","instances","_query","prune","removeAll","Ctor","initialValue","idOrRecord","queryOrRecords","updateIndex","types","boolean","integer","null","number","string","segmentToString","segment","str","makePath","makeError","actual","expected","addError","errors","maxLengthCommon","keyword","max","minLengthCommon","validationKeywords","allOf","allErrors","_schema","_validate","anyOf","validated","dependencies","enum","_enum","possibleValues","join","checkingTuple","maximum","exclusiveMaximum","maxItems","maxLength","maxProperties","minimum","exclusiveMinimum","minItems","minLength","minProperties","multipleOf","not","oneOf","additionalProperties","patternProperties","toValidate","undef","origProp","required","existingOnly","prevProp","validType","_type","validator","typeGroupValidators","uniqueItems","runOps","ANY_OPS","ARRAY_OPS","NUMERIC_OPS","OBJECT_OPS","STRING_OPS","validateAny","ctx","shouldPop","DOMAIN$7","numeric","unsetter","track","makeDescriptor","applyDefaults","hasSet","orig","keyPath","originalGet","error","current","changing","clearTimeout","setTimeout","changeRecord","timestamp","originalSet","_copy","applyDefaultsHooks","validatingHooks","makeNotify","getSchema","toProcess","originalExistingOnly","notify","notify2","count","defaults","destroyAll","find","findAll","sum","update","adapterArgs","beforeAssign","updateAll","updateMany","defaultAdapter","afterCount","afterCreate","afterCreateMany","afterDestroy","afterDestroyAll","afterFind","afterFindAll","afterSum","afterUpdate","afterUpdateAll","afterUpdateMany","beforeCreate","beforeCreateMany","beforeCount","beforeDestroy","beforeDestroyAll","beforeFind","beforeFindAll","beforeSum","beforeUpdate","beforeUpdateAll","beforeUpdateMany","_end","_data","wrap","belongsTo$$1","crud","originalRecord","parentRelationMap","adapterResponse","_runHook","_createParentRecordIfRequired","relationMap","_invokeAdapterMethod","createdProps","_createOrAssignChildRecordIfRequired","originalProps","_commitChanges","recordOrRecords","newValues","createInstance","context","parent","originalRecords","belongsToRelationData","Boolean","createdRecordsData","belongsToData","createdRecordData","RecordCtor","method","_this6","config","upper","before","after","_getAdapter","getAdapter","_result","getAdapters","hasMany$$1","hasOne$$1","registerAdapter","default","hookName","hookArgs","defaultValueIndex","overridenResult","propsOrRecords","_this7","conversionOptions","pass","_this8","_opts","_record","some","defineRelations","_this9","_name","getMapperByName","getMapper","proxiedMapperMethods","_onMapperEvent","as","original","defineMapper","DOMAIN$5","defineResource","warn","_getMapper","proxiedCollectionMethods","ownMethodsForScoping","cachedFn","hashOrId","cached","usePendingFind","usePendingFindAll","props$2","addToCache","_onCollectionEvent","cachedFind","cachedFindAll","cacheFind","cacheFindAll","hash","self","collectionOpts","indexed","hashQuery","eject","ejectAll","pendingQuery","force","DOMAIN$8","inject","removeRelated","_this10","_this11","_this12","_this13","_getCollection","_addMeta","_clearMeta","event","unlinkOnDestroy","props$1","updateOpts","relatedIdAttribute","foreignKeyDescriptor","currentParentId","storeRecord","inverseLocalField","toLink","toLinkIds","currentChildrenOfParent","parents","origGet","origSet","DataStore$1","version","full","major","minor","patch","belongsToType","hasManyType","hasOneType"],"mappings":"CAAC,SAAUA,EAAQC,GACC,iBAAZC,SAA0C,oBAAXC,OAAyBF,EAAQC,SACrD,mBAAXE,QAAyBA,OAAOC,IAAMD,OAAO,WAAY,WAAYH,GAC3EA,EAASD,EAAOM,WAHlB,CAIEC,KAAM,SAAWL,GAAW,aAmvD9B,SAASM,WACP,IAAIC,KACJC,OAAOC,iBAAiBJ,MAWtBK,MACEC,MAAO,SAASA,MAAMC,GACpB,OAAOC,EAAMC,IAAIP,EAAQK,KAe7BG,MACEJ,MAAO,SAASA,MAAMC,EAAKI,GACzB,OAAOH,EAAMI,IAAIV,EAAQK,EAAKI,KAalCE,QACEP,MAAO,SAASA,MAAMC,GACpB,OAAOC,EAAMM,MAAMZ,EAAQK,OAgFnC,SAASQ,UAAUC,GACjBf,SAASgB,KAAKjB,MACdgB,IAASA,MAuBThB,KAAKkB,QAAQF,EAAKG,eAAe,YAAaH,EAAKE,MAYnDf,OAAOiB,eAAepB,KAAM,cAAgBM,SAAWe,UAAU,IA+NnE,SAASC,MAAMC,GACbf,EAAMgB,eAAexB,KAAMsB,OAS3BtB,KAAKuB,WAAaA,EASlBvB,KAAKyB,KAAO,KA+nCd,SAASC,SAASC,GAChB,IAAIC,EAAUC,UAAUC,OAAS,QAAsBC,IAAjBF,UAAU,GAAmBA,UAAU,MAE7ErB,EAAMgB,eAAexB,KAAM0B,UAE3BE,EAAQI,KAAOhC,KAAKiC,YAAYC,UAChClC,KAAKmC,gBAAgBR,EAAeC,GAEkD,iBAAxD,IA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,EAAQ2B,MAAQ6D,EAChBxF,EAAQ2C,OAAS4E,EACjBvH,EAAQ8F,OAASuB,EACjBrH,EAAQM,SAAWA,SACnBN,EAAQsI,YAAca,GACtBnJ,EAAQa,MAAQA,EAChBb,EAAQgc,UAAYA,EACpBhc,EAAQic,QAAUA,EAClBjc,EAAQkc,OAASA,EACjBlc,EAAQixB,cAv7VY,YAw7VpBjxB,EAAQkxB,YAv7VU,UAw7VlBlxB,EAAQmxB,WAv7VS,SAy7VjB3wB,OAAOiB,eAAezB,EAAS,cAAgBW,OAAO"} \ No newline at end of file diff --git a/dist/js-data.min.map b/dist/js-data.min.map new file mode 100644 index 00000000..44588a73 --- /dev/null +++ b/dist/js-data.min.map @@ -0,0 +1 @@ +{"version":3,"sources":["dist/js-data.js"],"names":["global","factory","exports","module","define","amd","JSData","this","Settable","_props","Object","defineProperties","_get","value","key","utils","get","_set","_value","set","_unset","unset","Component","opts","call","debug","hasOwnProperty","defineProperty","writable","Query","collection","classCallCheck","data","Relation","relatedMapper","options","arguments","length","undefined","type","constructor","TYPE_NAME","validateOptions","_typeof","fillIn","Record","props","creatingPath","noValidatePath$1","noValidate","keepChangeHistoryPath","keepChangeHistory","mapper","id","idAttribute","validateOnSet","previousPath","toJSON","plainCopy","sort","a","b","hashCode","insertAt","array","index","splice","removeAt","binarySearch","field","lo","hi","compared","mid","found","Index","fieldList","isArray","Error","fieldGetter","isIndex","keys","values","Collection","records","Component$1","isString","queryClass","copy","COLLECTION_DEFAULTS","Query$1","recordId","obj","indexes","isObject","add","Schema","definition","_this2","properties","forOwn","_definition","prop","items","extends","forEach","validationKeyword","i","Mapper","_adapters","datastore","lifecycleMethods","LIFECYCLE_METHODS","recordClass","schema","MAPPER_DEFAULTS","name","err","DOMAIN$6","Schema$1","superClass","Record$1","extend","subClass","methods","addHiddenPropsToTarget","prototype","isPrototypeOf","create","apply","applySchema","Container","_mappers","mapperClass","mapperDefaults","Mapper$1","SimpleStore","SIMPLESTORE_DEFAULTS","collectionClass","Collection$1","_collections","_pendingQueries","_completedQueries","LinkedCollection","_added","DOMAIN$9","DataStore","DATASTORE_DEFAULTS","LinkedCollection$1","SimpleStore$1","Symbol","iterator","enumerable","configurable","toConsumableArray","arr","Array","arr2","from","DOMAIN","INFINITY","MAX_INTEGER","BOOL_TAG","DATE_TAG","FUNC_TAG","NUMBER_TAG","OBJECT_TAG","REGEXP_TAG","STRING_TAG","objToString","toString","PATH","ERRORS","400","_","404","toInteger","sign","remainder","toStr","isPlainObject","mkdirP","object","path","parts","split","Promise","dest","src","isFunction","indexOf","_forRelation","def","fn","thisArg","relationName","relation","containedName","with","_getIndex","localField","withAll","optsCopy","getRelation","slice","_activeWith","substr","list","_relation","target","map","propName","descriptor","getOwnPropertyDescriptor","areDifferent","newObject","oldObject","diff","diffObjects","diffCount","added","removed","changed","classCallCheck$$1","instance","ctor","to","stackFrom","stackTo","blacklist","plain","push","result","isBlacklisted","isDate","Date","getTime","isRegExp","RegExp","source","match","lastIndex","getPrototypeOf","deepFillIn","existing","deepMixIn","equalsFn","ignore","deepEqual","newKeys","filter","oldKeys","oldValue","newValue","equal","domain","code","prefix","message","eventify","getter","setter","_events","emit","events","_len","args","_key","shift","listeners","f","c","all","unshift","off","func","on","classProps","_subClass","_len2","_key2","setPrototypeOf","strictEs6Class","__proto__","findIndex","record","forEachRelation","relationList","len","fromJson","json","JSON","parse","get$$1","last","pop","getSuper","isCtor","__super__","intersection","array1","array2","item","matches","test","isBoolean","isInteger","isNull","isNumber","isSorN","isUndefined","logify","dbg","log","_len3","_key3","concat","level","_len4","_key4","toUpperCase","console","_console","_console2","noDupeAdd","omit","pick","reduce","reject","remove","resolve","set$$1","_path","exec","_equal","toJson","stringify","safeSetProp","safeSetLink","_listeners","DOMAIN$2","INDEX_ERR","reserved","limit","offset","orderBy","skip","where","escapeRegExp","percentRegExp","underscoreRegExp","escape","pattern","replace","_applyWhereFromObject","fields","ops","predicates","clause","==","expr","op","_applyWhereFromArray","_this","groups","_where","prev","parser","group","isOr","_testObjectGroup","keep","first","charAt","evaluate","_testArrayGroup","between","leftKeys","rightKeys","getIndex","compare","cA","cB","temp","predicate","like","query","getData","forEachFn","keyList","getAll","_this3","flags","num","Math","min","mapFn","mapCall","funcName","run","=","===","!=","!==",">",">=","<","<=","isectEmpty","isectNotEmpty","in","_in","notIn","contains","notContains","belongsToType","hasManyType","hasOneType","DOMAIN$4","canAutoAddLinks","relatedCollection","getCollection","related","DOMAIN_ERR","foreignKey","localKey","assignTo","relationFields","canFindLinkFor","getForeignKey","setForeignKey","relatedRecord","_setForeignKey","relatedRecords","getLocalField","setLocalField","relatedData","getInverse","inverse","findInverseRelation","isInversedTo","addLinkedRecords","linkRecord","isEmptyLinks","findExistingLinksFor","removeLinkedRecords","relatedId","unsaved","findExistingLinksByForeignKey","BelongsToRelation","HasManyRelation","localKeys","foreignKeys","hasForeignKeys","ids","findExistingLinksByLocalKeys","findExistingLinksByForeignKeys","HasOneRelation","RelationType","belongsTo","hasMany","hasOne","DOMAIN$3","superMethod","store","bind","_mapper","afterLoadRelations","beforeLoadRelations","changeHistory","changes","commit","destroy","hasChanges","quickHasChanges","isNew","isValid","validate","removeInverseRelation","currentParent","inverseDef","children","child","setupInverseRelation","loadRelations","relations","adapter","getAdapterName","then","tasks","task","raw","load","previous","revert","_this4","preserve","save","_this5","postProcess","changesOnly","silent","_this6","_ret","v","noValidatePath","pos","dataLocation","newIndex","results","order","_i","visitAll","cb","leftInclusive","rightInclusive","_between","leftKey","rightKey","_i2","currKey","peek","clear","insertRecord","removeRecord","isUnique","j","updateRecord","DOMAIN$1","commitOnMerge","emitRecordEvents","onConflict","_onRecordEvent","beforeAdd","singular","existingNoValidate","updateIndexes","createRecord","afterAdd","afterRemove","afterRemoveAll","beforeRemove","beforeRemoveAll","createIndex","instances","_query","prune","removeAll","Ctor","initialValue","idOrRecord","queryOrRecords","updateIndex","DOMAIN$7","types","boolean","integer","null","number","string","segmentToString","segment","str","makePath","segments","makeError","actual","expected","addError","errors","maxLengthCommon","keyword","max","minLengthCommon","validationKeywords","allOf","allErrors","_schema","_validate","anyOf","validated","dependencies","enum","_enum","possibleValues","join","checkingTuple","maximum","exclusiveMaximum","maxItems","maxLength","maxProperties","minimum","exclusiveMinimum","minItems","minLength","minProperties","multipleOf","not","oneOf","additionalProperties","patternProperties","toValidate","undef","origProp","required","existingOnly","prevProp","validType","_type","validator","typeGroupValidators","uniqueItems","runOps","ANY_OPS","ARRAY_OPS","NUMERIC_OPS","OBJECT_OPS","STRING_OPS","validateAny","ctx","shouldPop","changingPath","changedPath","changeHistoryPath","creatingPath$1","eventIdPath","noValidatePath$2","keepChangeHistoryPath$1","silentPath","validationFailureMsg","makeDescriptor","keyPath","unsetter","track","originalGet","error","current","changing","clearTimeout","setTimeout","changeRecord","timestamp","originalSet","numeric","applyDefaults","hasSet","orig","_ret4","_copy","applyDefaultsHooks","validatingHooks","makeNotify","getSchema","toProcess","originalExistingOnly","notify","notify2","count","defaults","destroyAll","find","findAll","sum","update","adapterArgs","beforeAssign","updateAll","updateMany","defaultAdapter","afterCount","afterCreate","afterCreateMany","afterDestroy","afterDestroyAll","afterFind","afterFindAll","afterSum","afterUpdate","afterUpdateAll","afterUpdateMany","beforeCreate","beforeCreateMany","beforeCount","beforeDestroy","beforeDestroyAll","beforeFind","beforeFindAll","beforeSum","beforeUpdate","beforeUpdateAll","beforeUpdateMany","_end","_data","wrap","belongsTo$$1","crud","originalRecord","belongsToRelationData","relationData","relatedIdAttribute","createMany","getAdapter","pass","createdRecordData","_result","createInstance","originalRecords","_records","createdRecordsData","belongsToData","RecordCtor","is","method","config","upper","before","after","_getAdapter","getAdapters","hasMany$$1","hasOne$$1","registerAdapter","default","_this7","_opts","_record","foundErrors","defineRelations","_this8","_name","getMapperByName","getMapper","DOMAIN$5","proxiedMapperMethods","_onMapperEvent","as","original","defineMapper","defineResource","warn","_getMapper","DOMAIN$8","proxiedCollectionMethods","ownMethodsForScoping","cachedFn","hashOrId","cached","usePendingFind","usePendingFindAll","props$2","addToCache","_onCollectionEvent","cachedFind","cachedFindAll","cacheFind","cacheFindAll","hash","self","indexed","hashQuery","eject","ejectAll","pendingQuery","promise","force","_this9","inject","removeRelated","_this10","_this11","_this12","_this13","_getCollection","_addMeta","_clearMeta","event","unlinkOnDestroy","props$1","updateOpts","foreignKeyDescriptor","currentParentId","storeRecord","inverseLocalField","toLink","toLinkIds","currentChildrenOfParent","parents","parent","origGet","origSet","DataStore$1","version","full","major","minor","patch"],"mappings":"CAAC,SAAUA,EAAQC,GACC,gBAAZC,UAA0C,mBAAXC,QAAyBF,EAAQC,SACrD,kBAAXE,SAAyBA,OAAOC,IAAMD,OAAO,WAAY,WAAYH,GAC3EA,EAASD,EAAOM,OAASN,EAAOM,aAChCC,KAAM,SAAWL,GAAW,YAyuD9B,SAASM,YACP,GAAIC,KACJC,QAAOC,iBAAiBJ,MAWtBK,MACEC,MAAO,QAASA,OAAMC,GACpB,MAAOC,GAAMC,IAAIP,EAAQK,KAe7BG,MACEJ,MAAO,QAASA,OAAMC,EAAKI,GACzB,MAAOH,GAAMI,IAAIV,EAAQK,EAAKI,KAalCE,QACEP,MAAO,QAASA,OAAMC,GACpB,MAAOC,GAAMM,MAAMZ,EAAQK,OAiFnC,QAASQ,WAAUC,GACjBf,SAASgB,KAAKjB,MACdgB,IAASA,MAwBThB,KAAKkB,QAAQF,EAAKG,eAAe,YAAaH,EAAKE,MAYnDf,OAAOiB,eAAepB,KAAM,cAAgBM,SAAWe,UAAU,IA6NnE,QAASC,OAAMC,GACbf,EAAMgB,eAAexB,KAAMsB,OAS3BtB,KAAKuB,WAAaA,EASlBvB,KAAKyB,KAAO,KA2iCd,QAASC,UAASC,GAChB,GAAIC,GAAUC,UAAUC,OAAS,GAAsBC,SAAjBF,UAAU,GAAmBA,UAAU,KAE7ErB,GAAMgB,eAAexB,KAAM0B,UAE3BE,EAAQI,KAAOhC,KAAKiC,YAAYC,UAChClC,KAAKmC,gBAAgBR,EAAeC,GAEkD,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644 --- a/package.json +++ b/package.json @@ -56,7 +56,7 @@ "mocha": "mocha --recursive -t 20000 -R dot -r babel-core/register -r babel-polyfill", "cover": "nyc --require babel-core/register --require babel-polyfill --cache mocha --recursive -t 20000 -R dot && nyc report --reporter=html", "test": "npm run build && npm run cover && npm run karma", - "release": "npm test && npm run doc && repo-tools updates && repo-tools changelog && repo-tools authors" + "release": "npm test && repo-tools changelog && repo-tools authors" }, "devDependencies": { "babel-core": "6.26.0",