1 | var Websocket = require('./websocket')
|
2 |
|
3 | class Router {
|
4 | constructor (port, service, opt, initCallback) {
|
5 | this.opt = opt
|
6 | this.port = port
|
7 | this.service = service
|
8 | this.initCallback = initCallback
|
9 | }
|
10 |
|
11 | start () {
|
12 | var websocket = new Websocket(this.port, this.opt)
|
13 | this.websocket = websocket
|
14 | this.websocket.start((message) => {
|
15 | this.call(message.id, message.service, message.fn, message.args)
|
16 | })
|
17 | if (this.initCallback) this.initCallback(this.websocket)
|
18 | return function () {
|
19 | if (websocket) {
|
20 | websocket.close()
|
21 | }
|
22 | }
|
23 | }
|
24 |
|
25 | call (callid, name, fn, args) {
|
26 | try {
|
27 | this.service[fn](args, (error, data) => {
|
28 | var response = {
|
29 | id: callid,
|
30 | type: 'reply',
|
31 | scope: name,
|
32 | result: data,
|
33 | error: error
|
34 | }
|
35 | this.websocket.send(JSON.stringify(response))
|
36 | })
|
37 | } catch (e) {
|
38 | var msg = 'Unexpected Error ' + e.message
|
39 | console.log('\x1b[31m%s\x1b[0m', '[ERR] ' + msg)
|
40 | if (this.websocket) {
|
41 | this.websocket.send(JSON.stringify({
|
42 | id: callid,
|
43 | type: 'reply',
|
44 | scope: name,
|
45 | error: msg
|
46 | }))
|
47 | }
|
48 | }
|
49 | }
|
50 | }
|
51 |
|
52 | module.exports = Router
|