all files / lib/waterline/query/finders/ dynamicFinders.js

56.25% Statements 54/96
53.85% Branches 28/52
58.33% Functions 7/12
59.77% Lines 52/87
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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291                              266×     266×     1230× 57× 56×   57×     1173×     1173×     1173× 1169× 10521×   1169× 3507×                                   14028× 14028×     14028×     14028×     14028×                                                                                                                                                                               56× 56×       56×     222×   222×   36×           56×                                                                                                                                                                                    
/**
 * Dynamic Queries
 *
 * Query the collection using the name of the attribute directly
 */
 
var _ = require('lodash');
var usageError = require('../../utils/usageError');
var utils = require('../../utils/helpers');
var normalize = require('../../utils/normalize');
var hasOwnProperty = utils.object.hasOwnProperty;
 
var finder = module.exports = {};
 
/**
 * buildDynamicFinders
 *
 * Attaches shorthand dynamic methods to the prototype for each attribute
 * in the schema.
 */
 
finder.buildDynamicFinders = function() {
  var self = this;
 
  // For each defined attribute, create a dynamic finder function
  Object.keys(this._attributes).forEach(function(attrName) {
 
    // Check if attribute is an association, if so generate limited dynamic finders
    if (hasOwnProperty(self._schema.schema[attrName], 'foreignKey')) {
      if (self.associationFinders !== false) {
        self.generateAssociationFinders(attrName);
      }
      return;
    }
 
    var capitalizedMethods = ['findOneBy*', 'findOneBy*In', 'findOneBy*Like', 'findBy*', 'findBy*In',
      'findBy*Like', 'countBy*', 'countBy*In', 'countBy*Like'];
 
    var lowercasedMethods = ['*StartsWith', '*Contains', '*EndsWith'];
 
 
    if (self.dynamicFinders !== false) {
      capitalizedMethods.forEach(function(method) {
        self.generateDynamicFinder(attrName, method);
      });
      lowercasedMethods.forEach(function(method) {
        self.generateDynamicFinder(attrName, method, true);
      });
    }
  });
};
 
 
/**
 * generateDynamicFinder
 *
 * Creates a dynamic method based off the schema. Used for shortcuts for various
 * methods where a criteria object can automatically be built.
 *
 * @param {String} attrName
 * @param {String} method
 * @param {Boolean} dont capitalize the attrName or do, defaults to false
 */
 
finder.generateDynamicFinder = function(attrName, method, dontCapitalize) {
  var self = this;
  var criteria;
 
  // Capitalize Attribute Name for camelCase
  var preparedAttrName = dontCapitalize ? attrName : utils.capitalize(attrName);
 
  // Figure out actual dynamic method name by injecting attribute name
  var actualMethodName = method.replace(/\*/g, preparedAttrName);
 
  // Assign this finder to the collection
  this[actualMethodName] = function dynamicMethod(value, options, cb) {
 
    if (typeof options === 'function') {
      cb = options;
      options = null;
    }
 
    options = options || {};
 
    var usage = utils.capitalize(self.identity) + '.' + actualMethodName + '(someValue,[options],callback)';
 
    Iif (typeof value === 'undefined') return usageError('No value specified!', usage, cb);
    Iif (options.where) return usageError('Cannot specify `where` option in a dynamic ' + method + '*() query!', usage, cb);
 
    // Build criteria query and submit it
    options.where = {};
    options.where[attrName] = value;
 
    switch (method) {
 
 
      ///////////////////////////////////////
      // Finders
      ///////////////////////////////////////
 
 
      case 'findOneBy*':
      case 'findOneBy*In':
        return self.findOne(options, cb);
 
      case 'findOneBy*Like':
        criteria = _.extend(options, {
          where: {
            like: options.where
          }
        });
 
        return self.findOne(criteria, cb);
 
 
      ///////////////////////////////////////
      // Aggregate Finders
      ///////////////////////////////////////
 
 
      case 'findBy*':
      case 'findBy*In':
        return self.find(options, cb);
 
      case 'findBy*Like':
        criteria = _.extend(options, {
          where: {
            like: options.where
          }
        });
 
        return self.find(criteria, cb);
 
 
      ///////////////////////////////////////
      // Count Finders
      ///////////////////////////////////////
 
 
      case 'countBy*':
      case 'countBy*In':
        return self.count(options, cb);
 
      case 'countBy*Like':
        criteria = _.extend(options, {
          where: {
            like: options.where
          }
        });
 
        return self.count(criteria, cb);
 
 
      ///////////////////////////////////////
      // Searchers
      ///////////////////////////////////////
 
      case '*StartsWith':
        return self.startsWith(options, cb);
 
      case '*Contains':
        return self.contains(options, cb);
 
      case '*EndsWith':
        return self.endsWith(options, cb);
    }
  };
};
 
 
/**
 * generateAssociationFinders
 *
 * Generate Dynamic Finders for an association.
 * Adds a .findBy<name>() method for has_one and belongs_to associations.
 *
 * @param {String} attrName, the column name of the attribute
 */
 
finder.generateAssociationFinders = function(attrName) {
  var self = this;
  var name, model;
 
  // Find the user defined key for this attrName, look in self defined columnName
  // properties and if that's not set see if the generated columnName matches the attrName
  for (var key in this._attributes) {
 
    // Cache the value
    var cache = this._attributes[key];
 
    if (!hasOwnProperty(cache, 'model')) continue;
 
    Iif (cache.model.toLowerCase() + '_id' === attrName) {
      name = key;
      model = cache.model;
    }
  }
 
  Eif (!name || !model) return;
 
  // Build a findOneBy<attrName> dynamic finder that forces a join on the association
  this['findOneBy' + utils.capitalize(name)] = function dynamicAssociationMethod(value, cb) {
 
    // Check proper usage
    var usage = utils.capitalize(self.identity) + '.' + 'findBy' + utils.capitalize(name) +
      '(someValue, callback)';
 
    if (typeof value === 'undefined') return usageError('No value specified!', usage, cb);
    if (typeof value === 'function') return usageError('No value specified!', usage, cb);
 
    var criteria = associationQueryCriteria(self, value, attrName);
    return this.findOne(criteria, cb);
  };
 
  // Build a findBy<attrName> dynamic finder that forces a join on the association
  this['findBy' + utils.capitalize(name)] = function dynamicAssociationMethod(value, cb) {
 
    // Check proper usage
    var usage = utils.capitalize(self.identity) + '.' + 'findBy' + utils.capitalize(name) +
      '(someValue, callback)';
 
    if (typeof value === 'undefined') return usageError('No value specified!', usage, cb);
    if (typeof value === 'function') return usageError('No value specified!', usage, cb);
 
    var criteria = associationQueryCriteria(self, value, attrName);
    return this.find(criteria, cb);
  };
};
 
 
/**
 * Build Join Array
 */
 
function buildJoin() {
  var self = this;
  var pk, attr;
 
  // Set the attr value to the generated schema attribute
  attr = self.waterline.schema[self.identity].attributes[name];
 
  // Get the current collection's primary key attribute
  Object.keys(self._attributes).forEach(function(key) {
    if (hasOwnProperty(self._attributes[key], 'primaryKey') && self._attributes[key].primaryKey) {
      pk = key;
    }
  });
 
  if (!attr) throw new Error('Attempting to populate an attribute that doesn\'t exist');
 
  // Grab the key being populated to check if it is a has many to belongs to
  // If it's a belongs_to the adapter needs to know that it should replace the foreign key
  // with the associated value.
  var parentKey = self.waterline.collections[self.identity].attributes[name];
 
 
  // Build the initial join object that will link this collection to either another collection
  // or to a junction table.
  var join = {
    parent: self._tableName,
    parentKey: attr.columnName || pk,
    child: attr.references,
    childKey: attr.on,
    select: true,
    removeParentKey: !!parentKey.model
  };
 
  return join;
}
 
/**
 * Query Criteria Builder for associations
 */
 
function associationQueryCriteria(context, value, attrName) {
 
  // Build a criteria object
  var criteria = {
    where: {},
    joins: []
  };
 
  // Build a join condition
  var join = buildJoin.call(context);
  criteria.joins.push(join);
 
  // Add where values
  criteria.where[attrName] = value;
  return criteria;
}