utils.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  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 get = require('./helpers/get');
  10. const sliced = require('sliced');
  11. const mpath = require('mpath');
  12. const ms = require('ms');
  13. const Buffer = require('safe-buffer').Buffer;
  14. const emittedSymbol = Symbol.for('mongoose:emitted');
  15. let MongooseBuffer;
  16. let MongooseArray;
  17. let Document;
  18. const specialProperties = new Set(['__proto__', 'constructor', 'prototype']);
  19. exports.specialProperties = specialProperties;
  20. /*!
  21. * Produces a collection name from model `name`. By default, just returns
  22. * the model name
  23. *
  24. * @param {String} name a model name
  25. * @param {Function} pluralize function that pluralizes the collection name
  26. * @return {String} a collection name
  27. * @api private
  28. */
  29. exports.toCollectionName = function(name, pluralize) {
  30. if (name === 'system.profile') {
  31. return name;
  32. }
  33. if (name === 'system.indexes') {
  34. return name;
  35. }
  36. if (typeof pluralize === 'function') {
  37. return pluralize(name);
  38. }
  39. return name;
  40. };
  41. /*!
  42. * Determines if `a` and `b` are deep equal.
  43. *
  44. * Modified from node/lib/assert.js
  45. *
  46. * @param {any} a a value to compare to `b`
  47. * @param {any} b a value to compare to `a`
  48. * @return {Boolean}
  49. * @api private
  50. */
  51. exports.deepEqual = function deepEqual(a, b) {
  52. if (a === b) {
  53. return true;
  54. }
  55. if (a instanceof Date && b instanceof Date) {
  56. return a.getTime() === b.getTime();
  57. }
  58. if ((isBsonType(a, 'ObjectID') && isBsonType(b, 'ObjectID')) ||
  59. (isBsonType(a, 'Decimal128') && isBsonType(b, 'Decimal128'))) {
  60. return a.toString() === b.toString();
  61. }
  62. if (a instanceof RegExp && b instanceof RegExp) {
  63. return a.source === b.source &&
  64. a.ignoreCase === b.ignoreCase &&
  65. a.multiline === b.multiline &&
  66. a.global === b.global;
  67. }
  68. if (typeof a !== 'object' && typeof b !== 'object') {
  69. return a == b;
  70. }
  71. if (a === null || b === null || a === undefined || b === undefined) {
  72. return false;
  73. }
  74. if (a.prototype !== b.prototype) {
  75. return false;
  76. }
  77. // Handle MongooseNumbers
  78. if (a instanceof Number && b instanceof Number) {
  79. return a.valueOf() === b.valueOf();
  80. }
  81. if (Buffer.isBuffer(a)) {
  82. return exports.buffer.areEqual(a, b);
  83. }
  84. if (isMongooseObject(a)) {
  85. a = a.toObject();
  86. }
  87. if (isMongooseObject(b)) {
  88. b = b.toObject();
  89. }
  90. let ka;
  91. let kb;
  92. let key;
  93. let i;
  94. try {
  95. ka = Object.keys(a);
  96. kb = Object.keys(b);
  97. } catch (e) {
  98. // happens when one is a string literal and the other isn't
  99. return false;
  100. }
  101. // having the same number of owned properties (keys incorporates
  102. // hasOwnProperty)
  103. if (ka.length !== kb.length) {
  104. return false;
  105. }
  106. // the same set of keys (although not necessarily the same order),
  107. ka.sort();
  108. kb.sort();
  109. // ~~~cheap key test
  110. for (i = ka.length - 1; i >= 0; i--) {
  111. if (ka[i] !== kb[i]) {
  112. return false;
  113. }
  114. }
  115. // equivalent values for every corresponding key, and
  116. // ~~~possibly expensive deep test
  117. for (i = ka.length - 1; i >= 0; i--) {
  118. key = ka[i];
  119. if (!deepEqual(a[key], b[key])) {
  120. return false;
  121. }
  122. }
  123. return true;
  124. };
  125. /*!
  126. * Get the bson type, if it exists
  127. */
  128. function isBsonType(obj, typename) {
  129. return get(obj, '_bsontype', void 0) === typename;
  130. }
  131. /*!
  132. * Get the last element of an array
  133. */
  134. exports.last = function(arr) {
  135. if (arr.length > 0) {
  136. return arr[arr.length - 1];
  137. }
  138. return void 0;
  139. };
  140. /*!
  141. * Object clone with Mongoose natives support.
  142. *
  143. * 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.
  144. *
  145. * Functions are never cloned.
  146. *
  147. * @param {Object} obj the object to clone
  148. * @param {Object} options
  149. * @param {Boolean} isArrayChild true if cloning immediately underneath an array. Special case for minimize.
  150. * @return {Object} the cloned object
  151. * @api private
  152. */
  153. exports.clone = function clone(obj, options, isArrayChild) {
  154. if (obj == null) {
  155. return obj;
  156. }
  157. if (Array.isArray(obj)) {
  158. return cloneArray(obj, options);
  159. }
  160. if (isMongooseObject(obj)) {
  161. if (options && options.json && typeof obj.toJSON === 'function') {
  162. return obj.toJSON(options);
  163. }
  164. return obj.toObject(options);
  165. }
  166. if (obj.constructor) {
  167. switch (exports.getFunctionName(obj.constructor)) {
  168. case 'Object':
  169. return cloneObject(obj, options, isArrayChild);
  170. case 'Date':
  171. return new obj.constructor(+obj);
  172. case 'RegExp':
  173. return cloneRegExp(obj);
  174. default:
  175. // ignore
  176. break;
  177. }
  178. }
  179. if (obj instanceof ObjectId) {
  180. return new ObjectId(obj.id);
  181. }
  182. if (isBsonType(obj, 'Decimal128')) {
  183. if (options && options.flattenDecimals) {
  184. return obj.toJSON();
  185. }
  186. return Decimal.fromString(obj.toString());
  187. }
  188. if (!obj.constructor && exports.isObject(obj)) {
  189. // object created with Object.create(null)
  190. return cloneObject(obj, options, isArrayChild);
  191. }
  192. if (obj.valueOf) {
  193. return obj.valueOf();
  194. }
  195. return cloneObject(obj, options, isArrayChild);
  196. };
  197. const clone = exports.clone;
  198. /*!
  199. * ignore
  200. */
  201. exports.promiseOrCallback = function promiseOrCallback(callback, fn, ee) {
  202. if (typeof callback === 'function') {
  203. return fn(function(error) {
  204. if (error != null) {
  205. if (ee != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) {
  206. error[emittedSymbol] = true;
  207. ee.emit('error', error);
  208. }
  209. try {
  210. callback(error);
  211. } catch (error) {
  212. return process.nextTick(() => {
  213. throw error;
  214. });
  215. }
  216. return;
  217. }
  218. callback.apply(this, arguments);
  219. });
  220. }
  221. const Promise = PromiseProvider.get();
  222. return new Promise((resolve, reject) => {
  223. fn(function(error, res) {
  224. if (error != null) {
  225. if (ee != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) {
  226. error[emittedSymbol] = true;
  227. ee.emit('error', error);
  228. }
  229. return reject(error);
  230. }
  231. if (arguments.length > 2) {
  232. return resolve(Array.prototype.slice.call(arguments, 1));
  233. }
  234. resolve(res);
  235. });
  236. });
  237. };
  238. /*!
  239. * ignore
  240. */
  241. function cloneObject(obj, options, isArrayChild) {
  242. const minimize = options && options.minimize;
  243. const ret = {};
  244. let hasKeys;
  245. for (const k in obj) {
  246. if (specialProperties.has(k)) {
  247. continue;
  248. }
  249. // Don't pass `isArrayChild` down
  250. const val = clone(obj[k], options);
  251. if (!minimize || (typeof val !== 'undefined')) {
  252. hasKeys || (hasKeys = true);
  253. ret[k] = val;
  254. }
  255. }
  256. return minimize && !isArrayChild ? hasKeys && ret : ret;
  257. }
  258. function cloneArray(arr, options) {
  259. const ret = [];
  260. for (let i = 0, l = arr.length; i < l; i++) {
  261. ret.push(clone(arr[i], options, true));
  262. }
  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. const keys = Object.keys(defaults);
  275. let i = keys.length;
  276. let 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, options, path) {
  302. options = options || {};
  303. const keys = Object.keys(from);
  304. let i = 0;
  305. const len = keys.length;
  306. let key;
  307. path = path || '';
  308. const omitNested = options.omitNested || {};
  309. while (i < len) {
  310. key = keys[i++];
  311. if (options.omit && options.omit[key]) {
  312. continue;
  313. }
  314. if (omitNested[path]) {
  315. continue;
  316. }
  317. if (specialProperties.has(key)) {
  318. continue;
  319. }
  320. if (to[key] == null) {
  321. to[key] = from[key];
  322. } else if (exports.isObject(from[key])) {
  323. if (!exports.isObject(to[key])) {
  324. to[key] = {};
  325. }
  326. if (from[key] != null) {
  327. if (from[key].instanceOfSchema) {
  328. to[key] = from[key].clone();
  329. continue;
  330. } else if (from[key] instanceof ObjectId) {
  331. to[key] = new ObjectId(from[key]);
  332. continue;
  333. }
  334. }
  335. merge(to[key], from[key], options, path ? path + '.' + key : key);
  336. } else if (options.overwrite) {
  337. to[key] = from[key];
  338. }
  339. }
  340. };
  341. /*!
  342. * Applies toObject recursively.
  343. *
  344. * @param {Document|Array|Object} obj
  345. * @return {Object}
  346. * @api private
  347. */
  348. exports.toObject = function toObject(obj) {
  349. Document || (Document = require('./document'));
  350. let ret;
  351. if (obj == null) {
  352. return obj;
  353. }
  354. if (obj instanceof Document) {
  355. return obj.toObject();
  356. }
  357. if (Array.isArray(obj)) {
  358. ret = [];
  359. for (let i = 0, len = obj.length; i < len; ++i) {
  360. ret.push(toObject(obj[i]));
  361. }
  362. return ret;
  363. }
  364. if (exports.isPOJO(obj)) {
  365. ret = {};
  366. for (const k in obj) {
  367. if (specialProperties.has(k)) {
  368. continue;
  369. }
  370. ret[k] = toObject(obj[k]);
  371. }
  372. return ret;
  373. }
  374. return obj;
  375. };
  376. /*!
  377. * Determines if `arg` is an object.
  378. *
  379. * @param {Object|Array|String|Function|RegExp|any} arg
  380. * @api private
  381. * @return {Boolean}
  382. */
  383. exports.isObject = function(arg) {
  384. if (Buffer.isBuffer(arg)) {
  385. return true;
  386. }
  387. return Object.prototype.toString.call(arg) === '[object Object]';
  388. };
  389. /*!
  390. * Determines if `arg` is a plain old JavaScript object (POJO). Specifically,
  391. * `arg` must be an object but not an instance of any special class, like String,
  392. * ObjectId, etc.
  393. *
  394. * `Object.getPrototypeOf()` is part of ES5: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf
  395. *
  396. * @param {Object|Array|String|Function|RegExp|any} arg
  397. * @api private
  398. * @return {Boolean}
  399. */
  400. exports.isPOJO = function(arg) {
  401. if (arg == null || typeof arg !== 'object') {
  402. return false;
  403. }
  404. const proto = Object.getPrototypeOf(arg);
  405. // Prototype may be null if you used `Object.create(null)`
  406. // Checking `proto`'s constructor is safe because `getPrototypeOf()`
  407. // explicitly crosses the boundary from object data to object metadata
  408. return !proto || proto.constructor.name === 'Object';
  409. };
  410. /*!
  411. * A faster Array.prototype.slice.call(arguments) alternative
  412. * @api private
  413. */
  414. exports.args = sliced;
  415. /*!
  416. * process.nextTick helper.
  417. *
  418. * Wraps `callback` in a try/catch + nextTick.
  419. *
  420. * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback.
  421. *
  422. * @param {Function} callback
  423. * @api private
  424. */
  425. exports.tick = function tick(callback) {
  426. if (typeof callback !== 'function') {
  427. return;
  428. }
  429. return function() {
  430. try {
  431. callback.apply(this, arguments);
  432. } catch (err) {
  433. // only nextTick on err to get out of
  434. // the event loop and avoid state corruption.
  435. process.nextTick(function() {
  436. throw err;
  437. });
  438. }
  439. };
  440. };
  441. /*!
  442. * Returns if `v` is a mongoose object that has a `toObject()` method we can use.
  443. *
  444. * This is for compatibility with libs like Date.js which do foolish things to Natives.
  445. *
  446. * @param {any} v
  447. * @api private
  448. */
  449. exports.isMongooseObject = function(v) {
  450. Document || (Document = require('./document'));
  451. MongooseArray || (MongooseArray = require('./types').Array);
  452. MongooseBuffer || (MongooseBuffer = require('./types').Buffer);
  453. if (v == null) {
  454. return false;
  455. }
  456. return v.$__ != null || // Document
  457. v.isMongooseArray || // Array or Document Array
  458. v.isMongooseBuffer || // Buffer
  459. v.$isMongooseMap; // Map
  460. };
  461. const isMongooseObject = exports.isMongooseObject;
  462. /*!
  463. * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB.
  464. *
  465. * @param {Object} object
  466. * @api private
  467. */
  468. exports.expires = function expires(object) {
  469. if (!(object && object.constructor.name === 'Object')) {
  470. return;
  471. }
  472. if (!('expires' in object)) {
  473. return;
  474. }
  475. let when;
  476. if (typeof object.expires !== 'string') {
  477. when = object.expires;
  478. } else {
  479. when = Math.round(ms(object.expires) / 1000);
  480. }
  481. object.expireAfterSeconds = when;
  482. delete object.expires;
  483. };
  484. /*!
  485. * Populate options constructor
  486. */
  487. function PopulateOptions(obj) {
  488. this.path = obj.path;
  489. this.match = obj.match;
  490. this.select = obj.select;
  491. this.options = obj.options;
  492. this.model = obj.model;
  493. if (typeof obj.subPopulate === 'object') {
  494. this.populate = obj.subPopulate;
  495. }
  496. if (obj.justOne != null) {
  497. this.justOne = obj.justOne;
  498. }
  499. if (obj.count != null) {
  500. this.count = obj.count;
  501. }
  502. this._docs = {};
  503. }
  504. // make it compatible with utils.clone
  505. PopulateOptions.prototype.constructor = Object;
  506. // expose
  507. exports.PopulateOptions = PopulateOptions;
  508. /*!
  509. * populate helper
  510. */
  511. exports.populate = function populate(path, select, model, match, options, subPopulate, justOne, count) {
  512. // The order of select/conditions args is opposite Model.find but
  513. // necessary to keep backward compatibility (select could be
  514. // an array, string, or object literal).
  515. function makeSingles(arr) {
  516. const ret = [];
  517. arr.forEach(function(obj) {
  518. if (/[\s]/.test(obj.path)) {
  519. const paths = obj.path.split(' ');
  520. paths.forEach(function(p) {
  521. const copy = Object.assign({}, obj);
  522. copy.path = p;
  523. ret.push(copy);
  524. });
  525. } else {
  526. ret.push(obj);
  527. }
  528. });
  529. return ret;
  530. }
  531. // might have passed an object specifying all arguments
  532. if (arguments.length === 1) {
  533. if (path instanceof PopulateOptions) {
  534. return [path];
  535. }
  536. if (Array.isArray(path)) {
  537. const singles = makeSingles(path);
  538. return singles.map(function(o) {
  539. if (o.populate && !(o.match || o.options)) {
  540. return exports.populate(o)[0];
  541. } else {
  542. return exports.populate(o)[0];
  543. }
  544. });
  545. }
  546. if (exports.isObject(path)) {
  547. match = path.match;
  548. options = path.options;
  549. select = path.select;
  550. model = path.model;
  551. subPopulate = path.populate;
  552. justOne = path.justOne;
  553. path = path.path;
  554. count = path.count;
  555. }
  556. } else if (typeof model === 'object') {
  557. options = match;
  558. match = model;
  559. model = undefined;
  560. }
  561. if (typeof path !== 'string') {
  562. throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`');
  563. }
  564. if (Array.isArray(subPopulate)) {
  565. const ret = [];
  566. subPopulate.forEach(function(obj) {
  567. if (/[\s]/.test(obj.path)) {
  568. const copy = Object.assign({}, obj);
  569. const paths = copy.path.split(' ');
  570. paths.forEach(function(p) {
  571. copy.path = p;
  572. ret.push(exports.populate(copy)[0]);
  573. });
  574. } else {
  575. ret.push(exports.populate(obj)[0]);
  576. }
  577. });
  578. subPopulate = exports.populate(ret);
  579. } else if (typeof subPopulate === 'object') {
  580. subPopulate = exports.populate(subPopulate);
  581. }
  582. const ret = [];
  583. const paths = path.split(' ');
  584. options = exports.clone(options);
  585. for (let i = 0; i < paths.length; ++i) {
  586. ret.push(new PopulateOptions({
  587. path: paths[i],
  588. select: select,
  589. match: match,
  590. options: options,
  591. model: model,
  592. subPopulate: subPopulate,
  593. justOne: justOne,
  594. count: count
  595. }));
  596. }
  597. return ret;
  598. };
  599. /*!
  600. * Return the value of `obj` at the given `path`.
  601. *
  602. * @param {String} path
  603. * @param {Object} obj
  604. */
  605. exports.getValue = function(path, obj, map) {
  606. return mpath.get(path, obj, '_doc', map);
  607. };
  608. /*!
  609. * Sets the value of `obj` at the given `path`.
  610. *
  611. * @param {String} path
  612. * @param {Anything} val
  613. * @param {Object} obj
  614. */
  615. exports.setValue = function(path, val, obj, map, _copying) {
  616. mpath.set(path, val, obj, '_doc', map, _copying);
  617. };
  618. /*!
  619. * Returns an array of values from object `o`.
  620. *
  621. * @param {Object} o
  622. * @return {Array}
  623. * @private
  624. */
  625. exports.object = {};
  626. exports.object.vals = function vals(o) {
  627. const keys = Object.keys(o);
  628. let i = keys.length;
  629. const ret = [];
  630. while (i--) {
  631. ret.push(o[keys[i]]);
  632. }
  633. return ret;
  634. };
  635. /*!
  636. * @see exports.options
  637. */
  638. exports.object.shallowCopy = exports.options;
  639. /*!
  640. * Safer helper for hasOwnProperty checks
  641. *
  642. * @param {Object} obj
  643. * @param {String} prop
  644. */
  645. const hop = Object.prototype.hasOwnProperty;
  646. exports.object.hasOwnProperty = function(obj, prop) {
  647. return hop.call(obj, prop);
  648. };
  649. /*!
  650. * Determine if `val` is null or undefined
  651. *
  652. * @return {Boolean}
  653. */
  654. exports.isNullOrUndefined = function(val) {
  655. return val === null || val === undefined;
  656. };
  657. /*!
  658. * ignore
  659. */
  660. exports.array = {};
  661. /*!
  662. * Flattens an array.
  663. *
  664. * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4]
  665. *
  666. * @param {Array} arr
  667. * @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.
  668. * @return {Array}
  669. * @private
  670. */
  671. exports.array.flatten = function flatten(arr, filter, ret) {
  672. ret || (ret = []);
  673. arr.forEach(function(item) {
  674. if (Array.isArray(item)) {
  675. flatten(item, filter, ret);
  676. } else {
  677. if (!filter || filter(item)) {
  678. ret.push(item);
  679. }
  680. }
  681. });
  682. return ret;
  683. };
  684. /*!
  685. * Removes duplicate values from an array
  686. *
  687. * [1, 2, 3, 3, 5] => [1, 2, 3, 5]
  688. * [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ]
  689. * => [ObjectId("550988ba0c19d57f697dc45e")]
  690. *
  691. * @param {Array} arr
  692. * @return {Array}
  693. * @private
  694. */
  695. exports.array.unique = function(arr) {
  696. const primitives = {};
  697. const ids = {};
  698. const ret = [];
  699. const length = arr.length;
  700. for (let i = 0; i < length; ++i) {
  701. if (typeof arr[i] === 'number' || typeof arr[i] === 'string' || arr[i] == null) {
  702. if (primitives[arr[i]]) {
  703. continue;
  704. }
  705. ret.push(arr[i]);
  706. primitives[arr[i]] = true;
  707. } else if (arr[i] instanceof ObjectId) {
  708. if (ids[arr[i].toString()]) {
  709. continue;
  710. }
  711. ret.push(arr[i]);
  712. ids[arr[i].toString()] = true;
  713. } else {
  714. ret.push(arr[i]);
  715. }
  716. }
  717. return ret;
  718. };
  719. /*!
  720. * Determines if two buffers are equal.
  721. *
  722. * @param {Buffer} a
  723. * @param {Object} b
  724. */
  725. exports.buffer = {};
  726. exports.buffer.areEqual = function(a, b) {
  727. if (!Buffer.isBuffer(a)) {
  728. return false;
  729. }
  730. if (!Buffer.isBuffer(b)) {
  731. return false;
  732. }
  733. if (a.length !== b.length) {
  734. return false;
  735. }
  736. for (let i = 0, len = a.length; i < len; ++i) {
  737. if (a[i] !== b[i]) {
  738. return false;
  739. }
  740. }
  741. return true;
  742. };
  743. exports.getFunctionName = function(fn) {
  744. if (fn.name) {
  745. return fn.name;
  746. }
  747. return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1];
  748. };
  749. /*!
  750. * Decorate buffers
  751. */
  752. exports.decorate = function(destination, source) {
  753. for (const key in source) {
  754. if (specialProperties.has(key)) {
  755. continue;
  756. }
  757. destination[key] = source[key];
  758. }
  759. };
  760. /**
  761. * merges to with a copy of from
  762. *
  763. * @param {Object} to
  764. * @param {Object} fromObj
  765. * @api private
  766. */
  767. exports.mergeClone = function(to, fromObj) {
  768. if (isMongooseObject(fromObj)) {
  769. fromObj = fromObj.toObject({
  770. transform: false,
  771. virtuals: false,
  772. depopulate: true,
  773. getters: false,
  774. flattenDecimals: false
  775. });
  776. }
  777. const keys = Object.keys(fromObj);
  778. const len = keys.length;
  779. let i = 0;
  780. let key;
  781. while (i < len) {
  782. key = keys[i++];
  783. if (specialProperties.has(key)) {
  784. continue;
  785. }
  786. if (typeof to[key] === 'undefined') {
  787. to[key] = exports.clone(fromObj[key], {
  788. transform: false,
  789. virtuals: false,
  790. depopulate: true,
  791. getters: false,
  792. flattenDecimals: false
  793. });
  794. } else {
  795. let val = fromObj[key];
  796. if (val != null && val.valueOf && !(val instanceof Date)) {
  797. val = val.valueOf();
  798. }
  799. if (exports.isObject(val)) {
  800. let obj = val;
  801. if (isMongooseObject(val) && !val.isMongooseBuffer) {
  802. obj = obj.toObject({
  803. transform: false,
  804. virtuals: false,
  805. depopulate: true,
  806. getters: false,
  807. flattenDecimals: false
  808. });
  809. }
  810. if (val.isMongooseBuffer) {
  811. obj = Buffer.from(obj);
  812. }
  813. exports.mergeClone(to[key], obj);
  814. } else {
  815. to[key] = exports.clone(val, {
  816. flattenDecimals: false
  817. });
  818. }
  819. }
  820. }
  821. };
  822. /**
  823. * Executes a function on each element of an array (like _.each)
  824. *
  825. * @param {Array} arr
  826. * @param {Function} fn
  827. * @api private
  828. */
  829. exports.each = function(arr, fn) {
  830. for (let i = 0; i < arr.length; ++i) {
  831. fn(arr[i]);
  832. }
  833. };
  834. /*!
  835. * ignore
  836. */
  837. exports.noop = function() {};