validation.js 1.9 KB

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