-
Notifications
You must be signed in to change notification settings - Fork 505
/
server.js
85 lines (67 loc) · 2.16 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
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
84
85
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const socket = require('socket.io');
const config = require('./config/configs');
// Use Node's default promise instead of Mongoose's promise library
mongoose.Promise = global.Promise;
// Connect to the database
mongoose.connect(config.db);
let db = mongoose.connection;
db.on('open', () => {
console.log('Connected to the database.');
});
db.on('error', (err) => {
console.log(`Database error: ${err}`);
});
// Instantiate express
const app = express();
// Don't touch this if you don't know it
// We are using this for the express-rate-limit middleware
// See: https://github.com/nfriedly/express-rate-limit
app.enable('trust proxy');
// Set public folder using built-in express.static middleware
app.use(express.static('public'));
// Set body parser middleware
app.use(bodyParser.json());
// Enable cross-origin access through the CORS middleware
// NOTICE: For React development server only!
if (process.env.CORS) {
app.use(cors());
}
// Initialize routes middleware
app.use('/api/users', require('./routes/users'));
// Use express's default error handling middleware
app.use((err, req, res, next) => {
if (res.headersSent) return next(err);
res.status(400).json({ err: err });
});
// Start the server
const port = process.env.PORT || 3000;
const server = app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
// Set up socket.io
const io = socket(server,{
cors:{
origin: config.react_app_url,
}
});
let online = 0;
io.on('connection', (socket) => {
online++;
console.log(`Socket ${socket.id} connected.`);
console.log(`Online: ${online}`);
io.emit('visitor enters', online);
socket.on('add', data => socket.broadcast.emit('add', data));
socket.on('update', data => socket.broadcast.emit('update', data));
socket.on('delete', data => socket.broadcast.emit('delete', data));
socket.on('disconnect', () => {
online--;
console.log(`Socket ${socket.id} disconnected.`);
console.log(`Online: ${online}`);
io.emit('visitor exits', online);
});
});