all files / lib/waterline/utils/nestedOperations/ create.js

88.46% Statements 23/26
70.59% Branches 12/17
100% Functions 3/3
95.45% Lines 21/22
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                                42×     42× 42× 42×   42×   42×     42× 42×     42×   42× 42× 42×   42×     74×           63×     63×           42×    
/**
 * Module Dependencies
 */
 
var _ = require('lodash');
var hasOwnProperty = require('../helpers').object.hasOwnProperty;
 
/**
 * Queue up .add() operations on a model instance for any nested association
 * values in a .create() query.
 *
 * @param {Object} parentModel
 * @param {Object} values
 * @param {Object} associations
 * @param {Function} cb
 * @api private
 */
 
module.exports = function(parentModel, values, associations, cb) {
  var self = this;
 
  // For each association, grab the primary key value and normalize into model.add methods
  associations.forEach(function(association) {
    var attribute = self.waterline.schema[self.identity].attributes[association];
    var modelName;
 
    Eif (hasOwnProperty(attribute, 'collection')) modelName = attribute.collection;
 
    Iif (!modelName) return;
 
    // Grab the relation's PK
    var related = self.waterline.collections[modelName];
    var relatedPK = _.find(related.attributes, { primaryKey: true });
 
    // Get the attribute's name
    var pk = self.waterline.collections[modelName].primaryKey;
 
    var optValues = values[association];
    Iif (!optValues) return;
    if (!_.isArray(optValues)) {
      optValues = _.isString(optValues) ? optValues.split(',') : [optValues];
    }
    optValues.forEach(function(val) {
 
      // If value is not an object, queue up an add
      if (!_.isPlainObject(val)) return parentModel[association].add(val);
 
      // If value is an object, check if a primary key is defined
      // If a custom PK was used and it's not autoIncrementing and the record
      // is being created then go ahead and don't reduce it. This allows nested
      // creates to work when custom PK's are used.
      Iif (relatedPK.autoIncrement && related.autoPK && hasOwnProperty(val, pk)) {
        return parentModel[association].add(val[pk]);
      } else {
        parentModel[association].add(val);
      }
    });
  });
 
  // Save the parent model
  parentModel.save(cb);
};