-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.js
55 lines (44 loc) · 1.88 KB
/
server.js
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
// Replace process.env variables with variables in .env file during development
require('dotenv').config();
// Import dependencies
const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const path = require('path');
const router = require('./router');
const mongoose = require('mongoose');
const {startAllCron} = require('./cron/cron-startup');
// Call io module with io instance
require('./socket/broadcast-socket')(io);
// If app is in dev mode
if (process.env.NODE_ENV !== 'production') {
// Inform developer to use React's localhost port when testing server
app.get('/', (req, res) => res.status(200).send(`Looks like you are in development mode: Back-end is now listening on port ${process.env.PORT}. Please start front-end server and use while testing the app (http://localhost:3000)`));
}
// Parse API requests as JSON
app.use(express.json());
// For api requests, rout them through router file
app.use(router);
// Serve static files (index.html) from from build folder
app.use(express.static(path.join(__dirname, 'client/build')));
// Leverage React routing, return requests to React
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
// Connect to MongoDB and listen for new requests
http.listen(process.env.PORT, async (req, res) => { // eslint-disable-line no-unused-vars
try {
await mongoose.connect(process.env.MONGO_DB, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
});
// Finds all broadcasts in DB and start their timers
await startAllCron();
console.log(`Drivel server connected to DB - listening on port: ${process.env.PORT}`);
} catch (error) {
console.log('Could not connect to database', error); // eslint-disable-line no-console
}
});