Matteo Scandolo | bd13aab | 2017-08-08 13:05:24 -0700 | [diff] [blame] | 1 | |
| 2 | /* |
| 3 | * Copyright 2017-present Open Networking Foundation |
| 4 | |
| 5 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | * you may not use this file except in compliance with the License. |
| 7 | * You may obtain a copy of the License at |
| 8 | |
| 9 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | |
| 11 | * Unless required by applicable law or agreed to in writing, software |
| 12 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | * See the License for the specific language governing permissions and |
| 15 | * limitations under the License. |
| 16 | */ |
| 17 | |
| 18 | |
Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 19 | (function () { |
| 20 | 'use strict'; |
| 21 | |
| 22 | const express = require('express'); |
| 23 | const app = express(); |
| 24 | const config = require('./config/config.js').gateway; |
| 25 | const bodyParser = require('body-parser'); |
| 26 | const cors = require('cors'); |
| 27 | const socketIo = require('./controllers/websocket.js'); |
| 28 | const logger = require('./config/logger.js'); |
| 29 | |
| 30 | // Apply middlewares |
| 31 | app.use(cors()); |
| 32 | app.use(bodyParser.json()); |
| 33 | |
Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 34 | app.get('/', function(req, res) { |
Matteo Scandolo | f64cdd5 | 2017-02-24 07:52:49 -0800 | [diff] [blame] | 35 | res.send('Welcome to the websocket server for XOS'); |
Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 36 | }); |
| 37 | |
Matteo Scandolo | f05d8a6 | 2016-12-06 13:36:49 -0800 | [diff] [blame] | 38 | const startServer = (port) => { |
Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 39 | |
| 40 | // if is running just return it |
| 41 | if(app.server) { |
| 42 | return app.server; |
| 43 | } |
| 44 | |
Matteo Scandolo | f05d8a6 | 2016-12-06 13:36:49 -0800 | [diff] [blame] | 45 | const server = app.listen(port || config.port, function() { |
| 46 | logger.info(`Express is listening to http://localhost:${port || config.port}`); |
Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 47 | |
| 48 | // once server is ready setup WebSocket |
| 49 | socketIo.create(server); |
| 50 | |
| 51 | // start redis |
| 52 | require('./controllers/redis.js'); |
| 53 | }); |
| 54 | app.server = server; |
| 55 | return server; |
| 56 | }; |
| 57 | |
| 58 | const stopServer = () => { |
| 59 | if(app.server) { |
| 60 | app.server.close(); |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | if(!module.parent) { |
| 65 | startServer(); |
| 66 | } |
| 67 | |
| 68 | module.exports = { |
| 69 | app: app, |
| 70 | start: startServer, |
| 71 | stop: stopServer |
| 72 | }; |
| 73 | })(); |