utils.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. /*!
  2. * Module dependencies.
  3. */
  4. var ObjectId = require('./types/objectid');
  5. var cloneRegExp = require('regexp-clone');
  6. var sliced = require('sliced');
  7. var mpath = require('mpath');
  8. var ms = require('ms');
  9. var MongooseBuffer;
  10. var MongooseArray;
  11. var Document;
  12. /*!
  13. * Produces a collection name from model `name`.
  14. *
  15. * @param {String} name a model name
  16. * @return {String} a collection name
  17. * @api private
  18. */
  19. exports.toCollectionName = function (name, options) {
  20. options = options || {};
  21. if ('system.profile' === name) return name;
  22. if ('system.indexes' === name) return name;
  23. if (options.pluralization === false) return name;
  24. return pluralize(name.toLowerCase());
  25. };
  26. /**
  27. * Pluralization rules.
  28. *
  29. * These rules are applied while processing the argument to `toCollectionName`.
  30. *
  31. * @deprecated remove in 4.x gh-1350
  32. */
  33. exports.pluralization = [
  34. [/(m)an$/gi, '$1en'],
  35. [/(pe)rson$/gi, '$1ople'],
  36. [/(child)$/gi, '$1ren'],
  37. [/^(ox)$/gi, '$1en'],
  38. [/(ax|test)is$/gi, '$1es'],
  39. [/(octop|vir)us$/gi, '$1i'],
  40. [/(alias|status)$/gi, '$1es'],
  41. [/(bu)s$/gi, '$1ses'],
  42. [/(buffal|tomat|potat)o$/gi, '$1oes'],
  43. [/([ti])um$/gi, '$1a'],
  44. [/sis$/gi, 'ses'],
  45. [/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'],
  46. [/(hive)$/gi, '$1s'],
  47. [/([^aeiouy]|qu)y$/gi, '$1ies'],
  48. [/(x|ch|ss|sh)$/gi, '$1es'],
  49. [/(matr|vert|ind)ix|ex$/gi, '$1ices'],
  50. [/([m|l])ouse$/gi, '$1ice'],
  51. [/(kn|w|l)ife$/gi, '$1ives'],
  52. [/(quiz)$/gi, '$1zes'],
  53. [/s$/gi, 's'],
  54. [/([^a-z])$/, '$1'],
  55. [/$/gi, 's']
  56. ];
  57. var rules = exports.pluralization;
  58. /**
  59. * Uncountable words.
  60. *
  61. * These words are applied while processing the argument to `toCollectionName`.
  62. * @api public
  63. */
  64. exports.uncountables = [
  65. 'advice',
  66. 'energy',
  67. 'excretion',
  68. 'digestion',
  69. 'cooperation',
  70. 'health',
  71. 'justice',
  72. 'labour',
  73. 'machinery',
  74. 'equipment',
  75. 'information',
  76. 'pollution',
  77. 'sewage',
  78. 'paper',
  79. 'money',
  80. 'species',
  81. 'series',
  82. 'rain',
  83. 'rice',
  84. 'fish',
  85. 'sheep',
  86. 'moose',
  87. 'deer',
  88. 'news',
  89. 'expertise',
  90. 'status',
  91. 'media'
  92. ];
  93. var uncountables = exports.uncountables;
  94. /*!
  95. * Pluralize function.
  96. *
  97. * @author TJ Holowaychuk (extracted from _ext.js_)
  98. * @param {String} string to pluralize
  99. * @api private
  100. */
  101. function pluralize (str) {
  102. var rule, found;
  103. if (!~uncountables.indexOf(str.toLowerCase())){
  104. found = rules.filter(function(rule){
  105. return str.match(rule[0]);
  106. });
  107. if (found[0]) return str.replace(found[0][0], found[0][1]);
  108. }
  109. return str;
  110. };
  111. /*!
  112. * Determines if `a` and `b` are deep equal.
  113. *
  114. * Modified from node/lib/assert.js
  115. *
  116. * @param {any} a a value to compare to `b`
  117. * @param {any} b a value to compare to `a`
  118. * @return {Boolean}
  119. * @api private
  120. */
  121. exports.deepEqual = function deepEqual (a, b) {
  122. if (a === b) return true;
  123. if (a instanceof Date && b instanceof Date)
  124. return a.getTime() === b.getTime();
  125. if (a instanceof ObjectId && b instanceof ObjectId) {
  126. return a.toString() === b.toString();
  127. }
  128. if (a instanceof RegExp && b instanceof RegExp) {
  129. return a.source == b.source &&
  130. a.ignoreCase == b.ignoreCase &&
  131. a.multiline == b.multiline &&
  132. a.global == b.global;
  133. }
  134. if (typeof a !== 'object' && typeof b !== 'object')
  135. return a == b;
  136. if (a === null || b === null || a === undefined || b === undefined)
  137. return false
  138. if (a.prototype !== b.prototype) return false;
  139. // Handle MongooseNumbers
  140. if (a instanceof Number && b instanceof Number) {
  141. return a.valueOf() === b.valueOf();
  142. }
  143. if (Buffer.isBuffer(a)) {
  144. return exports.buffer.areEqual(a, b);
  145. }
  146. if (isMongooseObject(a)) a = a.toObject();
  147. if (isMongooseObject(b)) b = b.toObject();
  148. try {
  149. var ka = Object.keys(a),
  150. kb = Object.keys(b),
  151. key, i;
  152. } catch (e) {//happens when one is a string literal and the other isn't
  153. return false;
  154. }
  155. // having the same number of owned properties (keys incorporates
  156. // hasOwnProperty)
  157. if (ka.length != kb.length)
  158. return false;
  159. //the same set of keys (although not necessarily the same order),
  160. ka.sort();
  161. kb.sort();
  162. //~~~cheap key test
  163. for (i = ka.length - 1; i >= 0; i--) {
  164. if (ka[i] != kb[i])
  165. return false;
  166. }
  167. //equivalent values for every corresponding key, and
  168. //~~~possibly expensive deep test
  169. for (i = ka.length - 1; i >= 0; i--) {
  170. key = ka[i];
  171. if (!deepEqual(a[key], b[key])) return false;
  172. }
  173. return true;
  174. };
  175. /*!
  176. * Object clone with Mongoose natives support.
  177. *
  178. * 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.
  179. *
  180. * Functions are never cloned.
  181. *
  182. * @param {Object} obj the object to clone
  183. * @param {Object} options
  184. * @return {Object} the cloned object
  185. * @api private
  186. */
  187. exports.clone = function clone (obj, options) {
  188. if (obj === undefined || obj === null)
  189. return obj;
  190. if (Array.isArray(obj))
  191. return cloneArray(obj, options);
  192. if (isMongooseObject(obj)) {
  193. if (options && options.json && 'function' === typeof obj.toJSON) {
  194. return obj.toJSON(options);
  195. } else {
  196. return obj.toObject(options);
  197. }
  198. }
  199. if (obj.constructor) {
  200. switch (exports.getFunctionName(obj.constructor)) {
  201. case 'Object':
  202. return cloneObject(obj, options);
  203. case 'Date':
  204. return new obj.constructor(+obj);
  205. case 'RegExp':
  206. return cloneRegExp(obj);
  207. default:
  208. // ignore
  209. break;
  210. }
  211. }
  212. if (obj instanceof ObjectId)
  213. return new ObjectId(obj.id);
  214. if (!obj.constructor && exports.isObject(obj)) {
  215. // object created with Object.create(null)
  216. return cloneObject(obj, options);
  217. }
  218. if (obj.valueOf)
  219. return obj.valueOf();
  220. };
  221. var clone = exports.clone;
  222. /*!
  223. * ignore
  224. */
  225. function cloneObject (obj, options) {
  226. var retainKeyOrder = options && options.retainKeyOrder
  227. , minimize = options && options.minimize
  228. , ret = {}
  229. , hasKeys
  230. , keys
  231. , val
  232. , k
  233. , i
  234. if (retainKeyOrder) {
  235. for (k in obj) {
  236. val = clone(obj[k], options);
  237. if (!minimize || ('undefined' !== typeof val)) {
  238. hasKeys || (hasKeys = true);
  239. ret[k] = val;
  240. }
  241. }
  242. } else {
  243. // faster
  244. keys = Object.keys(obj);
  245. i = keys.length;
  246. while (i--) {
  247. k = keys[i];
  248. val = clone(obj[k], options);
  249. if (!minimize || ('undefined' !== typeof val)) {
  250. if (!hasKeys) hasKeys = true;
  251. ret[k] = val;
  252. }
  253. }
  254. }
  255. return minimize
  256. ? hasKeys && ret
  257. : ret;
  258. };
  259. function cloneArray (arr, options) {
  260. var ret = [];
  261. for (var i = 0, l = arr.length; i < l; i++)
  262. ret.push(clone(arr[i], options));
  263. return ret;
  264. };
  265. /*!
  266. * Shallow copies defaults into options.
  267. *
  268. * @param {Object} defaults
  269. * @param {Object} options
  270. * @return {Object} the merged object
  271. * @api private
  272. */
  273. exports.options = function (defaults, options) {
  274. var keys = Object.keys(defaults)
  275. , i = keys.length
  276. , k ;
  277. options = options || {};
  278. while (i--) {
  279. k = keys[i];
  280. if (!(k in options)) {
  281. options[k] = defaults[k];
  282. }
  283. }
  284. return options;
  285. };
  286. /*!
  287. * Generates a random string
  288. *
  289. * @api private
  290. */
  291. exports.random = function () {
  292. return Math.random().toString().substr(3);
  293. };
  294. /*!
  295. * Merges `from` into `to` without overwriting existing properties.
  296. *
  297. * @param {Object} to
  298. * @param {Object} from
  299. * @api private
  300. */
  301. exports.merge = function merge (to, from) {
  302. var keys = Object.keys(from)
  303. , i = keys.length
  304. , key;
  305. while (i--) {
  306. key = keys[i];
  307. if ('undefined' === typeof to[key]) {
  308. to[key] = from[key];
  309. } else if (exports.isObject(from[key])) {
  310. merge(to[key], from[key]);
  311. }
  312. }
  313. };
  314. /*!
  315. * toString helper
  316. */
  317. var toString = Object.prototype.toString;
  318. /*!
  319. * Determines if `arg` is an object.
  320. *
  321. * @param {Object|Array|String|Function|RegExp|any} arg
  322. * @api private
  323. * @return {Boolean}
  324. */
  325. exports.isObject = function (arg) {
  326. return '[object Object]' == toString.call(arg);
  327. }
  328. /*!
  329. * A faster Array.prototype.slice.call(arguments) alternative
  330. * @api private
  331. */
  332. exports.args = sliced;
  333. /*!
  334. * process.nextTick helper.
  335. *
  336. * Wraps `callback` in a try/catch + nextTick.
  337. *
  338. * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback.
  339. *
  340. * @param {Function} callback
  341. * @api private
  342. */
  343. exports.tick = function tick (callback) {
  344. if ('function' !== typeof callback) return;
  345. return function () {
  346. try {
  347. callback.apply(this, arguments);
  348. } catch (err) {
  349. // only nextTick on err to get out of
  350. // the event loop and avoid state corruption.
  351. process.nextTick(function () {
  352. throw err;
  353. });
  354. }
  355. }
  356. }
  357. /*!
  358. * Returns if `v` is a mongoose object that has a `toObject()` method we can use.
  359. *
  360. * This is for compatibility with libs like Date.js which do foolish things to Natives.
  361. *
  362. * @param {any} v
  363. * @api private
  364. */
  365. exports.isMongooseObject = function (v) {
  366. Document || (Document = require('./document'));
  367. MongooseArray || (MongooseArray = require('./types').Array);
  368. MongooseBuffer || (MongooseBuffer = require('./types').Buffer);
  369. return v instanceof Document ||
  370. (v && v.isMongooseArray) ||
  371. (v && v.isMongooseBuffer);
  372. };
  373. var isMongooseObject = exports.isMongooseObject;
  374. /*!
  375. * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB.
  376. *
  377. * @param {Object} object
  378. * @api private
  379. */
  380. exports.expires = function expires (object) {
  381. if (!(object && 'Object' == object.constructor.name)) return;
  382. if (!('expires' in object)) return;
  383. var when;
  384. if ('string' != typeof object.expires) {
  385. when = object.expires;
  386. } else {
  387. when = Math.round(ms(object.expires) / 1000);
  388. }
  389. object.expireAfterSeconds = when;
  390. delete object.expires;
  391. };
  392. /*!
  393. * Populate options constructor
  394. */
  395. function PopulateOptions (path, select, match, options, model) {
  396. this.path = path;
  397. this.match = match;
  398. this.select = select;
  399. this.options = options;
  400. this.model = model;
  401. this._docs = {};
  402. }
  403. // make it compatible with utils.clone
  404. PopulateOptions.prototype.constructor = Object;
  405. // expose
  406. exports.PopulateOptions = PopulateOptions;
  407. /*!
  408. * populate helper
  409. */
  410. exports.populate = function populate (path, select, model, match, options) {
  411. // The order of select/conditions args is opposite Model.find but
  412. // necessary to keep backward compatibility (select could be
  413. // an array, string, or object literal).
  414. // might have passed an object specifying all arguments
  415. if (1 === arguments.length) {
  416. if (path instanceof PopulateOptions) {
  417. return [path];
  418. }
  419. if (Array.isArray(path)) {
  420. return path.map(function(o){
  421. return exports.populate(o)[0];
  422. });
  423. }
  424. if (exports.isObject(path)) {
  425. match = path.match;
  426. options = path.options;
  427. select = path.select;
  428. model = path.model;
  429. path = path.path;
  430. }
  431. } else if ('string' !== typeof model && 'function' !== typeof model) {
  432. options = match;
  433. match = model;
  434. model = undefined;
  435. }
  436. if ('string' != typeof path) {
  437. throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`');
  438. }
  439. var ret = [];
  440. var paths = path.split(' ');
  441. for (var i = 0; i < paths.length; ++i) {
  442. ret.push(new PopulateOptions(paths[i], select, match, options, model));
  443. }
  444. return ret;
  445. }
  446. /*!
  447. * Return the value of `obj` at the given `path`.
  448. *
  449. * @param {String} path
  450. * @param {Object} obj
  451. */
  452. exports.getValue = function (path, obj, map) {
  453. return mpath.get(path, obj, '_doc', map);
  454. }
  455. /*!
  456. * Sets the value of `obj` at the given `path`.
  457. *
  458. * @param {String} path
  459. * @param {Anything} val
  460. * @param {Object} obj
  461. */
  462. exports.setValue = function (path, val, obj, map) {
  463. mpath.set(path, val, obj, '_doc', map);
  464. }
  465. /*!
  466. * Returns an array of values from object `o`.
  467. *
  468. * @param {Object} o
  469. * @return {Array}
  470. * @private
  471. */
  472. exports.object = {};
  473. exports.object.vals = function vals (o) {
  474. var keys = Object.keys(o)
  475. , i = keys.length
  476. , ret = [];
  477. while (i--) {
  478. ret.push(o[keys[i]]);
  479. }
  480. return ret;
  481. }
  482. /*!
  483. * @see exports.options
  484. */
  485. exports.object.shallowCopy = exports.options;
  486. /*!
  487. * Safer helper for hasOwnProperty checks
  488. *
  489. * @param {Object} obj
  490. * @param {String} prop
  491. */
  492. var hop = Object.prototype.hasOwnProperty;
  493. exports.object.hasOwnProperty = function (obj, prop) {
  494. return hop.call(obj, prop);
  495. }
  496. /*!
  497. * Determine if `val` is null or undefined
  498. *
  499. * @return {Boolean}
  500. */
  501. exports.isNullOrUndefined = function (val) {
  502. return null == val
  503. }
  504. /*!
  505. * ignore
  506. */
  507. exports.array = {};
  508. /*!
  509. * Flattens an array.
  510. *
  511. * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4]
  512. *
  513. * @param {Array} arr
  514. * @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.
  515. * @return {Array}
  516. * @private
  517. */
  518. exports.array.flatten = function flatten (arr, filter, ret) {
  519. ret || (ret = []);
  520. arr.forEach(function (item) {
  521. if (Array.isArray(item)) {
  522. flatten(item, filter, ret);
  523. } else {
  524. if (!filter || filter(item)) {
  525. ret.push(item);
  526. }
  527. }
  528. });
  529. return ret;
  530. };
  531. /*!
  532. * Removes duplicate values from an array
  533. *
  534. * [1, 2, 3, 3, 5] => [1, 2, 3, 5]
  535. * [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ]
  536. * => [ObjectId("550988ba0c19d57f697dc45e")]
  537. *
  538. * @param {Array} arr
  539. * @return {Array}
  540. * @private
  541. */
  542. exports.array.unique = function(arr) {
  543. var primitives = {};
  544. var ids = {};
  545. var ret = [];
  546. var length = arr.length;
  547. for (var i = 0; i < length; ++i) {
  548. if (typeof arr[i] === 'number' || typeof arr[i] === 'string') {
  549. if (primitives[arr[i]]) {
  550. continue;
  551. }
  552. ret.push(arr[i]);
  553. primitives[arr[i]] = true;
  554. } else if (arr[i] instanceof ObjectId) {
  555. if (ids[arr[i].toString()]) {
  556. continue;
  557. }
  558. ret.push(arr[i]);
  559. ids[arr[i].toString()] = true;
  560. } else {
  561. ret.push(arr[i]);
  562. }
  563. }
  564. return ret;
  565. };
  566. /*!
  567. * Determines if two buffers are equal.
  568. *
  569. * @param {Buffer} a
  570. * @param {Object} b
  571. */
  572. exports.buffer = {};
  573. exports.buffer.areEqual = function (a, b) {
  574. if (!Buffer.isBuffer(a)) return false;
  575. if (!Buffer.isBuffer(b)) return false;
  576. if (a.length !== b.length) return false;
  577. for (var i = 0, len = a.length; i < len; ++i) {
  578. if (a[i] !== b[i]) return false;
  579. }
  580. return true;
  581. };
  582. exports.getFunctionName = function(fn) {
  583. if (fn.name) {
  584. return fn.name;
  585. }
  586. return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1];
  587. };
  588. exports.decorate = function(destination, source) {
  589. for (var key in source) {
  590. destination[key] = source[key];
  591. }
  592. };
  593. /**
  594. * merges to with a copy of from
  595. *
  596. * @param {Object} to
  597. * @param {Object} from
  598. * @api private
  599. */
  600. exports.mergeClone = function(to, from) {
  601. var keys = Object.keys(from)
  602. , i = keys.length
  603. , key
  604. while (i--) {
  605. key = keys[i];
  606. if ('undefined' === typeof to[key]) {
  607. // make sure to retain key order here because of a bug handling the $each
  608. // operator in mongodb 2.4.4
  609. to[key] = exports.clone(from[key], { retainKeyOrder : 1});
  610. } else {
  611. if (exports.isObject(from[key])) {
  612. exports.mergeClone(to[key], from[key]);
  613. } else {
  614. // make sure to retain key order here because of a bug handling the
  615. // $each operator in mongodb 2.4.4
  616. to[key] = exports.clone(from[key], { retainKeyOrder : 1});
  617. }
  618. }
  619. }
  620. };
  621. /**
  622. * Executes a function on each element of an array (like _.each)
  623. *
  624. * @param {Array} arr
  625. * @param {Function} fn
  626. * @api private
  627. */
  628. exports.each = function(arr, fn) {
  629. for (var i = 0; i < arr.length; ++i) {
  630. fn(arr[i]);
  631. }
  632. };