all files / lib/offshore/query/dql/ destroy.js

91.14% Statements 72/79
78.95% Branches 30/38
100% Functions 10/10
98.55% Lines 68/69
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                          120× 120×   120×         120×     120×     120× 42×     78× 78×       78×     76× 76×     76×     76× 76×     66×         66×     33×                 17× 17×   17× 51× 51× 17×         17×     17× 25× 25×   25×     17×   17×                       66× 66× 66× 61× 53× 312×         66×              
/**
 * Module Dependencies
 */
 
var async = require('async');
var _ = require('lodash');
var usageError = require('../../utils/usageError');
var utils = require('../../utils/helpers');
var normalize = require('../../utils/normalize');
var Deferred = require('../deferred');
var getRelations = require('../../utils/getRelations');
var callbacks = require('../../utils/callbacksRunner');
var hasOwnProperty = utils.object.hasOwnProperty;
 
/**
 * Destroy a Record
 *
 * @param {Object} criteria to destroy
 * @param {Function} callback
 * @return Deferred object if no callback
 */
 
module.exports = function(criteria, cb, metaContainer) {
  var self = this;
  var pk;
 
  if (typeof criteria === 'function') {
    cb = criteria;
    criteria = {};
  }
 
  // Check if criteria is an integer or string and normalize criteria
  // to object, using the specified primary key field.
  criteria = normalize.expandPK(self, criteria);
 
  // Normalize criteria
  criteria = normalize.criteria(criteria);
 
  // Return Deferred or pass to adapter
  if (typeof cb !== 'function') {
    return new Deferred(this, this.destroy, criteria);
  }
 
  var usage = utils.capitalize(this.identity) + '.destroy([options], callback)';
  Iif (typeof cb !== 'function') return usageError('Invalid callback specified!', usage, cb);
 
  // If there was something defined in the criteria that would return no results, don't even
  // run the query and just return an empty result set.
  if (criteria === false) {
    return cb(null, []);
  }
 
  callbacks.beforeDestroy(self, criteria, function(err) {
    Iif (err) return cb(err);
 
    // Transform Search Criteria
    criteria = self._transformer.serialize(criteria);
 
    // Pass to adapter
    self.adapter._loadQuery(self._query).destroy(criteria, function(err, result) {
      if (err) return cb(err);
 
      // Look for any m:m associations and destroy the value in the join table
      var relations = getRelations({
        schema: self.offshore.schema,
        parentCollection: self.identity
      });
 
      if (relations.length === 0) return after();
 
      // Find the collection's primary key
      for (var key in self.attributes) {
        if (!self.attributes[key].hasOwnProperty('primaryKey')) continue;
 
        // Check if custom primaryKey value is falsy
        Iif (!self.attributes[key].primaryKey) continue;
 
        if (self.attributes[key].columnName) {
          pk = self.attributes[key].columnName;
        } else {
          pk = key;
        }
 
        break;
      }
 
      function destroyJoinTableRecords(item, next) {
        var collection = self.offshore.collections[item];
        var refKey;
 
        Object.keys(collection._attributes).forEach(function(key) {
          var attr = collection._attributes[key];
          if (attr.references !== self.identity) return;
          refKey = key;
        });
 
        // If no refKey return, this could leave orphaned join table values but it's better
        // than crashing.
        Iif (!refKey) return next();
 
        // Make sure we don't return any undefined pks
        var mappedValues = result.reduce(function(memo, vals) {
          Eif (vals[pk] !== undefined) {
            memo.push(vals[pk]);
          }
          return memo;
        }, []);
 
        var criteria = {};
 
        if (mappedValues.length > 0) {
          criteria[refKey] = mappedValues;
          var q = collection.destroy(criteria);
 
          Iif(metaContainer) {
            q.meta(metaContainer);
          }
 
          q.exec(next);
        } else {
          return next();
        }
 
      }
 
      async.each(relations, destroyJoinTableRecords, function(err) {
        Iif (err) return cb(err);
        after();
      });
 
      function after() {
        callbacks.afterDestroy(self, result, function(err) {
          Iif (err) return cb(err);
          if (result) {
            if (_.isArray(result)) {
              result = result.map(function(entry) {
                return self._transformer.unserialize(entry);
              });
            } else {
              result = self._transformer.unserialize(result);
            }
          }
          cb(null, result);
        });
      }
 
    }, metaContainer);
  });
};