-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathserver.js
More file actions
83 lines (75 loc) · 2.35 KB
/
Copy pathserver.js
File metadata and controls
83 lines (75 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
'use strict';
const express = require('express');
const app = express();
const http = require('http');
const cors = require('cors');
const session = require('express-session');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const expressSwagger = require('express-swagger-generator')(app);
const srvConfig = require('./config');
const mongoose = require('mongoose');
const {CONNECTION_TYPE, DB_HOST, DB_USERNAME, DB_PASSWORD, DB_PORT, DB_NAME, DB_QUERY_PARAMS} = srvConfig;
const dbAuthString = (DB_USERNAME && DB_PASSWORD) ? `${srvConfig.DB_USERNAME}:${srvConfig.DB_PASSWORD}@` : '';
let httpServer;
/**
* Configure middleware
*/
app.use(
cors({
// origin: `http://localhost:${srvConfig.SERVER_PORT}`,
origin: function (origin, callback) {
return callback(null, true)
},
optionsSuccessStatus: 200,
credentials: true
}),
session({
saveUninitialized: true,
secret: srvConfig.SESSION_SECRET,
resave: true
}),
cookieParser(),
bodyParser.json()
);
/**
* Include all API Routes
*/
app.use('/api', require('./routes/api'));
/**
* Swagger UI documentation
*/
if (srvConfig.SWAGGER_SETTINGS.enableSwaggerUI)
expressSwagger(srvConfig.SWAGGER_SETTINGS);
/**
* Configure http(s)Server
*/
if (srvConfig.HTTPS_ENABLED) {
const privateKey = fs.readFileSync(srvConfig.PRIVATE_KEY_PATH, 'utf8');
const certificate = fs.readFileSync(srvConfig.CERTIFICATE_PATH, 'utf8');
const ca = fs.readFileSync(srvConfig.CA_PATH, 'utf8');
// Create a HTTPS server
httpServer = https.createServer({key: privateKey, cert: certificate, ca: ca}, app);
} else {
// Create a HTTP server
httpServer = http.createServer({}, app);
}
/**
* Start http server & connect to MongoDB
*/
httpServer.listen(srvConfig.SERVER_PORT, () => {
mongoose.connect(`${CONNECTION_TYPE}://${dbAuthString}${DB_HOST}:${DB_PORT}/${DB_NAME}${DB_QUERY_PARAMS}`, {
useNewUrlParser: true,
useUnifiedTopology: true
}, () => {
console.log(`Server started on port ${srvConfig.SERVER_PORT}`);
});
});
/**
* Socket.io section
*/
const io = require('socket.io')(httpServer);
io.on('connection', function (socket) {
console.log(`New connection: ${socket.id}`);
socket.on('disconnect', () => console.log(`Connection left (${socket.id})`));
});