all files / lib/offshore/utils/nestedOperations/ reduceAssociations.js

92% Statements 23/25
71.43% Branches 15/21
100% Functions 2/2
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 64 65 66 67 68                                  2266×   2266×     7927×     7927× 7879×   7875×       52×         52×   51×                             2266×    
/**
 * Module Dependencies
 */
 
var hop = require('../helpers').object.hasOwnProperty;
var _ = require('lodash');
var assert = require('assert');
var util = require('util');
 
/**
 * Traverse an object representing values replace associated objects with their
 * foreign keys.
 *
 * @param {String} model
 * @param {Object} schema
 * @param {Object} values
 * @return {Object}
 * @api private
 */
 
 
module.exports = function(model, schema, values, method) {
  var self = this;
 
  Object.keys(values).forEach(function(key) {
 
    // Check to see if this key is a foreign key
    var attribute = schema[model].attributes[key];
 
    // If not a plainObject, check if this is a model instance and has a toObject method
    if (!_.isPlainObject(values[key])) {
      if (_.isObject(values[key]) && !Array.isArray(values[key]) && values[key].toObject && typeof values[key].toObject === 'function') {
        values[key] = values[key].toObject();
      } else {
        return;
      }
    }
    // Check that this user-specified value is not NULL
    Iif (values[key] === null) return;
 
    // Check that this user-specified value actually exists
    // as an attribute in `model`'s schema.
    // If it doesn't- just ignore it
    if (typeof attribute !== 'object') return;
 
    if (!hop(values[key], attribute.on)) return;
 
    // Look and see if the related model has a custom primary key AND that
    // the intended method is "create"
    var related = self.offshore.collections[attribute.references];
    var relatedPK = _.find(related.attributes, { primaryKey: true });
 
    // 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 && method && (method == 'create' || method == 'update')) {
      return;
    }
 
    // Otherwise reduce the association like normal
    var fk = values[key][attribute.on];
    values[key] = fk;
 
  });
 
  return values;
};