Scope method should return cached relation value (sync)

This commit is contained in:
Fabien Franzen 2014-09-04 21:23:24 +02:00
parent aea2f64181
commit 3efe7ab354
2 changed files with 12 additions and 6 deletions

View File

@ -55,13 +55,13 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres
} else {
throw new Error('Method can be only called with one or two arguments');
}
if (!self.__cachedRelations || self.__cachedRelations[name] === undefined
|| actualRefresh) {
// It either doesn't hit the cache or refresh is required
var params = mergeQuery(actualCond, scopeParams);
var targetModel = this.targetModel(receiver);
return targetModel.find(params, function (err, data) {
targetModel.find(params, function (err, data) {
if (!err && saveOnCache) {
defineCachedRelations(self);
self.__cachedRelations[name] = data;
@ -149,10 +149,12 @@ function defineScope(cls, targetClass, name, params, methods, options) {
var self = this;
var f = function(condOrRefresh, cb) {
if(arguments.length === 1) {
definition.related(self, f._scope, condOrRefresh);
if (arguments.length === 0) {
return self.__cachedRelations && self.__cachedRelations[name];
} else if (arguments.length === 1) {
return definition.related(self, f._scope, condOrRefresh);
} else {
definition.related(self, f._scope, condOrRefresh, cb);
return definition.related(self, f._scope, condOrRefresh, cb);
}
};

View File

@ -91,10 +91,14 @@ describe('relations', function () {
should.not.exist(err);
should.exist(ch);
ch.should.have.lengthOf(3);
var chapters = book.chapters();
chapters.should.eql(ch);
book.chapters({order: 'name DESC'}, function (e, c) {
should.not.exist(e);
should.exist(c);
c.shift().name.should.equal('z');
c.pop().name.should.equal('a');
done();