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

92.44% Statements 110/119
84.78% Branches 78/92
100% Functions 14/14
93.16% Lines 109/117
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 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328                            418× 418× 418×                                                             418×   418×     418×                                                     418×       418×   418×   418×                   418× 418×   418× 1177×   1177×     2566×   2566× 312×       2566×     898×     896×                                                 1784× 1784× 1784× 1784×     1784×     1784×   1784×   29× 29×         1751× 333×         1784× 9019×     9019× 9019× 9019×               9019×       9019× 8986× 4879×         4140×         4135× 865×               4135× 3466× 3466× 3463×                         4135×                 4135×           4135× 4135× 4135×           4133× 4105×       28×   28× 36×     36×     28×         1784×     1782× 23×     1759×     1758× 1516× 1516× 599×   1516× 825×            
/**
 * Handles validation on a model
 *
 * Uses Offshore-validator for validating
 * https://github.com/Atlantis-Software/offshore-validator
 */
 
var _ = require('lodash');
var validator = require('offshore-validator');
var async = require('async');
var utils = require('../utils/helpers');
var hasOwnProperty = utils.object.hasOwnProperty;
var WLValidationError = require('../error/WLValidationError');
var offshoreCriteria = require('offshore-criteria');
var associationValidator = require('./associationValidations');
var normalize = require('../utils/normalize');
 
/**
 * Build up validations using the Offshore-validator module.
 *
 * @param {String} adapter
 */
 
var Validator = module.exports = function(context) {
  this.validations = {};
  this.associations = {};
  this.context = context;
};
 
/**
 * 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, criteria) {
  var self = this;
 
  defaults = defaults || {};
 
  // These properties are reserved and may not be used as validations
  this.reservedProperties = [
    'criteria',
    '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);
  }
 
  //this.criteria = criteria;
  this.criteria = normalize.criteria(criteria);
 
  this.defaults = {};
 
  if (criteria) {
    _.keys(this.criteria.where).forEach(function(key) {
      Eif (attrs[key]) {
        var type = attrs[key].type || attrs[key];
        var val = self.criteria.where[key];
        Iif (_.isPlainObject(val) && type !== 'json') {
          return;
        }
        Iif (_.isArray(val) && type !== 'array') {
          return;
        }
        self.defaults[key] = val;
      }
    });
  }
 
  // Add custom type definitions to validator
  types = types || {};
  validator.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 ((prop === 'collection') || (prop === 'model')) {
        self.associations[attr] = new associationValidator(self.context);
      }
 
      // If property is reserved don't do anything with it
      if (self.reservedProperties.indexOf(prop) > -1) { return; }
 
      // use the Offshore-validator `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);
  var associations = Object.keys(this.associations);
 
  // Handle optional second arg AND Use present values only, specified values, or all validations
  var type = Array.isArray(presentOnly) ? 'array' : typeof presentOnly;
  
  //affecting default values specified in the model criteria to the record to insert if they don't exist
  values = _.defaults(values, self.defaults);
  
  switch (type) {
    case 'function':
      cb = presentOnly;
      break;
    case 'string':
      validations = [presentOnly];
      break;
    case 'array':
      validations = presentOnly;
      break;
    default:
      // Any other truthy value.
      if (presentOnly) {
        validations = _.intersection(validations, Object.keys(values));
      }
  }
 
  // Validate all validations in parallel
  async.each(validations, function _eachValidation(validation, cb) {
    var curValidation = self.validations[validation];
 
    // Build Requirements
    var requirements;
    try {
      requirements = validator(curValidation);
    }
    catch (e) {
      // Handle fatal error:
      return cb(e);
    }
 
    // Grab value and set to null if undefined
    var value = _.isUndefined(values[validation]) ? null : values[validation];
 
    // 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 Offshore-validator.
      var validationError;
      try {
        validationError = validator(value).to(requirements.data, values);
      }
      catch (e) {
        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(null, errors);
    }
    // validate criteria of the model
    if (!offshoreCriteria([values], {where: self.criteria ? self.criteria.where : void 0}).results[0]) {
      errors.Criteria = [{rule: 'criteria', message: 'Object :\n' + require('util').inspect(values) + ' does not respect criteria defined in the model.'}];
      return cb(null, errors);
    }
    // validate association's criteria
    async.each(associations, function(association, next) {
      var associationValues = values[association] || [];
      if (!_.isArray(associationValues)) {
        associationValues = [associationValues];
      }
      async.each(associationValues, function(value, next) {
        self.associations[association].validate(value, false, next);
      }, next);
 
    }, cb);
  });
};