all files / lib/waterline/model/lib/defaultMethods/ destroy.js

72.73% Statements 32/44
60.71% Branches 17/28
100% Functions 4/4
74.42% Lines 32/43
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                                                                                                                                                           
 
/**
 * Module dependencies
 */
 
var utils = require('../../../utils/helpers');
var hasOwnProperty = utils.object.hasOwnProperty;
var defer = require('../../../utils/defer');
var noop = function() {};
 
/**
 * Model.destroy()
 *
 * Destroys an instance of a model
 *
 * @param {Object} context,
 * @param {Object} proto
 * @param {Function} callback
 * @return {Promise}
 * @api public
 */
 
var Destroy = module.exports = function(context, proto, cb) {
 
  var deferred;
  var err;
 
  if (typeof cb !== 'function') {
    deferred = defer();
  }
 
  cb = cb || noop;
 
  var values = proto.toObject();
  var attributes = context.waterline.schema[context.identity].attributes;
  var primaryKey = this.findPrimaryKey(attributes, values);
 
  Iif (!primaryKey) {
    err = new Error('No Primary Key set to update the record with! ' +
    'Try setting an attribute as a primary key or include an ID property.');
 
    if (deferred) {
      deferred.reject(err);
    }
 
    return cb(err);
  }
 
  Iif (!values[primaryKey]) {
    err = new Error('No Primary Key set to update the record with! ' +
    'Primary Key must have a value, it can\'t be an optional value.');
 
    if (deferred) {
      deferred.reject(err);
    }
 
    return cb(err);
  }
 
  // Build Search Criteria
  var criteria = {};
  criteria[primaryKey] = values[primaryKey];
 
  // Execute Query
  context.destroy(criteria, function(err, status) {
    Iif (err) {
 
      if (deferred) {
        deferred.reject(err);
      }
 
      return cb(err);
    }
 
    if (deferred) {
      deferred.resolve(status);
    }
 
    cb.apply(this, arguments);
  });
 
  if (deferred) {
    return deferred.promise;
  }
};
 
/**
 * Find Primary Key
 *
 * @param {Object} attributes
 * @param {Object} values
 * @api private
 */
 
Destroy.prototype.findPrimaryKey = function(attributes, values) {
  var primaryKey = null;
 
  for (var attribute in attributes) {
    if (hasOwnProperty(attributes[attribute], 'primaryKey') && attributes[attribute].primaryKey) {
      primaryKey = attribute;
      break;
    }
  }
 
  // If no primary key check for an ID property
  Iif (!primaryKey && hasOwnProperty(values, 'id')) primaryKey = 'id';
 
  return primaryKey;
};