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