fixed and enhanced caching in getters and setters in abstract-class

This commit is contained in:
Sébastien Drouyer 2012-11-01 01:13:16 +01:00
parent 6d8454c5ac
commit 46b7747c87
1 changed files with 22 additions and 15 deletions

View File

@ -729,17 +729,23 @@ AbstractClass.belongsTo = function (anotherClass, params) {
}.bind(this));
};
this.prototype[methodName] = function (p) {
this.prototype[methodName] = function (refresh, p) {
if (arguments.length === 1) {
p = refresh;
refresh = false;
} else if (arguments.length > 2) {
throw new Error('Method only can\'t be only called with more than two arguments');
}
var self = this;
var cachedValue = null;
if (this.__cachedRelations && this.__cachedRelations[methodName]) {
var cachedValue;
if (!refresh && this.__cachedRelations && (typeof this.__cachedRelations[methodName] !== 'undefined')) {
cachedValue = this.__cachedRelations[methodName];
}
if (p instanceof AbstractClass) { // acts as setter
this[fk] = p.id;
this.__cachedRelations[methodName] = p;
} else if (typeof p === 'function') { // acts as async getter
if (cachedValue === null) {
if (typeof cachedValue === 'undefined') {
this.__finders__[methodName](this[fk], function(err, inst) {
if (!err) {
self.__cachedRelations[methodName] = inst;
@ -752,10 +758,10 @@ AbstractClass.belongsTo = function (anotherClass, params) {
return cachedValue;
}
} else if (typeof p === 'undefined') { // acts as sync getter
return cachedValue || this[fk];
return this[fk];
} else { // setter
this[fk] = p;
this.__cachedRelations[methodName] = p;
delete this.__cachedRelations[methodName];
}
};
@ -793,6 +799,7 @@ function defineScope(cls, targetClass, name, params, methods) {
var f = function caller(condOrRefresh, cb) {
var actualCond = {};
var actualRefresh = false;
var saveOnCache = true;
if (arguments.length === 1) {
cb = condOrRefresh;
} else if (arguments.length === 2) {
@ -800,23 +807,23 @@ function defineScope(cls, targetClass, name, params, methods) {
actualRefresh = condOrRefresh;
} else {
actualCond = condOrRefresh;
actualRefresh = true;
saveOnCache = false;
}
} else if (arguments.length > 2) {
throw new Error('Method only can\'t be called with more than two arguments');
} else {
throw new Error('Method only can be only called with one or two arguments');
}
if (!this.__cachedRelations || !this.__cachedRelations[name] || actualRefresh) {
if (!this.__cachedRelations || (typeof this.__cachedRelations[name] == 'undefined') || actualRefresh) {
var self = this;
return targetClass.all(mergeParams(actualCond, caller._scope), function(err, data) {
if (!err && saveOnCache) {
self.__cachedRelations[name] = data;
}
cb(err, data);
});
} else {
if (cb) {
cb(null, this.__cachedRelations);
} else {
return this.__cachedRelations[name];
}
cb(null, this.__cachedRelations[name]);
}
};
f._scope = typeof params === 'function' ? params.call(this) : params;