Skip to content

Commit

Permalink
Adds findByAssociation to extendsTo (#314)
Browse files Browse the repository at this point in the history
  • Loading branch information
dresende committed Sep 18, 2013
1 parent 2e307b9 commit d4eb2d0
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
36 changes: 36 additions & 0 deletions lib/Associations/Extend.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,42 @@ exports.prepare = function (db, Model, associations, association_properties, mod

associations.push(association);

Model["findBy" + assocName] = function () {
var cb = null, conditions = null, options = {};

for (var i = 0; i < arguments.length; i++) {
switch (typeof arguments[i]) {
case "function":
cb = arguments[i];
break;
case "object":
if (conditions === null) {
conditions = arguments[i];
} else {
options = arguments[i];
}
break;
}
}

if (conditions === null) {
throw ErrorCodes.generateError(ErrorCodes.PARAM_MISMATCH, ".findBy(" + assocName + ") is missing a conditions object");
}

options.__merge = {
from : { table: association.model.table, field: Object.keys(association.field) },
to : { table: Model.table, field: Model.id },
where : [ association.model.table, conditions ],
table : Model.table
};
options.extra = [];

if (typeof cb == "function") {
return Model.find({}, options, cb);
}
return Model.find({}, options);
};

return association.model;
};
};
Expand Down
33 changes: 33 additions & 0 deletions test/integration/association-extend.js
Original file line number Diff line number Diff line change
Expand Up @@ -212,4 +212,37 @@ describe("Model.extendsTo()", function() {
});
});
});

describe("findBy()", function () {
before(setup());

it("should throw if no conditions passed", function (done) {
(function () {
Person.findByAddress(function () {});
}).should.throw();

return done();
});

it("should lookup in Model based on associated model properties", function (done) {
Person.findByAddress({
number: 123
}, function (err, people) {
should.equal(err, null);
should(Array.isArray(people));
should(people.length == 1);

return done();
});
});

it("should return a ChainFind if no callback passed", function (done) {
var ChainFind = Person.findByAddress({
number: 123
});
ChainFind.run.should.be.a("function");

return done();
});
});
});

0 comments on commit d4eb2d0

Please sign in to comment.