validation.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /*!
  2. * Module requirements
  3. */
  4. 'use strict';
  5. const MongooseError = require('./mongooseError');
  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. * Ensure `name` and `message` show up in toJSON output re: gh-9847
  58. */
  59. Object.defineProperty(ValidationError.prototype, 'toJSON', {
  60. enumerable: false,
  61. writable: false,
  62. configurable: true,
  63. value: function() {
  64. return Object.assign({}, this, { name: this.name, message: this.message });
  65. }
  66. });
  67. Object.defineProperty(ValidationError.prototype, 'name', {
  68. value: 'ValidationError'
  69. });
  70. /*!
  71. * ignore
  72. */
  73. function _generateMessage(err) {
  74. const keys = Object.keys(err.errors || {});
  75. const len = keys.length;
  76. const msgs = [];
  77. let key;
  78. for (let i = 0; i < len; ++i) {
  79. key = keys[i];
  80. if (err === err.errors[key]) {
  81. continue;
  82. }
  83. msgs.push(key + ': ' + err.errors[key].message);
  84. }
  85. return msgs.join(', ');
  86. }
  87. /*!
  88. * Module exports
  89. */
  90. module.exports = ValidationError;