-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
77 lines (55 loc) · 2.13 KB
/
app.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
const path = require("path");
const express = require('express');
const socketio = require('socket.io');
const cors = require('cors');
const router = express.Router();
const { addUser, removeUser, getUser, getUsersInRoom } = require('./users');
const app = express();
const server = require('http').Server(app)
const io = socketio(server);
app.use(cors());
app.use(router);
const PORT = process.env.PORT || 8000;
if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "./client/build")));
}
app.get("/*", function (req, res) {
res.sendFile(path.join(__dirname, "/client/build/index.html"), function (err) {
if (err) {
res.status(500).send(err);
}
});
});
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Methods',
'OPTIONS, GET, POST, PUT, PATCH, DELETE'
);
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});
io.on('connect', (socket) => {
socket.on('join', ({ name, room }, callback) => {
const { error, user } = addUser({ id: socket.id, name, room });
if(error) return callback(error);
socket.join(user.room);
socket.emit('message', { user: 'AutoModerator', text: `Welcome to room #${user.room}.`});
socket.broadcast.to(user.room).emit('message', { user: 'AutoModerator', text: `${(user.name.charAt(0).toUpperCase() + user.name.slice(1))} has joined!` });
io.to(user.room).emit('roomData', { room: user.room, users: getUsersInRoom(user.room) });
callback();
});
socket.on('sendMessage', (message, callback) => {
const user = getUser(socket.id);
io.to(user.room).emit('message', { user: user.name, text: message });
callback();
});
socket.on('disconnect', () => {
const user = removeUser(socket.id);
if(user) {
io.to(user.room).emit('message', { user: 'AutoModerator', text: `${user.name} has left.` });
io.to(user.room).emit('roomData', { room: user.room, users: getUsersInRoom(user.room)});
}
})
});
server.listen(PORT, () => console.log(`Server running at port ${PORT}.`));