-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
74 lines (66 loc) · 1.83 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
require('dotenv').config();
const url = require('./urls');
const express = require('express');
const app = express();
app.use(require('cors')());
const port = process.env.PORT || 5000;
const server = require('http').Server(app);
const io = require('socket.io')(server, {
cors: {
origin: url,
},
rememberTransport: false,
transports: ['websocket', 'polling'],
});
const hp = require('./routes/hp');
const { addUser, getUser, deleteUser, getUsers } = require('./users');
app.use(hp);
app.use('*', (req, res, next) => {
res.status(404).json({
message: 'Route Not Found',
});
});
io.on('connection', (socket) => {
console.log('New client connected');
socket.on('join-room', ({ name, room }, callback) => {
const { user, error } = addUser(socket.id, name, room);
if (error) {
return socket.emit('nameTaken');
}
socket.join(user.room);
socket
.to(room)
.emit('notification', {
title: "Someone's here",
description: `${user.name} just entered the room`,
});
io.in(room).emit('users', getUsers(room));
});
socket.on('sendMessage', async (obj) => {
io.to(obj.room).emit('message', { user: obj.name, text: obj.msg });
});
socket.on('snap-image', async ({ imageSrc, room }) => {
io.to(room).emit('image', { imageSrc });
});
socket.on('verifyName', (obj) => {
const users = getUsers(obj.room);
const user = users && users.find((u) => u.name === obj.name);
if (user) {
socket.emit('nameTaken');
}
});
socket.on('disconnect', () => {
console.log('User disconnected');
const user = deleteUser(socket.id);
if (user) {
io.in(user.room).emit('notification', {
title: 'Someone just left',
description: `${user.name} just left the room`,
});
io.in(user.room).emit('users', getUsers(user.room));
}
});
});
server.listen(port, () => {
console.log(`listening on http://localhost:${port}`);
});