Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve-findById #29

Merged
merged 4 commits into from Nov 24, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 21 additions & 3 deletions lib/model.js
Expand Up @@ -260,17 +260,35 @@ Model.prototype.where = function(condition) {
* @param [withJson]
* @returns {*}
*/
Model.prototype.findById = function(_id, callback, withJson) {
Model.prototype.findById = function (_id, callback, withJson) {
var id = _id;
if(this.primaryKeys.length === 1 && typeof _id !== "object") {
var self = this;
if (this.primaryKeys.length === 1 && typeof _id !== "object") {
id = {};
id[this.primaryKeys[0].name] = _id;
}

if(typeof id !== "object") {
if (typeof id !== "object") {
return callback(new Error("You should pass a valid IDs object."));
}

if (this.cache) {
return this.cache.getData(this.toshihiko.database, this.name, id, function (err, data) {
if (err) {
data = [];
}
if (data.length !== 0) {
var yukari = new Yukari(self, "query");
yukari._initRow(data[0],true);
if (withJson) {
yukari = yukari.toJSON();
}
return callback(null, yukari);
}
return self.where(id).findOne(callback, withJson);
})
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing semicolon.

}

return this.where(id).findOne(callback, withJson);
};

Expand Down
8 changes: 8 additions & 0 deletions test/model.js
Expand Up @@ -130,6 +130,14 @@ describe("model", function () {
should(err).not.be.ok;
data.should.hasOwnProperty("key1").eql(3);
done();
},true);
});

it("findById return null", function(done) {
Model.findById(100, function(err, data) {
should(err).not.be.ok;
should.not.exist(data);
done();
});
});

Expand Down