-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.js
74 lines (58 loc) · 1.91 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
const express = require('express'),
morgan = require('morgan'),
path = require('path'),
http = require('http'),
{ Server } = require('socket.io'),
mongoose = require('mongoose'),
routes = require('./routes'),
handlers = require('./handlers');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 8888;
const server = http.createServer(app);
const io = new Server(server, {
cors: { origin: '*', methods: ['GET', 'POST'] }
});
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(morgan('tiny'));
app.use(routes);
mongoose
.connect(process.env.MONGODB_ATLAS_URI || 'mongodb://localhost/playlistr', {
useNewUrlParser: true, // Removes deprecation warning
useUnifiedTopology: true
})
.catch(err => console.log(err));
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, '/client/build', 'index.html'));
});
}
io.on('connection', socket => {
console.log('Client connected to server:', socket.id);
socket.on('join room', (roomId, user) => {
handlers.addUser(roomId, user, socket);
socket.join(roomId);
socket.to(roomId).emit('user status', {
text: `${user.name} joined...`,
roomId,
user
});
const currentUsers = handlers.getUsersInRoom(roomId);
io.in(roomId).emit('current users', currentUsers);
});
socket.on('host song', ({ song, roomId }) => {
socket.emit('room song', song);
});
socket.on('disconnect', () => {
const user = handlers.removeUser(socket);
if (user) {
io.to(user.room).emit('user status', { text: `${user.name} left...` });
io.to(user.room).emit('current users', handlers.getUsersInRoom(user.room));
console.log('Client disconnected from server: ', user.socketId);
}
});
});
console.log(`Listening on port ${port}.`);
server.listen(port);