validator.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*!
  2. * Module dependencies.
  3. */
  4. 'use strict';
  5. const MongooseError = require('./');
  6. class ValidatorError extends MongooseError {
  7. /**
  8. * Schema validator error
  9. *
  10. * @param {Object} properties
  11. * @api private
  12. */
  13. constructor(properties) {
  14. let msg = properties.message;
  15. if (!msg) {
  16. msg = MongooseError.messages.general.default;
  17. }
  18. const message = formatMessage(msg, properties);
  19. super(message);
  20. properties = Object.assign({}, properties, { message: message });
  21. this.properties = properties;
  22. this.kind = properties.type;
  23. this.path = properties.path;
  24. this.value = properties.value;
  25. this.reason = properties.reason;
  26. }
  27. /*!
  28. * toString helper
  29. * TODO remove? This defaults to `${this.name}: ${this.message}`
  30. */
  31. toString() {
  32. return this.message;
  33. }
  34. /*!
  35. * Ensure `name` and `message` show up in toJSON output re: gh-9296
  36. */
  37. toJSON() {
  38. return Object.assign({ name: this.name, message: this.message }, this);
  39. }
  40. }
  41. Object.defineProperty(ValidatorError.prototype, 'name', {
  42. value: 'ValidatorError'
  43. });
  44. /*!
  45. * The object used to define this validator. Not enumerable to hide
  46. * it from `require('util').inspect()` output re: gh-3925
  47. */
  48. Object.defineProperty(ValidatorError.prototype, 'properties', {
  49. enumerable: false,
  50. writable: true,
  51. value: null
  52. });
  53. // Exposed for testing
  54. ValidatorError.prototype.formatMessage = formatMessage;
  55. /*!
  56. * Formats error messages
  57. */
  58. function formatMessage(msg, properties) {
  59. if (typeof msg === 'function') {
  60. return msg(properties);
  61. }
  62. const propertyNames = Object.keys(properties);
  63. for (const propertyName of propertyNames) {
  64. if (propertyName === 'message') {
  65. continue;
  66. }
  67. msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]);
  68. }
  69. return msg;
  70. }
  71. /*!
  72. * exports
  73. */
  74. module.exports = ValidatorError;