Skip to content

Instantly share code, notes, and snippets.

@zdychacek
Last active November 11, 2016 11:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zdychacek/00d4853ab6856f3c6912 to your computer and use it in GitHub Desktop.
Save zdychacek/00d4853ab6856f3c6912 to your computer and use it in GitHub Desktop.
Proxy for remote method calls
// require Proxy API normalization polyfill because current V8's implementation doesn't support standardized API
const Reflect = require('harmony-reflect');
function createProxy (action) {
// create the callable proxy
function _createCallableProxy (name) {
const methodNames = [ name ];
return new Proxy(function () {}, {
get (target, name, receiver) {
// push a name of the method into the accumulator
methodNames.push(name);
return receiver;
},
apply (target, name, args) {
// call the method finally
return action(methodNames.join('.'), args);
}
});
}
// create the main proxy object
return new Proxy({}, {
get (target, name) {
return _createCallableProxy(name);
}
});
}
// create a proxy
const remoteProxy = createProxy(function (methodName, args) {
console.log(`Calling a remote method "${methodName}" with arguments:`, args);
});
remoteProxy.long.path.to.method.to.call.on.remote.server(1, { actions: true });
// -> Calling a remote method "long.path.to.method.to.call.on.remote.server" with arguments: [ 1, { actions: true } ]
// the following won't affect the next `remoteProxy` call
remoteProxy.huhu;
remoteProxy.hehe.hihi;
remoteProxy.next.remote.call({ name: 'Ondrej' });
// -> Calling a remote method "next.remote.call" with arguments: [ { name: 'Ondrej' } ]
const a = remoteProxy.method1;
const b = remoteProxy.method2;
a();
// -> Calling a remote method "method1" with arguments: []
@arkhan19
Copy link

arkhan19 commented Aug 8, 2014

gr8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment