A different way of thinking of web client-server RPC
MIT License
ByProxy allows the client to access an object or module on the server as if it were a local object. The object's API can then be invoked directly on the client.
For example, a calculator server:
On the server:
class Calculator {
constructor() {
this.opCount = 0;
}
add(a, b) {
this.opCount++;
return a + b;
}
subtract(a, b) {
this.opCount++;
return a - b;
}
}
// Serve an instance of Calculator via Express
byproxy.serve(app, '/calculator', new Calculator());
On the client:
const calculator = byproxy.link('/calculator');
const sum = await calculator.add(2, 6); // 8
const diff = await calculator.subtract(6, 2); // 4
console.log(await calculator.opCount); // 2
const mymod = require('my-awesome-mod');
byproxy.serve(app, '/updater', mymod);
Server:
byproxy.serve(app, '/hello', function (name) {
return 'Hello ' + name + '!';
});
Client:
const hello = byproxy.link('/hello');
console.log(await hello('John')); // Hello John!
Server:
byproxy.serve(app, '/updater', {
async delayedUpdate() {
return new Promise(........);
}
});
Client:
const result = await updater.delayedUpdate();
Since everything is a promise, the promise is rejected when the server returns and error code. The body of the response is in the error message and error.code
will give you the status code of the rest call.
For most cases, when using async-await
, simply catch the error
const calculator = byproxy.link('/calculator');
try {
const x = await calculator.divide(10, 0); // div by 0 error
} catch (err) {
console.error(err);
}
ByProxy is composed of two modules byproxy-serve
for the server and byproxy-link
for the client.
They are both available on NPM.
npm install --save byproxy-serve
npm install --save byproxy-link
Note: ByProxy is not a rest library. It integrates with Express on the server. There is no dependency required on the client.
ByProxy demo project is a simple example.