Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 1 | (function () { |
| 2 | 'use strict'; |
| 3 | |
| 4 | const express = require('express'); |
| 5 | const app = express(); |
| 6 | const config = require('./config/config.js').gateway; |
| 7 | const bodyParser = require('body-parser'); |
| 8 | const cors = require('cors'); |
| 9 | const socketIo = require('./controllers/websocket.js'); |
| 10 | const logger = require('./config/logger.js'); |
| 11 | |
| 12 | // Apply middlewares |
| 13 | app.use(cors()); |
| 14 | app.use(bodyParser.json()); |
| 15 | |
| 16 | // Load routes |
Matteo Scandolo | f64cdd5 | 2017-02-24 07:52:49 -0800 | [diff] [blame] | 17 | // require('./routes/core_proxy.js')(app); |
Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 18 | |
| 19 | app.get('/', function(req, res) { |
Matteo Scandolo | f64cdd5 | 2017-02-24 07:52:49 -0800 | [diff] [blame] | 20 | res.send('Welcome to the websocket server for XOS'); |
Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 21 | }); |
| 22 | |
Matteo Scandolo | f05d8a6 | 2016-12-06 13:36:49 -0800 | [diff] [blame] | 23 | const startServer = (port) => { |
Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 24 | |
| 25 | // if is running just return it |
| 26 | if(app.server) { |
| 27 | return app.server; |
| 28 | } |
| 29 | |
Matteo Scandolo | f05d8a6 | 2016-12-06 13:36:49 -0800 | [diff] [blame] | 30 | const server = app.listen(port || config.port, function() { |
| 31 | logger.info(`Express is listening to http://localhost:${port || config.port}`); |
Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 32 | |
| 33 | // once server is ready setup WebSocket |
| 34 | socketIo.create(server); |
| 35 | |
| 36 | // start redis |
| 37 | require('./controllers/redis.js'); |
| 38 | }); |
| 39 | app.server = server; |
| 40 | return server; |
| 41 | }; |
| 42 | |
| 43 | const stopServer = () => { |
| 44 | if(app.server) { |
| 45 | app.server.close(); |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | if(!module.parent) { |
| 50 | startServer(); |
| 51 | } |
| 52 | |
| 53 | module.exports = { |
| 54 | app: app, |
| 55 | start: startServer, |
| 56 | stop: stopServer |
| 57 | }; |
| 58 | })(); |