Implement scope.findOne

This commit is contained in:
Fabien Franzen 2015-03-21 13:44:06 +01:00
parent 5d0b745f31
commit 8199767a8a
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.destroyAll = destroyAll;
f.findById = findById;
f.findOne = findOne;
f.count = count;
for (var i in definition.methods) {
f[i] = definition.methods[i].bind(self);
@ -245,6 +246,13 @@ function defineScope(cls, targetClass, name, params, methods, options) {
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 f = this[name].count;
f.apply(this[name], arguments);
@ -287,10 +295,16 @@ function defineScope(cls, targetClass, name, params, methods, options) {
function findById(id, cb) {
var targetModel = definition.targetModel(this._receiver);
var idName = targetModel.definition.idName();
var where = {};
where[idName] = id;
var filter = { where: {} };
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 filter = mergeQuery({ where: scoped }, { where: where });
var filter = mergeQuery({ where: scoped }, filter || {});
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) {
Station.active.findById(stationA.id, function(err, station) {
should.not.exist(err);