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

93.33% Statements 28/30
61.11% Branches 11/18
100% Functions 4/4
93.33% Lines 28/30
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   312×                       932×   932×   932×     931×   928×    
var _ = require('lodash');
var offshoreCriteria = require('offshore-criteria');
var normalize = require('../utils/normalize');
 
var AssociationValidator = module.exports = function(context) {
  this.context = context;
};
 
AssociationValidator.prototype.initialize = function(collectionName, criteria) {
  var self = this;
  this.collectionName = collectionName;
  this.criteria = normalize.criteria(criteria);
  this.defaults = {};
  Eif (this.criteria.where) {
    _.keys(this.criteria.where).forEach(function(key) {
      var attr = self.context.offshore.collections[self.collectionName]._attributes[key];
      Eif (attr) {
        var type = attr.type || attr;
        var val = self.criteria.where[key];
        Iif (_.isPlainObject(val) && type !== 'json') {
          return;
        }
        Iif (_.isArray(val) && type !== 'array') {
          return;
        }
        self.defaults[key] = val;
      }
    });
  }
};
 
AssociationValidator.prototype.validate = function(values, presentOnly, cb) {
  var errors = {};
 
  values = _.defaults(values, this.defaults);
 
  if (!offshoreCriteria([values], this.criteria).results[0]) {
    errors.Association = [{rule: 'criteria', message: 'Associated objects :\n' + require('util').inspect(values) + ' do not respect criteria specified in the parent model.'}];
    return cb(errors);
  }
  // calling model validation after validating association criteria
  if (this.context.offshore.collections[this.collectionName]) {
    return this.context.offshore.collections[this.collectionName]._validator.validate(values, presentOnly, cb);
  }
  cb();
};