validation.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /*!
  2. * Module requirements
  3. */
  4. 'use strict';
  5. const MongooseError = require('./mongooseError');
  6. const getConstructorName = require('../helpers/getConstructorName');
  7. const util = require('util');
  8. class ValidationError extends MongooseError {
  9. /**
  10. * Document Validation Error
  11. *
  12. * @api private
  13. * @param {Document} [instance]
  14. * @inherits MongooseError
  15. */
  16. constructor(instance) {
  17. let _message;
  18. if (getConstructorName(instance) === 'model') {
  19. _message = instance.constructor.modelName + ' validation failed';
  20. } else {
  21. _message = 'Validation failed';
  22. }
  23. super(_message);
  24. this.errors = {};
  25. this._message = _message;
  26. if (instance) {
  27. instance.$errors = this.errors;
  28. }
  29. }
  30. /**
  31. * Console.log helper
  32. */
  33. toString() {
  34. return this.name + ': ' + _generateMessage(this);
  35. }
  36. /*!
  37. * inspect helper
  38. */
  39. inspect() {
  40. return Object.assign(new Error(this.message), this);
  41. }
  42. /*!
  43. * add message
  44. */
  45. addError(path, error) {
  46. this.errors[path] = error;
  47. this.message = this._message + ': ' + _generateMessage(this);
  48. }
  49. }
  50. if (util.inspect.custom) {
  51. /*!
  52. * Avoid Node deprecation warning DEP0079
  53. */
  54. ValidationError.prototype[util.inspect.custom] = ValidationError.prototype.inspect;
  55. }
  56. /*!
  57. * Helper for JSON.stringify
  58. * Ensure `name` and `message` show up in toJSON output re: gh-9847
  59. */
  60. Object.defineProperty(ValidationError.prototype, 'toJSON', {
  61. enumerable: false,
  62. writable: false,
  63. configurable: true,
  64. value: function() {
  65. return Object.assign({}, this, { name: this.name, message: this.message });
  66. }
  67. });
  68. Object.defineProperty(ValidationError.prototype, 'name', {
  69. value: 'ValidationError'
  70. });
  71. /*!
  72. * ignore
  73. */
  74. function _generateMessage(err) {
  75. const keys = Object.keys(err.errors || {});
  76. const len = keys.length;
  77. const msgs = [];
  78. let key;
  79. for (let i = 0; i < len; ++i) {
  80. key = keys[i];
  81. if (err === err.errors[key]) {
  82. continue;
  83. }
  84. msgs.push(key + ': ' + err.errors[key].message);
  85. }
  86. return msgs.join(', ');
  87. }
  88. /*!
  89. * Module exports
  90. */
  91. module.exports = ValidationError;