Merge pull request #524 from fabien/feature/scope-findOne

Implement scope.findOne
This commit is contained in:
Raymond Feng 2015-03-22 07:55:15 -07:00
commit 268c04e14f
2 changed files with 33 additions and 3 deletions

View File

@ -190,6 +190,7 @@ function defineScope(cls, targetClass, name, params, methods, options) {
f.create = create; f.create = create;
f.destroyAll = destroyAll; f.destroyAll = destroyAll;
f.findById = findById; f.findById = findById;
f.findOne = findOne;
f.count = count; f.count = count;
for (var i in definition.methods) { for (var i in definition.methods) {
f[i] = definition.methods[i].bind(self); f[i] = definition.methods[i].bind(self);
@ -245,6 +246,13 @@ function defineScope(cls, targetClass, name, params, methods, options) {
cls['__findById__' + name] = fn_findById; cls['__findById__' + name] = fn_findById;
var fn_findOne = function (cb) {
var f = this[name].findOne;
f.apply(this[name], arguments);
};
cls['__findOne__' + name] = fn_findOne;
var fn_count = function (cb) { var fn_count = function (cb) {
var f = this[name].count; var f = this[name].count;
f.apply(this[name], arguments); f.apply(this[name], arguments);
@ -287,10 +295,16 @@ function defineScope(cls, targetClass, name, params, methods, options) {
function findById(id, cb) { function findById(id, cb) {
var targetModel = definition.targetModel(this._receiver); var targetModel = definition.targetModel(this._receiver);
var idName = targetModel.definition.idName(); var idName = targetModel.definition.idName();
var where = {}; var filter = { where: {} };
where[idName] = id; filter.where[idName] = id;
this.findOne(filter, cb);
}
function findOne(filter, cb) {
if (typeof filter === 'function') cb = filter, filter = {};
var targetModel = definition.targetModel(this._receiver);
var scoped = (this._scope && this._scope.where) || {}; var scoped = (this._scope && this._scope.where) || {};
var filter = mergeQuery({ where: scoped }, { where: where }); var filter = mergeQuery({ where: scoped }, filter || {});
targetModel.findOne(filter, cb); targetModel.findOne(filter, cb);
} }

View File

@ -182,6 +182,22 @@ describe('scope - filtered count and destroyAll', function () {
}); });
}); });
it('should find one', function(done) {
Station.active.findOne(function(err, station) {
should.not.exist(err);
station.name.should.equal('a');
done();
});
});
it('should find one - with filter', function(done) {
Station.active.findOne({ where: { name: 'c' } }, function(err, station) {
should.not.exist(err);
station.name.should.equal('c');
done();
});
});
it('should find by id - match', function(done) { it('should find by id - match', function(done) {
Station.active.findById(stationA.id, function(err, station) { Station.active.findById(stationA.id, function(err, station) {
should.not.exist(err); should.not.exist(err);