Skip to content

Commit

Permalink
improve-findById
Browse files Browse the repository at this point in the history
  • Loading branch information
luicfer committed Nov 24, 2015
1 parent b855545 commit 50b4a6e
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions lib/model.js
Original file line number Diff line number Diff line change
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]);
if (withJson) {
yukari = yukari.toJSON();
}
return callback(null, yukari);
}
return self.where(id).findOne(callback, withJson);
})
}

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

Expand Down

0 comments on commit 50b4a6e

Please sign in to comment.