Skip to content

Commit

Permalink
Added namespacing capabilities.
Browse files Browse the repository at this point in the history
  • Loading branch information
coreybutler committed Aug 14, 2013
1 parent 1551f46 commit c7fe5e6
Showing 1 changed file with 55 additions and 9 deletions.
64 changes: 55 additions & 9 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,10 @@ function Server(sock) {

Server.prototype.methodDescriptions = function(){
var obj = {};
var fn;

for (var name in this.methods) {
fn = this.methods[name];
obj[name] = {
name: name,
params: params(fn)
};
var ns = getNamespace(this.methods[name]);
obj[name] = getNamespace(this.methods[name],true);
}

return obj;
Expand Down Expand Up @@ -76,8 +72,18 @@ Server.prototype.onmessage = function(msg, reply){
var meth = msg.method;
if (!meth) return reply({ error: '.method required' });

// Check for namespacing
var ns = meth.split('.');
if (ns.length > 1){
var fn = this.methods;
ns.forEach(function(attr){
fn = fn[attr];
});
} else {
var fn = this.methods[meth];
}

// ensure .method is exposed
var fn = this.methods[meth];
if (!fn) return reply({ error: 'method "' + meth + '" does not exist' });

// .args
Expand All @@ -94,6 +100,29 @@ Server.prototype.onmessage = function(msg, reply){
fn.apply(null, args);
};

/**
* Get the namespace tree.
*
* @param {Object} obj
* @param {Object} parms
* @api private
*/
var getNamespace = function(obj,parms) {
parms = parms == undefined ? false : parms;
switch (typeof obj){
case 'function':
return obj;
case 'object':
var out = {};
for (var ns in obj){
out[ns] = typeof obj[ns] == 'function' ? (parms == true ? {name: ns, params:params(obj[ns])} : obj[ns]) : getNamespace(obj[ns],parms);
}
return out;
default:
throw 'Function attribute provided to expose() is invalid.';
}
};

/**
* Expose many or a single method.
*
Expand All @@ -109,8 +138,25 @@ Server.prototype.expose = function(name, fn){
}
} else {
debug('expose "%s"', name);
this.methods[name] = fn;
this.methods[name] = getNamespace(fn);
}
};

/**
* Retrieve a method
*
* @param {Object} obj
* @api private
*/
var getMethod = function(obj) {
if (typeof obj == 'function'){
return obj;
}
var ns = obj;
while (typeof ns == 'object'){
ns = ns[Object.keys(ns)[0]];
}
return ns;
};

/**
Expand All @@ -122,7 +168,7 @@ Server.prototype.expose = function(name, fn){
*/

function params(fn) {
var ret = fn.toString().match(/^function *(\w*)\((.*?)\)/)[2];
var ret = getMethod(fn).toString().match(/^function *(\w*)\((.*?)\)/)[2];
if (ret) return ret.split(/ *, */);
return [];
}

0 comments on commit c7fe5e6

Please sign in to comment.