Skip to content

Commit

Permalink
Adds Utilities.checkConditions() (#293)
Browse files Browse the repository at this point in the history
  • Loading branch information
dresende committed Aug 8, 2013
1 parent ad97778 commit fdc7862
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
17 changes: 16 additions & 1 deletion lib/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ function Model(opts) {
opts = opts || {};

if (!Array.isArray(opts.id)) {
opts.id = [opts.id];
opts.id = [ opts.id ];
}

var one_associations = [];
Expand Down Expand Up @@ -365,6 +365,9 @@ function Model(opts) {
if (order) {
order = Utilities.standardizeOrder(order);
}
if (conditions) {
conditions = Utilities.checkConditions(conditions, model_fields, one_associations);
}

var chain = new ChainFind(model, {
only : options.only || model_fields,
Expand Down Expand Up @@ -460,6 +463,10 @@ function Model(opts) {
throw ErrorCodes.generateError(ErrorCodes.MISSING_CALLBACK, "Missing Model.count() callback");
}

if (conditions) {
conditions = Utilities.checkConditions(conditions, model_fields, one_associations);
}

opts.driver.count(opts.table, conditions, {}, function (err, data) {
if (err || data.length === 0) {
return cb(err);
Expand All @@ -483,6 +490,10 @@ function Model(opts) {
}
}

if (conditions) {
conditions = Utilities.checkConditions(conditions, model_fields, one_associations);
}

return new require("./AggregateFunctions")({
table : opts.table,
driver_name : opts.driver_name,
Expand Down Expand Up @@ -516,6 +527,10 @@ function Model(opts) {
}
}

if (conditions) {
conditions = Utilities.checkConditions(conditions, model_fields, one_associations);
}

opts.driver.count(opts.table, conditions, {}, function (err, data) {
if (err || data.length === 0) {
return cb(err);
Expand Down
29 changes: 29 additions & 0 deletions lib/Utilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,35 @@ exports.standardizeOrder = function (order) {
return new_order;
};

/**
* Checks for:
*
* A) condition keys being association names of a model;
* B) condition values being instances;
*/
exports.checkConditions = function (conditions, model_fields, one_associations) {
for (var k in conditions) {
if (!conditions.hasOwnProperty(k)) continue;

// B)
if (conditions[k].isInstance) {
conditions[k] = conditions[k][conditions[k].model().id];
}

// A)
if (model_fields.indexOf(k) == -1) {
for (var i = 0; i < one_associations.length; i++) {
if (one_associations[i].name == k) {
conditions[Object.keys(one_associations[i].field).pop()] = conditions[k];
delete conditions[k];
}
}
}
}

return conditions;
};

/**
* Gets all the values within an object or array, optionally
* using a keys array to get only specific values
Expand Down

0 comments on commit fdc7862

Please sign in to comment.