Last active
November 11, 2016 11:19
-
-
Save zdychacek/00d4853ab6856f3c6912 to your computer and use it in GitHub Desktop.
Proxy for remote method calls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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: [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
gr8