UNPKG

1.59 kBJavaScriptView Raw
1var eve = require('../../index');
2
3function RPCAgent(id) {
4 // execute super constructor
5 eve.Agent.call(this, id);
6
7 this.foo = 'bar';
8 this.count = 0;
9
10 // extend the agent with RPC functionality
11 this.rpc = this.loadModule('rpc', this.rpcFunctions, {timeout:2000}); // option 1
12
13 this.rpc = this.loadModule('rpc', {methods: this.rpcFunctions, timeout:2000}); // option 1
14
15 // alternative ways to load the RPC module:
16 // this.rpc = this.loadModule('rpc', {add: this.rpcFunctions.add}); // option 2
17 // this.rpc = this.loadModule('rpc', {minus: this.minus}); // option 3
18 // this.rpc = this.loadModule('rpc', ['minus']); // option 4
19
20 // connect to all transports provided by the system
21 this.connect(eve.system.transports.getAll());
22}
23
24// extend the eve.Agent prototype
25RPCAgent.prototype = Object.create(eve.Agent.prototype);
26RPCAgent.prototype.constructor = RPCAgent;
27
28// this is used when loading rpc with options 3 and 4
29RPCAgent.prototype.minus = function (params, sender) {
30 return params.a - params.b;
31};
32
33// define RPC functions, preferably in a separated object to clearly distinct
34// exposed functions from local functions.
35RPCAgent.prototype.rpcFunctions = {};
36RPCAgent.prototype.rpcFunctions.add = function (params, sender) {
37 return params.a + params.b;
38};
39
40RPCAgent.prototype.askToAdd = function (to, params) {
41 var message = {method: 'add', params: params};
42 this.rpc.request(to, message).then(function (reply) {
43 console.log('The agent told me that', params.a, '+', params.b, '=', reply);
44 });
45};
46
47module.exports = RPCAgent;