@studiolabs/strong-remoting
Version:
StrongLoop Remoting Module
102 lines (82 loc) • 2.55 kB
JavaScript
// Copyright IBM Corp. 2013,2014. All Rights Reserved.
// Node module: strong-remoting
// This file is licensed under the Artistic License 2.0.
// License text available at https://opensource.org/licenses/Artistic-2.0
;
var g = require('strong-globalize')();
/**
* Expose `CoteContext`.
*/
module.exports = CoteContext;
/**
* Module dependencies.
*/
var EventEmitter = require('events').EventEmitter;
var debug = require('debug')('strong-remoting:socket-io-context');
var util = require('util');
var inherits = util.inherits;
var assert = require('assert');
/**
* Create a new `CoteContext` with the given `options`.
*
* @param {Object} options
* @return {CoteContext}
*/
function CoteContext(method, typeRegistry, args) {
// NOTE(bajtos) we are not asserting via "instanceof" to allow
// multiple copies of strong-remoting to cooperate together
assert(method && typeof method === 'object',
'method must be a SharedClass instance');
assert(typeRegistry && typeof typeRegistry === 'object',
'typeRegistry must be a TypeRegistry instance');
EventEmitter.call(this);
this.method = method;
this.typeRegistry = typeRegistry;
this.args = args;
}
/**
* Inherit from `EventEmitter`.
*/
inherits(CoteContext, EventEmitter);
CoteContext.prototype.getScope = function() {
// Static methods are invoked on the constructor (this = constructor fn)
// Prototype methods are invoked on the instance (this = instance)
var method = this.method;
return this.instance ||
method.ctor ||
method.sharedMethod && method.sharedMethod.ctor;
};
/**
* Invoke the given shared method using the provided scope against
* the current context.
*/
CoteContext.prototype.invoke = function(scope, method, fn) {
var args = this.args;
var returns = method.returns;
var result;
// invoke the shared method
method.invoke(scope, args, function(err) {
var resultArgs = arguments;
if (method.name === 'on' && method.ctor instanceof EventEmitter) {
resultArgs[1] = resultArgs[0];
err = null;
}
if (err) {
return fn(err);
}
// map the arguments using the returns description
if (returns.length > 1) {
// multiple
result = {};
returns.forEach(function(o, i) {
// map the name of the arg in the returns desc
// to the same arg in the callback
result[o.name || o.arg] = resultArgs[i + 1];
});
} else {
// single or no result...
result = resultArgs[1];
}
fn(null, result);
});
};