/node_modules/mongoose/lib/utils.js

https://bitbucket.org/coleman333/smartsite · JavaScript · 843 lines · 506 code · 124 blank · 213 comment · 147 complexity · e5291d054522d99199932e1107fff01f MD5 · raw file

  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. const Decimal = require('./types/decimal128');
  6. const ObjectId = require('./types/objectid');
  7. const PromiseProvider = require('./promise_provider');
  8. const cloneRegExp = require('regexp-clone');
  9. const sliced = require('sliced');
  10. const mpath = require('mpath');
  11. const ms = require('ms');
  12. let MongooseBuffer;
  13. let MongooseArray;
  14. let Document;
  15. /*!
  16. * Produces a collection name from model `name`. By default, just returns
  17. * the model name
  18. *
  19. * @param {String} name a model name
  20. * @param {Function} pluralize function that pluralizes the collection name
  21. * @return {String} a collection name
  22. * @api private
  23. */
  24. exports.toCollectionName = function(name, pluralize) {
  25. if (name === 'system.profile') {
  26. return name;
  27. }
  28. if (name === 'system.indexes') {
  29. return name;
  30. }
  31. if (typeof pluralize === 'function') {
  32. return pluralize(name);
  33. }
  34. return name;
  35. };
  36. /*!
  37. * Determines if `a` and `b` are deep equal.
  38. *
  39. * Modified from node/lib/assert.js
  40. *
  41. * @param {any} a a value to compare to `b`
  42. * @param {any} b a value to compare to `a`
  43. * @return {Boolean}
  44. * @api private
  45. */
  46. exports.deepEqual = function deepEqual(a, b) {
  47. if (a === b) {
  48. return true;
  49. }
  50. if (a instanceof Date && b instanceof Date) {
  51. return a.getTime() === b.getTime();
  52. }
  53. if ((a instanceof ObjectId && b instanceof ObjectId) ||
  54. (a instanceof Decimal && b instanceof Decimal)) {
  55. return a.toString() === b.toString();
  56. }
  57. if (a instanceof RegExp && b instanceof RegExp) {
  58. return a.source === b.source &&
  59. a.ignoreCase === b.ignoreCase &&
  60. a.multiline === b.multiline &&
  61. a.global === b.global;
  62. }
  63. if (typeof a !== 'object' && typeof b !== 'object') {
  64. return a == b;
  65. }
  66. if (a === null || b === null || a === undefined || b === undefined) {
  67. return false;
  68. }
  69. if (a.prototype !== b.prototype) {
  70. return false;
  71. }
  72. // Handle MongooseNumbers
  73. if (a instanceof Number && b instanceof Number) {
  74. return a.valueOf() === b.valueOf();
  75. }
  76. if (Buffer.isBuffer(a)) {
  77. return exports.buffer.areEqual(a, b);
  78. }
  79. if (isMongooseObject(a)) {
  80. a = a.toObject();
  81. }
  82. if (isMongooseObject(b)) {
  83. b = b.toObject();
  84. }
  85. try {
  86. var ka = Object.keys(a),
  87. kb = Object.keys(b),
  88. key, i;
  89. } catch (e) {
  90. // happens when one is a string literal and the other isn't
  91. return false;
  92. }
  93. // having the same number of owned properties (keys incorporates
  94. // hasOwnProperty)
  95. if (ka.length !== kb.length) {
  96. return false;
  97. }
  98. // the same set of keys (although not necessarily the same order),
  99. ka.sort();
  100. kb.sort();
  101. // ~~~cheap key test
  102. for (i = ka.length - 1; i >= 0; i--) {
  103. if (ka[i] !== kb[i]) {
  104. return false;
  105. }
  106. }
  107. // equivalent values for every corresponding key, and
  108. // ~~~possibly expensive deep test
  109. for (i = ka.length - 1; i >= 0; i--) {
  110. key = ka[i];
  111. if (!deepEqual(a[key], b[key])) {
  112. return false;
  113. }
  114. }
  115. return true;
  116. };
  117. /*!
  118. * Object clone with Mongoose natives support.
  119. *
  120. * If options.minimize is true, creates a minimal data object. Empty objects and undefined values will not be cloned. This makes the data payload sent to MongoDB as small as possible.
  121. *
  122. * Functions are never cloned.
  123. *
  124. * @param {Object} obj the object to clone
  125. * @param {Object} options
  126. * @return {Object} the cloned object
  127. * @api private
  128. */
  129. exports.clone = function clone(obj, options) {
  130. if (obj === undefined || obj === null) {
  131. return obj;
  132. }
  133. if (Array.isArray(obj)) {
  134. return cloneArray(obj, options);
  135. }
  136. if (isMongooseObject(obj)) {
  137. if (options && options.json && typeof obj.toJSON === 'function') {
  138. return obj.toJSON(options);
  139. }
  140. return obj.toObject(options);
  141. }
  142. if (obj.constructor) {
  143. switch (exports.getFunctionName(obj.constructor)) {
  144. case 'Object':
  145. return cloneObject(obj, options);
  146. case 'Date':
  147. return new obj.constructor(+obj);
  148. case 'RegExp':
  149. return cloneRegExp(obj);
  150. default:
  151. // ignore
  152. break;
  153. }
  154. }
  155. if (obj instanceof ObjectId) {
  156. return new ObjectId(obj.id);
  157. }
  158. if (obj instanceof Decimal) {
  159. if (options && options.flattenDecimals) {
  160. return obj.toJSON();
  161. }
  162. return Decimal.fromString(obj.toString());
  163. }
  164. if (!obj.constructor && exports.isObject(obj)) {
  165. // object created with Object.create(null)
  166. return cloneObject(obj, options);
  167. }
  168. if (obj.valueOf) {
  169. return obj.valueOf();
  170. }
  171. };
  172. var clone = exports.clone;
  173. /*!
  174. * ignore
  175. */
  176. exports.promiseOrCallback = function promiseOrCallback(callback, fn) {
  177. if (typeof callback === 'function') {
  178. try {
  179. return fn(callback);
  180. } catch (error) {
  181. return process.nextTick(() => {
  182. throw error;
  183. });
  184. }
  185. }
  186. const Promise = PromiseProvider.get();
  187. return new Promise((resolve, reject) => {
  188. fn(function(error, res) {
  189. if (error != null) {
  190. return reject(error);
  191. }
  192. if (arguments.length > 2) {
  193. return resolve(Array.prototype.slice.call(arguments, 1));
  194. }
  195. resolve(res);
  196. });
  197. });
  198. };
  199. /*!
  200. * ignore
  201. */
  202. function cloneObject(obj, options) {
  203. const minimize = options && options.minimize;
  204. const ret = {};
  205. let hasKeys;
  206. let val;
  207. let k;
  208. for (k in obj) {
  209. val = clone(obj[k], options);
  210. if (!minimize || (typeof val !== 'undefined')) {
  211. hasKeys || (hasKeys = true);
  212. ret[k] = val;
  213. }
  214. }
  215. return minimize ? hasKeys && ret : ret;
  216. }
  217. function cloneArray(arr, options) {
  218. var ret = [];
  219. for (var i = 0, l = arr.length; i < l; i++) {
  220. ret.push(clone(arr[i], options));
  221. }
  222. return ret;
  223. }
  224. /*!
  225. * Shallow copies defaults into options.
  226. *
  227. * @param {Object} defaults
  228. * @param {Object} options
  229. * @return {Object} the merged object
  230. * @api private
  231. */
  232. exports.options = function(defaults, options) {
  233. var keys = Object.keys(defaults),
  234. i = keys.length,
  235. k;
  236. options = options || {};
  237. while (i--) {
  238. k = keys[i];
  239. if (!(k in options)) {
  240. options[k] = defaults[k];
  241. }
  242. }
  243. return options;
  244. };
  245. /*!
  246. * Generates a random string
  247. *
  248. * @api private
  249. */
  250. exports.random = function() {
  251. return Math.random().toString().substr(3);
  252. };
  253. /*!
  254. * Merges `from` into `to` without overwriting existing properties.
  255. *
  256. * @param {Object} to
  257. * @param {Object} from
  258. * @api private
  259. */
  260. exports.merge = function merge(to, from, options, path) {
  261. options = options || {};
  262. const keys = Object.keys(from);
  263. let i = 0;
  264. const len = keys.length;
  265. let key;
  266. path = path || '';
  267. const omitNested = options.omitNested || {};
  268. while (i < len) {
  269. key = keys[i++];
  270. if (options.omit && options.omit[key]) {
  271. continue;
  272. }
  273. if (omitNested[path]) {
  274. continue;
  275. }
  276. if (to[key] == null) {
  277. to[key] = from[key];
  278. } else if (exports.isObject(from[key])) {
  279. if (!exports.isObject(to[key])) {
  280. to[key] = {};
  281. }
  282. merge(to[key], from[key], options, path ? path + '.' + key : key);
  283. } else if (options.overwrite) {
  284. to[key] = from[key];
  285. }
  286. }
  287. };
  288. /*!
  289. * Applies toObject recursively.
  290. *
  291. * @param {Document|Array|Object} obj
  292. * @return {Object}
  293. * @api private
  294. */
  295. exports.toObject = function toObject(obj) {
  296. Document || (Document = require('./document'));
  297. var ret;
  298. if (obj == null) {
  299. return obj;
  300. }
  301. if (obj instanceof Document) {
  302. return obj.toObject();
  303. }
  304. if (Array.isArray(obj)) {
  305. ret = [];
  306. for (var i = 0, len = obj.length; i < len; ++i) {
  307. ret.push(toObject(obj[i]));
  308. }
  309. return ret;
  310. }
  311. if ((obj.constructor && exports.getFunctionName(obj.constructor) === 'Object') ||
  312. (!obj.constructor && exports.isObject(obj))) {
  313. ret = {};
  314. for (var k in obj) {
  315. ret[k] = toObject(obj[k]);
  316. }
  317. return ret;
  318. }
  319. return obj;
  320. };
  321. /*!
  322. * Determines if `arg` is an object.
  323. *
  324. * @param {Object|Array|String|Function|RegExp|any} arg
  325. * @api private
  326. * @return {Boolean}
  327. */
  328. exports.isObject = function(arg) {
  329. if (Buffer.isBuffer(arg)) {
  330. return true;
  331. }
  332. return Object.prototype.toString.call(arg) === '[object Object]';
  333. };
  334. /*!
  335. * A faster Array.prototype.slice.call(arguments) alternative
  336. * @api private
  337. */
  338. exports.args = sliced;
  339. /*!
  340. * process.nextTick helper.
  341. *
  342. * Wraps `callback` in a try/catch + nextTick.
  343. *
  344. * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback.
  345. *
  346. * @param {Function} callback
  347. * @api private
  348. */
  349. exports.tick = function tick(callback) {
  350. if (typeof callback !== 'function') {
  351. return;
  352. }
  353. return function() {
  354. try {
  355. callback.apply(this, arguments);
  356. } catch (err) {
  357. // only nextTick on err to get out of
  358. // the event loop and avoid state corruption.
  359. process.nextTick(function() {
  360. throw err;
  361. });
  362. }
  363. };
  364. };
  365. /*!
  366. * Returns if `v` is a mongoose object that has a `toObject()` method we can use.
  367. *
  368. * This is for compatibility with libs like Date.js which do foolish things to Natives.
  369. *
  370. * @param {any} v
  371. * @api private
  372. */
  373. exports.isMongooseObject = function(v) {
  374. Document || (Document = require('./document'));
  375. MongooseArray || (MongooseArray = require('./types').Array);
  376. MongooseBuffer || (MongooseBuffer = require('./types').Buffer);
  377. return v instanceof Document ||
  378. (v && v.isMongooseArray) ||
  379. (v && v.isMongooseBuffer);
  380. };
  381. var isMongooseObject = exports.isMongooseObject;
  382. /*!
  383. * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB.
  384. *
  385. * @param {Object} object
  386. * @api private
  387. */
  388. exports.expires = function expires(object) {
  389. if (!(object && object.constructor.name === 'Object')) {
  390. return;
  391. }
  392. if (!('expires' in object)) {
  393. return;
  394. }
  395. var when;
  396. if (typeof object.expires !== 'string') {
  397. when = object.expires;
  398. } else {
  399. when = Math.round(ms(object.expires) / 1000);
  400. }
  401. object.expireAfterSeconds = when;
  402. delete object.expires;
  403. };
  404. /*!
  405. * Populate options constructor
  406. */
  407. function PopulateOptions(path, select, match, options, model, subPopulate) {
  408. this.path = path;
  409. this.match = match;
  410. this.select = select;
  411. this.options = options;
  412. this.model = model;
  413. if (typeof subPopulate === 'object') {
  414. this.populate = subPopulate;
  415. }
  416. this._docs = {};
  417. }
  418. // make it compatible with utils.clone
  419. PopulateOptions.prototype.constructor = Object;
  420. // expose
  421. exports.PopulateOptions = PopulateOptions;
  422. /*!
  423. * populate helper
  424. */
  425. exports.populate = function populate(path, select, model, match, options, subPopulate) {
  426. // The order of select/conditions args is opposite Model.find but
  427. // necessary to keep backward compatibility (select could be
  428. // an array, string, or object literal).
  429. // might have passed an object specifying all arguments
  430. if (arguments.length === 1) {
  431. if (path instanceof PopulateOptions) {
  432. return [path];
  433. }
  434. if (Array.isArray(path)) {
  435. return path.map(function(o) {
  436. return exports.populate(o)[0];
  437. });
  438. }
  439. if (exports.isObject(path)) {
  440. match = path.match;
  441. options = path.options;
  442. select = path.select;
  443. model = path.model;
  444. subPopulate = path.populate;
  445. path = path.path;
  446. }
  447. } else if (typeof model !== 'string' && typeof model !== 'function') {
  448. options = match;
  449. match = model;
  450. model = undefined;
  451. }
  452. if (typeof path !== 'string') {
  453. throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`');
  454. }
  455. if (Array.isArray(subPopulate)) {
  456. let ret = [];
  457. subPopulate.forEach(function(obj) {
  458. if (/[\s]/.test(obj.path)) {
  459. let copy = Object.assign({}, obj);
  460. let paths = copy.path.split(' ');
  461. paths.forEach(function(p) {
  462. copy.path = p;
  463. ret.push(exports.populate(copy)[0]);
  464. });
  465. } else {
  466. ret.push(exports.populate(obj)[0]);
  467. }
  468. });
  469. subPopulate = exports.populate(ret);
  470. } else if (typeof subPopulate === 'object') {
  471. subPopulate = exports.populate(subPopulate);
  472. }
  473. var ret = [];
  474. var paths = path.split(' ');
  475. options = exports.clone(options);
  476. for (var i = 0; i < paths.length; ++i) {
  477. ret.push(new PopulateOptions(paths[i], select, match, options, model, subPopulate));
  478. }
  479. return ret;
  480. };
  481. /*!
  482. * Return the value of `obj` at the given `path`.
  483. *
  484. * @param {String} path
  485. * @param {Object} obj
  486. */
  487. exports.getValue = function(path, obj, map) {
  488. return mpath.get(path, obj, '_doc', map);
  489. };
  490. /*!
  491. * Sets the value of `obj` at the given `path`.
  492. *
  493. * @param {String} path
  494. * @param {Anything} val
  495. * @param {Object} obj
  496. */
  497. exports.setValue = function(path, val, obj, map, _copying) {
  498. mpath.set(path, val, obj, '_doc', map, _copying);
  499. };
  500. /*!
  501. * Returns an array of values from object `o`.
  502. *
  503. * @param {Object} o
  504. * @return {Array}
  505. * @private
  506. */
  507. exports.object = {};
  508. exports.object.vals = function vals(o) {
  509. var keys = Object.keys(o),
  510. i = keys.length,
  511. ret = [];
  512. while (i--) {
  513. ret.push(o[keys[i]]);
  514. }
  515. return ret;
  516. };
  517. /*!
  518. * @see exports.options
  519. */
  520. exports.object.shallowCopy = exports.options;
  521. /*!
  522. * Safer helper for hasOwnProperty checks
  523. *
  524. * @param {Object} obj
  525. * @param {String} prop
  526. */
  527. var hop = Object.prototype.hasOwnProperty;
  528. exports.object.hasOwnProperty = function(obj, prop) {
  529. return hop.call(obj, prop);
  530. };
  531. /*!
  532. * Determine if `val` is null or undefined
  533. *
  534. * @return {Boolean}
  535. */
  536. exports.isNullOrUndefined = function(val) {
  537. return val === null || val === undefined;
  538. };
  539. /*!
  540. * ignore
  541. */
  542. exports.array = {};
  543. /*!
  544. * Flattens an array.
  545. *
  546. * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4]
  547. *
  548. * @param {Array} arr
  549. * @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsey value, the item will not be included in the results.
  550. * @return {Array}
  551. * @private
  552. */
  553. exports.array.flatten = function flatten(arr, filter, ret) {
  554. ret || (ret = []);
  555. arr.forEach(function(item) {
  556. if (Array.isArray(item)) {
  557. flatten(item, filter, ret);
  558. } else {
  559. if (!filter || filter(item)) {
  560. ret.push(item);
  561. }
  562. }
  563. });
  564. return ret;
  565. };
  566. /*!
  567. * Removes duplicate values from an array
  568. *
  569. * [1, 2, 3, 3, 5] => [1, 2, 3, 5]
  570. * [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ]
  571. * => [ObjectId("550988ba0c19d57f697dc45e")]
  572. *
  573. * @param {Array} arr
  574. * @return {Array}
  575. * @private
  576. */
  577. exports.array.unique = function(arr) {
  578. var primitives = {};
  579. var ids = {};
  580. var ret = [];
  581. var length = arr.length;
  582. for (var i = 0; i < length; ++i) {
  583. if (typeof arr[i] === 'number' || typeof arr[i] === 'string') {
  584. if (primitives[arr[i]]) {
  585. continue;
  586. }
  587. ret.push(arr[i]);
  588. primitives[arr[i]] = true;
  589. } else if (arr[i] instanceof ObjectId) {
  590. if (ids[arr[i].toString()]) {
  591. continue;
  592. }
  593. ret.push(arr[i]);
  594. ids[arr[i].toString()] = true;
  595. } else {
  596. ret.push(arr[i]);
  597. }
  598. }
  599. return ret;
  600. };
  601. /*!
  602. * Determines if two buffers are equal.
  603. *
  604. * @param {Buffer} a
  605. * @param {Object} b
  606. */
  607. exports.buffer = {};
  608. exports.buffer.areEqual = function(a, b) {
  609. if (!Buffer.isBuffer(a)) {
  610. return false;
  611. }
  612. if (!Buffer.isBuffer(b)) {
  613. return false;
  614. }
  615. if (a.length !== b.length) {
  616. return false;
  617. }
  618. for (var i = 0, len = a.length; i < len; ++i) {
  619. if (a[i] !== b[i]) {
  620. return false;
  621. }
  622. }
  623. return true;
  624. };
  625. exports.getFunctionName = function(fn) {
  626. if (fn.name) {
  627. return fn.name;
  628. }
  629. return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1];
  630. };
  631. exports.decorate = function(destination, source) {
  632. for (var key in source) {
  633. destination[key] = source[key];
  634. }
  635. };
  636. /**
  637. * merges to with a copy of from
  638. *
  639. * @param {Object} to
  640. * @param {Object} fromObj
  641. * @api private
  642. */
  643. exports.mergeClone = function(to, fromObj) {
  644. if (isMongooseObject(fromObj)) {
  645. fromObj = fromObj.toObject({
  646. transform: false,
  647. virtuals: false,
  648. depopulate: true,
  649. getters: false,
  650. flattenDecimals: false
  651. });
  652. }
  653. var keys = Object.keys(fromObj);
  654. var len = keys.length;
  655. var i = 0;
  656. var key;
  657. while (i < len) {
  658. key = keys[i++];
  659. if (typeof to[key] === 'undefined') {
  660. to[key] = exports.clone(fromObj[key], {
  661. transform: false,
  662. virtuals: false,
  663. depopulate: true,
  664. getters: false,
  665. flattenDecimals: false
  666. });
  667. } else {
  668. var val = fromObj[key];
  669. if (val != null && val.valueOf && !(val instanceof Date)) {
  670. val = val.valueOf();
  671. }
  672. if (exports.isObject(val)) {
  673. var obj = val;
  674. if (isMongooseObject(val) && !val.isMongooseBuffer) {
  675. obj = obj.toObject({
  676. transform: false,
  677. virtuals: false,
  678. depopulate: true,
  679. getters: false,
  680. flattenDecimals: false
  681. });
  682. }
  683. if (val.isMongooseBuffer) {
  684. obj = new Buffer(obj);
  685. }
  686. exports.mergeClone(to[key], obj);
  687. } else {
  688. to[key] = exports.clone(val, {
  689. flattenDecimals: false
  690. });
  691. }
  692. }
  693. }
  694. };
  695. /**
  696. * Executes a function on each element of an array (like _.each)
  697. *
  698. * @param {Array} arr
  699. * @param {Function} fn
  700. * @api private
  701. */
  702. exports.each = function(arr, fn) {
  703. for (var i = 0; i < arr.length; ++i) {
  704. fn(arr[i]);
  705. }
  706. };
  707. /*!
  708. * Centralize this so we can more easily work around issues with people
  709. * stubbing out `process.nextTick()` in tests using sinon:
  710. * https://github.com/sinonjs/lolex#automatically-incrementing-mocked-time
  711. * See gh-6074
  712. */
  713. exports.immediate = function immediate(cb) {
  714. return process.nextTick(cb);
  715. };
  716. /*!
  717. * ignore
  718. */
  719. exports.noop = function() {};