Dedupe the alias methods during mixin

To prevent the same method from showing up multiple times in API explorer,
for example, Model.deleteById, Model.removeById
This commit is contained in:
Raymond Feng 2013-12-13 16:45:31 -08:00
parent efb5b36c84
commit bf592413e1
2 changed files with 23 additions and 5 deletions

View File

@ -55,11 +55,12 @@ exports.mixin = function (newClass, mixinClass, options) {
}
if (options.staticProperties) {
var staticProxies = [];
Object.keys(mixinClass).forEach(function (classProp) {
if (classProp !== 'super_' && classProp !== '_mixins' && (!newClass.hasOwnProperty(classProp) || options.override)) {
var pd = Object.getOwnPropertyDescriptor(mixinClass, classProp);
if(options.proxyFunctions && pd.writable && typeof pd.value === 'function') {
pd.value = exports.proxy(pd.value);
pd.value = exports.proxy(pd.value, staticProxies);
}
Object.defineProperty(newClass, classProp, pd);
}
@ -68,11 +69,12 @@ exports.mixin = function (newClass, mixinClass, options) {
if (options.instanceProperties) {
if (mixinClass.prototype) {
var instanceProxies = [];
Object.keys(mixinClass.prototype).forEach(function (instanceProp) {
if (!newClass.prototype.hasOwnProperty(instanceProp) || options.override) {
var pd = Object.getOwnPropertyDescriptor(mixinClass.prototype, instanceProp);
if(options.proxyFunctions && pd.writable && typeof pd.value === 'function') {
pd.value = exports.proxy(pd.value);
pd.value = exports.proxy(pd.value, instanceProxies);
}
Object.defineProperty(newClass.prototype, instanceProp, pd);
}
@ -83,10 +85,20 @@ exports.mixin = function (newClass, mixinClass, options) {
return newClass;
};
exports.proxy = function(fn) {
exports.proxy = function(fn, proxies) {
// Make sure same methods referenced by different properties have the same proxy
// For example, deleteById is an alias of removeById
proxies = proxies || [];
for(var i = 0; i<proxies.length; i++) {
if(proxies[i]._delegate === fn) {
return proxies[i];
}
}
var f = function() {
return fn.apply(this, arguments);
};
f._delegate = fn;
proxies.push(f);
Object.keys(fn).forEach(function(x) {
f[x] = fn[x];
});

View File

@ -868,6 +868,12 @@ describe('Injected methods from connectors', function(){
assert.equal(m1.shared, true, 'M1.save is now remotable');
assert.equal(!!m2.shared, false, 'M2.save is not remotable');
assert.equal(M1.deleteById, M1.removeById,
'Same methods on the same model should have the same proxy');
assert.notEqual(M1.deleteById, M2.deleteById,
'Same methods on differnt models should have different proxies');
});
});