Commit | Line | Data |
---|---|---|
47e22477 JB |
1 | const RoboHydraHead = require('robohydra').heads.RoboHydraHead; |
2 | const RoboHydraWebSocketHead = require('robohydra').heads.RoboHydraWebSocketHead; | |
3 | const RoboHydraWebSocketHeadProxy = require('robohydra').heads.RoboHydraWebSocketHeadProxy; | |
4 | ||
e7aeea18 | 5 | exports.getBodyParts = function (conf) { |
47e22477 JB |
6 | let wsSocket; |
7 | return { | |
8 | heads: [ | |
9 | new RoboHydraHead({ | |
10 | name: 'message', | |
11 | path: '/message', | |
12 | method: 'POST', | |
e7aeea18 | 13 | handler: function (req, res) { |
47e22477 JB |
14 | const msg = JSON.stringify(req.body); |
15 | if (wsSocket) { | |
16 | wsSocket.send(msg); | |
17 | res.send('Message sent'); | |
18 | } else { | |
19 | res.send('Cannot send message, no opened websocket found'); | |
20 | } | |
e7aeea18 | 21 | }, |
47e22477 JB |
22 | }), |
23 | ||
24 | new RoboHydraHead({ | |
25 | name: 'close', | |
26 | path: '/close', | |
27 | method: 'GET', | |
e7aeea18 | 28 | handler: function (req, res) { |
47e22477 JB |
29 | if (wsSocket) { |
30 | wsSocket.close(); | |
31 | res.send('Websocket closed'); | |
32 | } else { | |
33 | res.send('Cannot close websocket, no opened websocket found'); | |
34 | } | |
e7aeea18 | 35 | }, |
47e22477 JB |
36 | }), |
37 | ||
38 | new RoboHydraWebSocketHeadProxy({ | |
39 | name: 'proxy', | |
40 | mountPath: '/proxy', | |
41 | proxyTo: 'ws://server.example.com', | |
e7aeea18 | 42 | preProcessor: function (data) { |
47e22477 JB |
43 | console.log('From the client: ' + data); |
44 | }, | |
e7aeea18 | 45 | postProcessor: function (data) { |
47e22477 | 46 | console.log('From the server: ' + data); |
e7aeea18 | 47 | }, |
47e22477 JB |
48 | }), |
49 | ||
50 | new RoboHydraWebSocketHead({ | |
51 | name: 'WS Server', | |
52 | path: '/.*', | |
e7aeea18 | 53 | handler: function (req, socket) { |
47e22477 | 54 | wsSocket = socket; |
e7aeea18 JB |
55 | }, |
56 | }), | |
57 | ], | |
47e22477 JB |
58 | }; |
59 | }; |