Skip to content

Instantly share code, notes, and snippets.

@jdub
Created January 1, 2011 11:36
Show Gist options
  • Save jdub/761697 to your computer and use it in GitHub Desktop.
Save jdub/761697 to your computer and use it in GitHub Desktop.
function JSONRPC(options) {
if (!(this instanceof JSONRPC)) return new JSONRPC(options);
this.socket = options.socket || null;
this.fallback = options.fallback || null;
this.callbacks = {};
}
// FIXME: check for unloved callbacks at a user-defined interval
// call them with Error objects
// we already store original call time because keys ARE the time :-)
// are intervals/timeouts GCed if this object is deleted/unset?
// params: <method>, params**, [callback]
// return: sent jsonrpc object, handy if you haven't set a socket
JSONRPC.prototype.send = function(method) {
if ( typeof method !== 'string' ) throw new Error({
code: -32600,
message: "Invalid JSON-RPC: <method> must be a string."
});
var params = Array.prototype.slice.call(arguments, 1),
callback = arguments[arguments.length - 1],
rpc = {jsonrpc: '2.0', method: method};
// if we have a callback, generate an id for it so we catch the result
if ( typeof callback === 'function' ) {
rpc.id = Date.now();
this.callbacks[rpc.id] = callback;
// dump the nulled callback from the args to params conversion
params.pop();
}
// FIXME: making assumptions here that won't work with named params
if ( params.length > 0 ) rpc.params = params;
if ( this.socket.send ) this.socket.send(rpc);
return rpc;
};
// params: message = jsonrpc 2.0 result object
JSONRPC.prototype.receive = function(message) {
if ( message && message.jsonrpc && message.jsonrpc === '2.0' ) {
var result = message.result || message || null;
// hit up our callback (and then delete it)
if ( message.id && typeof this.callbacks[message.id] === 'function' ) {
this.callbacks[message.id](result);
delete this.callbacks[message.id];
// or hit up our fallback
} else if ( typeof this.fallback === 'function' ) {
this.fallback(result);
// or log it and see what happens, FIXME: smarter please
} else {
if (console) console.log(message);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment