all files / lib/waterline/core/ validations.js

92.47% Statements 86/93
87.88% Branches 58/66
100% Functions 11/11
93.41% Lines 85/91
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 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292                              274×                                                             274×   274×     274×                                                     274×       274× 274×   274× 545×   545×     1075×     1075×     466×     464×                                                   1343× 1343× 1343×       1343×   29× 29×           1310× 335×             1343× 6568×     6568× 6568× 6568×           6568×     6568× 6568× 3480×         6568× 6535× 3503×         3065×         3060× 682×               3060× 2842× 2842× 2836×                         3060×                 3060×           3060× 3060× 3060×             3058× 3030×       28×   28× 36×     36×     28×         1343×       1341× 1318×     23×        
/**
 * Handles validation on a model
 *
 * Uses Anchor for validating
 * https://github.com/balderdashy/anchor
 */
 
var _ = require('lodash');
var anchor = require('anchor');
var async = require('async');
var utils = require('../utils/helpers');
var hasOwnProperty = utils.object.hasOwnProperty;
var WLValidationError = require('../error/WLValidationError');
 
 
/**
 * Build up validations using the Anchor module.
 *
 * @param {String} adapter
 */
 
var Validator = module.exports = function(adapter) {
  this.validations = {};
};
 
/**
 * Builds a Validation Object from a normalized attributes
 * object.
 *
 * Loops through an attributes object to build a validation object
 * containing attribute name as key and a series of validations that
 * are run on each model. Skips over type and defaultsTo as they are
 * schema properties.
 *
 * Example:
 *
 * attributes: {
 *   name: {
 *     type: 'string',
 *     length: { min: 2, max: 5 }
 *   }
 *   email: {
 *     type: 'string',
 *     required: true
 *   }
 * }
 *
 * Returns: {
 *   name: { length: { min:2, max: 5 }},
 *   email: { required: true }
 * }
 */
 
Validator.prototype.initialize = function(attrs, types, defaults) {
  var self = this;
 
  defaults = defaults || {};
 
  // These properties are reserved and may not be used as validations
  this.reservedProperties = [
    'defaultsTo',
    'primaryKey',
    'autoIncrement',
    'unique',
    'index',
    'collection',
    'dominant',
    'through',
    'columnName',
    'foreignKey',
    'references',
    'on',
    'groupKey',
    'model',
    'via',
    'size',
    'example',
    'validationMessage',
    'validations',
    'populateSettings',
    'onKey',
    'protected',
    'meta'
  ];
 
 
  if (defaults.ignoreProperties && Array.isArray(defaults.ignoreProperties)) {
    this.reservedProperties = this.reservedProperties.concat(defaults.ignoreProperties);
  }
 
  // Add custom type definitions to anchor
  types = types || {};
  anchor.define(types);
 
  Object.keys(attrs).forEach(function(attr) {
    self.validations[attr] = {};
 
    Object.keys(attrs[attr]).forEach(function(prop) {
 
      // Ignore null values
      Iif (attrs[attr][prop] === null) { return; }
 
      // If property is reserved don't do anything with it
      if (self.reservedProperties.indexOf(prop) > -1) { return; }
 
      // use the Anchor `in` method for enums
      if (prop === 'enum') {
        self.validations[attr]['in'] = attrs[attr][prop];
        return;
      }
 
      self.validations[attr][prop] = attrs[attr][prop];
    });
  });
};
 
 
/**
 * Validator.prototype.validate()
 *
 * Accepts a dictionary of values and validates them against
 * the validation rules expected by this schema (`this.validations`).
 * Validation is performed using Anchor.
 *
 *
 * @param {Dictionary} values
 *        The dictionary of values to validate.
 *
 * @param {Boolean|String|String[]} presentOnly
 *        only validate present values (if `true`) or validate the
 *        specified attribute(s).
 *
 * @param {Function} callback
 *        @param {Error} err - a fatal error, if relevant.
 *        @param {Array} invalidAttributes - an array of errors
 */
 
Validator.prototype.validate = function(values, presentOnly, cb) {
  var self = this;
  var errors = {};
  var validations = Object.keys(this.validations);
 
  // Handle optional second arg AND Use present values only, specified values, or all validations
  /* eslint-disable no-fallthrough */
  switch (typeof presentOnly) {
    case 'function':
      cb = presentOnly;
      break;
    case 'string':
      validations = [presentOnly];
      break;
    case 'object':
      Eif (Array.isArray(presentOnly)) {
        validations = presentOnly;
        break;
      } // Fall through to the default if the object is not an array
    default:
      // Any other truthy value.
      if (presentOnly) {
        validations = _.intersection(validations, Object.keys(values));
      }
    /* eslint-enable no-fallthrough */
  }
 
 
  // Validate all validations in parallel
  async.each(validations, function _eachValidation(validation, cb) {
    var curValidation = self.validations[validation];
 
    // Build Requirements
    var requirements;
    try {
      requirements = anchor(curValidation);
    }
    catch (e) {
      // Handle fatal error:
      return cb(e);
    }
    requirements = _.cloneDeep(requirements);
 
    // Grab value and set to null if undefined
    var value = values[validation];
    if (typeof value == 'undefined') {
      value = null;
    }
 
    // If value is not required and empty then don't
    // try and validate it
    if (!curValidation.required) {
      if (value === null || value === '') {
        return cb();
      }
    }
 
    // If Boolean and required manually check
    if (curValidation.required && curValidation.type === 'boolean' && (typeof value !== 'undefined' && value !== null)) {
      Eif (value.toString() === 'true' || value.toString() === 'false') {
        return cb();
      }
    }
 
    // If type is integer and the value matches a mongoID let it validate
    if (hasOwnProperty(self.validations[validation], 'type') && self.validations[validation].type === 'integer') {
      Iif (utils.matchMongoId(value)) {
        return cb();
      }
    }
 
    // Rule values may be specified as sync or async functions.
    // Call them and replace the rule value with the function's result
    // before running validations.
    async.each(Object.keys(requirements.data), function _eachKey(key, next) {
      try {
        if (typeof requirements.data[key] !== 'function') {
          return next();
        }
 
        // Run synchronous function
        if (requirements.data[key].length < 1) {
          requirements.data[key] = requirements.data[key].apply(values, []);
          return next();
        }
 
        // Run async function
        requirements.data[key].call(values, function(result) {
          requirements.data[key] = result;
          next();
        });
      }
      catch (e) {
        return next(e);
      }
    }, function afterwards(unexpectedErr) {
      Iif (unexpectedErr) {
        // Handle fatal error
        return cb(unexpectedErr);
      }
 
      // If the value has a dynamic required function and it evaluates to false lets look and see
      // if the value supplied is null or undefined. If so then we don't need to check anything. This
      // prevents type errors like `undefined` should be a string.
      // if required is set to 'false', don't enforce as required rule
      if (requirements.data.hasOwnProperty('required') && !requirements.data.required) {
        Iif (_.isNull(value)) {
          return cb();
        }
      }
 
      // Now run the validations using Anchor.
      var validationError;
      try {
        validationError = anchor(value).to(requirements.data, values);
      }
      catch (e) {
        // Handle fatal error:
        return cb(e);
      }
 
      // If no validation errors, bail.
      if (!validationError) {
        return cb();
      }
 
      // Build an array of errors.
      errors[validation] = [];
 
      validationError.forEach(function(obj) {
        Iif (obj.property) {
          delete obj.property;
        }
        errors[validation].push({ rule: obj.rule, message: obj.message });
      });
 
      return cb();
    });
 
  }, function allValidationsChecked(err) {
    // Handle fatal error:
    if (err) {
      return cb(err);
    }
 
 
    if (Object.keys(errors).length === 0) {
      return cb();
    }
 
    return cb(undefined, errors);
  });
 
};