All files / mongoose/lib/error validator.js

19.23% Statements 5/26
0% Branches 0/6
0% Functions 0/4
19.23% Lines 5/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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