Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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. * @return {Object} the cloned object
  150. * @api private
  151. */
  152. exports.clone = function clone(obj, options) {
  153. if (obj === undefined || obj === null) {
  154. return obj;
  155. }
  156. if (Array.isArray(obj)) {
  157. return cloneArray(obj, options);
  158. }
  159. if (isMongooseObject(obj)) {
  160. if (options && options.json && typeof obj.toJSON === 'function') {
  161. return obj.toJSON(options);
  162. }
  163. return obj.toObject(options);
  164. }
  165. if (obj.constructor) {
  166. switch (exports.getFunctionName(obj.constructor)) {
  167. case 'Object':
  168. return cloneObject(obj, options);
  169. case 'Date':
  170. return new obj.constructor(+obj);
  171. case 'RegExp':
  172. return cloneRegExp(obj);
  173. default:
  174. // ignore
  175. break;
  176. }
  177. }
  178. if (obj instanceof ObjectId) {
  179. return new ObjectId(obj.id);
  180. }
  181. if (isBsonType(obj, 'Decimal128')) {
  182. if (options && options.flattenDecimals) {
  183. return obj.toJSON();
  184. }
  185. return Decimal.fromString(obj.toString());
  186. }
  187. if (!obj.constructor && exports.isObject(obj)) {
  188. // object created with Object.create(null)
  189. return cloneObject(obj, options);
  190. }
  191. if (obj.valueOf) {
  192. return obj.valueOf();
  193. }
  194. };
  195. const clone = exports.clone;
  196. /*!
  197. * ignore
  198. */
  199. exports.promiseOrCallback = function promiseOrCallback(callback, fn, ee) {
  200. if (typeof callback === 'function') {
  201. return fn(function(error) {
  202. if (error != null) {
  203. if (ee != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) {
  204. error[emittedSymbol] = true;
  205. ee.emit('error', error);
  206. }
  207. try {
  208. callback(error);
  209. } catch (error) {
  210. return process.nextTick(() => {
  211. throw error;
  212. });
  213. }
  214. return;
  215. }
  216. callback.apply(this, arguments);
  217. });
  218. }
  219. const Promise = PromiseProvider.get();
  220. return new Promise((resolve, reject) => {
  221. fn(function(error, res) {
  222. if (error != null) {
  223. if (ee != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) {
  224. error[emittedSymbol] = true;
  225. ee.emit('error', error);
  226. }
  227. return reject(error);
  228. }
  229. if (arguments.length > 2) {
  230. return resolve(Array.prototype.slice.call(arguments, 1));
  231. }
  232. resolve(res);
  233. });
  234. });
  235. };
  236. /*!
  237. * ignore
  238. */
  239. function cloneObject(obj, options) {
  240. const minimize = options && options.minimize;
  241. const ret = {};
  242. let hasKeys;
  243. let val;
  244. let k;
  245. for (k in obj) {
  246. if (specialProperties.has(k)) {
  247. continue;
  248. }
  249. val = clone(obj[k], options);
  250. if (!minimize || (typeof val !== 'undefined')) {
  251. hasKeys || (hasKeys = true);
  252. ret[k] = val;
  253. }
  254. }
  255. return minimize ? hasKeys && ret : ret;
  256. }
  257. function cloneArray(arr, options) {
  258. const ret = [];
  259. for (let i = 0, l = arr.length; i < l; i++) {
  260. ret.push(clone(arr[i], options));
  261. }
  262. return ret;
  263. }
  264. /*!
  265. * Shallow copies defaults into options.
  266. *
  267. * @param {Object} defaults
  268. * @param {Object} options
  269. * @return {Object} the merged object
  270. * @api private
  271. */
  272. exports.options = function(defaults, options) {
  273. const keys = Object.keys(defaults);
  274. let i = keys.length;
  275. let k;
  276. options = options || {};
  277. while (i--) {
  278. k = keys[i];
  279. if (!(k in options)) {
  280. options[k] = defaults[k];
  281. }
  282. }
  283. return options;
  284. };
  285. /*!
  286. * Generates a random string
  287. *
  288. * @api private
  289. */
  290. exports.random = function() {
  291. return Math.random().toString().substr(3);
  292. };
  293. /*!
  294. * Merges `from` into `to` without overwriting existing properties.
  295. *
  296. * @param {Object} to
  297. * @param {Object} from
  298. * @api private
  299. */
  300. exports.merge = function merge(to, from, options, path) {
  301. options = options || {};
  302. const keys = Object.keys(from);
  303. let i = 0;
  304. const len = keys.length;
  305. let key;
  306. path = path || '';
  307. const omitNested = options.omitNested || {};
  308. while (i < len) {
  309. key = keys[i++];
  310. if (options.omit && options.omit[key]) {
  311. continue;
  312. }
  313. if (omitNested[path]) {
  314. continue;
  315. }
  316. if (specialProperties.has(key)) {
  317. continue;
  318. }
  319. if (to[key] == null) {
  320. to[key] = from[key];
  321. } else if (exports.isObject(from[key])) {
  322. if (!exports.isObject(to[key])) {
  323. to[key] = {};
  324. }
  325. if (from[key] != null) {
  326. if (from[key].instanceOfSchema) {
  327. to[key] = from[key].clone();
  328. continue;
  329. } else if (from[key] instanceof ObjectId) {
  330. to[key] = new ObjectId(from[key]);
  331. continue;
  332. }
  333. }
  334. merge(to[key], from[key], options, path ? path + '.' + key : key);
  335. } else if (options.overwrite) {
  336. to[key] = from[key];
  337. }
  338. }
  339. };
  340. /*!
  341. * Applies toObject recursively.
  342. *
  343. * @param {Document|Array|Object} obj
  344. * @return {Object}
  345. * @api private
  346. */
  347. exports.toObject = function toObject(obj) {
  348. Document || (Document = require('./document'));
  349. let ret;
  350. if (obj == null) {
  351. return obj;
  352. }
  353. if (obj instanceof Document) {
  354. return obj.toObject();
  355. }
  356. if (Array.isArray(obj)) {
  357. ret = [];
  358. for (let i = 0, len = obj.length; i < len; ++i) {
  359. ret.push(toObject(obj[i]));
  360. }
  361. return ret;
  362. }
  363. if ((obj.constructor && exports.getFunctionName(obj.constructor) === 'Object') ||
  364. (!obj.constructor && exports.isObject(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 object.
  391. *
  392. * @param {Object|Array|String|Function|RegExp|any} arg
  393. * @api private
  394. * @return {Boolean}
  395. */
  396. exports.isPOJO = function(arg) {
  397. return arg instanceof Object && arg.constructor.name === 'Object';
  398. };
  399. /*!
  400. * A faster Array.prototype.slice.call(arguments) alternative
  401. * @api private
  402. */
  403. exports.args = sliced;
  404. /*!
  405. * process.nextTick helper.
  406. *
  407. * Wraps `callback` in a try/catch + nextTick.
  408. *
  409. * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback.
  410. *
  411. * @param {Function} callback
  412. * @api private
  413. */
  414. exports.tick = function tick(callback) {
  415. if (typeof callback !== 'function') {
  416. return;
  417. }
  418. return function() {
  419. try {
  420. callback.apply(this, arguments);
  421. } catch (err) {
  422. // only nextTick on err to get out of
  423. // the event loop and avoid state corruption.
  424. process.nextTick(function() {
  425. throw err;
  426. });
  427. }
  428. };
  429. };
  430. /*!
  431. * Returns if `v` is a mongoose object that has a `toObject()` method we can use.
  432. *
  433. * This is for compatibility with libs like Date.js which do foolish things to Natives.
  434. *
  435. * @param {any} v
  436. * @api private
  437. */
  438. exports.isMongooseObject = function(v) {
  439. Document || (Document = require('./document'));
  440. MongooseArray || (MongooseArray = require('./types').Array);
  441. MongooseBuffer || (MongooseBuffer = require('./types').Buffer);
  442. if (v == null) {
  443. return false;
  444. }
  445. return v.$__ != null || // Document
  446. v.isMongooseArray || // Array or Document Array
  447. v.isMongooseBuffer || // Buffer
  448. v.$isMongooseMap; // Map
  449. };
  450. const isMongooseObject = exports.isMongooseObject;
  451. /*!
  452. * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB.
  453. *
  454. * @param {Object} object
  455. * @api private
  456. */
  457. exports.expires = function expires(object) {
  458. if (!(object && object.constructor.name === 'Object')) {
  459. return;
  460. }
  461. if (!('expires' in object)) {
  462. return;
  463. }
  464. let when;
  465. if (typeof object.expires !== 'string') {
  466. when = object.expires;
  467. } else {
  468. when = Math.round(ms(object.expires) / 1000);
  469. }
  470. object.expireAfterSeconds = when;
  471. delete object.expires;
  472. };
  473. /*!
  474. * Populate options constructor
  475. */
  476. function PopulateOptions(obj) {
  477. this.path = obj.path;
  478. this.match = obj.match;
  479. this.select = obj.select;
  480. this.options = obj.options;
  481. this.model = obj.model;
  482. if (typeof obj.subPopulate === 'object') {
  483. this.populate = obj.subPopulate;
  484. }
  485. if (obj.justOne != null) {
  486. this.justOne = obj.justOne;
  487. }
  488. if (obj.count != null) {
  489. this.count = obj.count;
  490. }
  491. this._docs = {};
  492. }
  493. // make it compatible with utils.clone
  494. PopulateOptions.prototype.constructor = Object;
  495. // expose
  496. exports.PopulateOptions = PopulateOptions;
  497. /*!
  498. * populate helper
  499. */
  500. exports.populate = function populate(path, select, model, match, options, subPopulate, justOne, count) {
  501. // The order of select/conditions args is opposite Model.find but
  502. // necessary to keep backward compatibility (select could be
  503. // an array, string, or object literal).
  504. function makeSingles(arr) {
  505. const ret = [];
  506. arr.forEach(function(obj) {
  507. if (/[\s]/.test(obj.path)) {
  508. const paths = obj.path.split(' ');
  509. paths.forEach(function(p) {
  510. const copy = Object.assign({}, obj);
  511. copy.path = p;
  512. ret.push(copy);
  513. });
  514. } else {
  515. ret.push(obj);
  516. }
  517. });
  518. return ret;
  519. }
  520. // might have passed an object specifying all arguments
  521. if (arguments.length === 1) {
  522. if (path instanceof PopulateOptions) {
  523. return [path];
  524. }
  525. if (Array.isArray(path)) {
  526. const singles = makeSingles(path);
  527. return singles.map(function(o) {
  528. if (o.populate && !(o.match || o.options)) {
  529. return exports.populate(o)[0];
  530. } else {
  531. return exports.populate(o)[0];
  532. }
  533. });
  534. }
  535. if (exports.isObject(path)) {
  536. match = path.match;
  537. options = path.options;
  538. select = path.select;
  539. model = path.model;
  540. subPopulate = path.populate;
  541. justOne = path.justOne;
  542. path = path.path;
  543. count = path.count;
  544. }
  545. } else if (typeof model === 'object') {
  546. options = match;
  547. match = model;
  548. model = undefined;
  549. }
  550. if (typeof path !== 'string') {
  551. throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`');
  552. }
  553. if (Array.isArray(subPopulate)) {
  554. const ret = [];
  555. subPopulate.forEach(function(obj) {
  556. if (/[\s]/.test(obj.path)) {
  557. const copy = Object.assign({}, obj);
  558. const paths = copy.path.split(' ');
  559. paths.forEach(function(p) {
  560. copy.path = p;
  561. ret.push(exports.populate(copy)[0]);
  562. });
  563. } else {
  564. ret.push(exports.populate(obj)[0]);
  565. }
  566. });
  567. subPopulate = exports.populate(ret);
  568. } else if (typeof subPopulate === 'object') {
  569. subPopulate = exports.populate(subPopulate);
  570. }
  571. const ret = [];
  572. const paths = path.split(' ');
  573. options = exports.clone(options);
  574. for (let i = 0; i < paths.length; ++i) {
  575. ret.push(new PopulateOptions({
  576. path: paths[i],
  577. select: select,
  578. match: match,
  579. options: options,
  580. model: model,
  581. subPopulate: subPopulate,
  582. justOne: justOne,
  583. count: count
  584. }));
  585. }
  586. return ret;
  587. };
  588. /*!
  589. * Return the value of `obj` at the given `path`.
  590. *
  591. * @param {String} path
  592. * @param {Object} obj
  593. */
  594. exports.getValue = function(path, obj, map) {
  595. return mpath.get(path, obj, '_doc', map);
  596. };
  597. /*!
  598. * Sets the value of `obj` at the given `path`.
  599. *
  600. * @param {String} path
  601. * @param {Anything} val
  602. * @param {Object} obj
  603. */
  604. exports.setValue = function(path, val, obj, map, _copying) {
  605. mpath.set(path, val, obj, '_doc', map, _copying);
  606. };
  607. /*!
  608. * Returns an array of values from object `o`.
  609. *
  610. * @param {Object} o
  611. * @return {Array}
  612. * @private
  613. */
  614. exports.object = {};
  615. exports.object.vals = function vals(o) {
  616. const keys = Object.keys(o);
  617. let i = keys.length;
  618. const ret = [];
  619. while (i--) {
  620. ret.push(o[keys[i]]);
  621. }
  622. return ret;
  623. };
  624. /*!
  625. * @see exports.options
  626. */
  627. exports.object.shallowCopy = exports.options;
  628. /*!
  629. * Safer helper for hasOwnProperty checks
  630. *
  631. * @param {Object} obj
  632. * @param {String} prop
  633. */
  634. const hop = Object.prototype.hasOwnProperty;
  635. exports.object.hasOwnProperty = function(obj, prop) {
  636. return hop.call(obj, prop);
  637. };
  638. /*!
  639. * Determine if `val` is null or undefined
  640. *
  641. * @return {Boolean}
  642. */
  643. exports.isNullOrUndefined = function(val) {
  644. return val === null || val === undefined;
  645. };
  646. /*!
  647. * ignore
  648. */
  649. exports.array = {};
  650. /*!
  651. * Flattens an array.
  652. *
  653. * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4]
  654. *
  655. * @param {Array} arr
  656. * @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.
  657. * @return {Array}
  658. * @private
  659. */
  660. exports.array.flatten = function flatten(arr, filter, ret) {
  661. ret || (ret = []);
  662. arr.forEach(function(item) {
  663. if (Array.isArray(item)) {
  664. flatten(item, filter, ret);
  665. } else {
  666. if (!filter || filter(item)) {
  667. ret.push(item);
  668. }
  669. }
  670. });
  671. return ret;
  672. };
  673. /*!
  674. * Removes duplicate values from an array
  675. *
  676. * [1, 2, 3, 3, 5] => [1, 2, 3, 5]
  677. * [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ]
  678. * => [ObjectId("550988ba0c19d57f697dc45e")]
  679. *
  680. * @param {Array} arr
  681. * @return {Array}
  682. * @private
  683. */
  684. exports.array.unique = function(arr) {
  685. const primitives = {};
  686. const ids = {};
  687. const ret = [];
  688. const length = arr.length;
  689. for (let i = 0; i < length; ++i) {
  690. if (typeof arr[i] === 'number' || typeof arr[i] === 'string' || arr[i] == null) {
  691. if (primitives[arr[i]]) {
  692. continue;
  693. }
  694. ret.push(arr[i]);
  695. primitives[arr[i]] = true;
  696. } else if (arr[i] instanceof ObjectId) {
  697. if (ids[arr[i].toString()]) {
  698. continue;
  699. }
  700. ret.push(arr[i]);
  701. ids[arr[i].toString()] = true;
  702. } else {
  703. ret.push(arr[i]);
  704. }
  705. }
  706. return ret;
  707. };
  708. /*!
  709. * Determines if two buffers are equal.
  710. *
  711. * @param {Buffer} a
  712. * @param {Object} b
  713. */
  714. exports.buffer = {};
  715. exports.buffer.areEqual = function(a, b) {
  716. if (!Buffer.isBuffer(a)) {
  717. return false;
  718. }
  719. if (!Buffer.isBuffer(b)) {
  720. return false;
  721. }
  722. if (a.length !== b.length) {
  723. return false;
  724. }
  725. for (let i = 0, len = a.length; i < len; ++i) {
  726. if (a[i] !== b[i]) {
  727. return false;
  728. }
  729. }
  730. return true;
  731. };
  732. exports.getFunctionName = function(fn) {
  733. if (fn.name) {
  734. return fn.name;
  735. }
  736. return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1];
  737. };
  738. /*!
  739. * Decorate buffers
  740. */
  741. exports.decorate = function(destination, source) {
  742. for (const key in source) {
  743. if (specialProperties.has(key)) {
  744. continue;
  745. }
  746. destination[key] = source[key];
  747. }
  748. };
  749. /**
  750. * merges to with a copy of from
  751. *
  752. * @param {Object} to
  753. * @param {Object} fromObj
  754. * @api private
  755. */
  756. exports.mergeClone = function(to, fromObj) {
  757. if (isMongooseObject(fromObj)) {
  758. fromObj = fromObj.toObject({
  759. transform: false,
  760. virtuals: false,
  761. depopulate: true,
  762. getters: false,
  763. flattenDecimals: false
  764. });
  765. }
  766. const keys = Object.keys(fromObj);
  767. const len = keys.length;
  768. let i = 0;
  769. let key;
  770. while (i < len) {
  771. key = keys[i++];
  772. if (specialProperties.has(key)) {
  773. continue;
  774. }
  775. if (typeof to[key] === 'undefined') {
  776. to[key] = exports.clone(fromObj[key], {
  777. transform: false,
  778. virtuals: false,
  779. depopulate: true,
  780. getters: false,
  781. flattenDecimals: false
  782. });
  783. } else {
  784. let val = fromObj[key];
  785. if (val != null && val.valueOf && !(val instanceof Date)) {
  786. val = val.valueOf();
  787. }
  788. if (exports.isObject(val)) {
  789. let obj = val;
  790. if (isMongooseObject(val) && !val.isMongooseBuffer) {
  791. obj = obj.toObject({
  792. transform: false,
  793. virtuals: false,
  794. depopulate: true,
  795. getters: false,
  796. flattenDecimals: false
  797. });
  798. }
  799. if (val.isMongooseBuffer) {
  800. obj = Buffer.from(obj);
  801. }
  802. exports.mergeClone(to[key], obj);
  803. } else {
  804. to[key] = exports.clone(val, {
  805. flattenDecimals: false
  806. });
  807. }
  808. }
  809. }
  810. };
  811. /**
  812. * Executes a function on each element of an array (like _.each)
  813. *
  814. * @param {Array} arr
  815. * @param {Function} fn
  816. * @api private
  817. */
  818. exports.each = function(arr, fn) {
  819. for (let i = 0; i < arr.length; ++i) {
  820. fn(arr[i]);
  821. }
  822. };
  823. /*!
  824. * ignore
  825. */
  826. exports.noop = function() {};