-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
91 lines (77 loc) · 2.65 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
86
87
88
89
90
91
const express = require('express')
const app = express()
const http = require('http')
const server = http.createServer(app)
const { Server } = require('socket.io')
const cors = require('cors')
const io = new Server(server)
const { createClient } = require('redis')
const { v4 } = require('uuid')
const moment = require('moment')
const { json } = require('body-parser')
const { blueBright, greenBright, redBright } = require('chalk')
const client = createClient()
app.use(json())
app.use(cors())
client.on('error', console.error)
client
.connect()
.then(() => console.log(blueBright.bold('Connected to redis locally!')))
.catch(() => {
console.error(redBright.bold('Error connecting to redis'))
})
app.get('/', (req, res) => {
res.send({ msg: 'hi' })
})
app.post('/create-room-with-user', async (req, res) => {
const { username } = req.body
const roomId = v4()
await client
.hSet(`${roomId}:info`, {
created: moment(),
updated: moment(),
})
.catch((err) => {
console.error(1, err)
})
// await client.lSet(`${roomId}:users`, [])
res.status(201).send({ roomId })
})
io.on('connection', (socket) => {
socket.on('CODE_CHANGED', async (code) => {
const { roomId, username } = await client.hGetAll(socket.id)
const roomName = `ROOM:${roomId}`
// Store the current code in Redis
await client.set(`${roomId}:code`, code)
socket.to(roomName).emit('CODE_CHANGED', code)
})
socket.on('DISSCONNECT_FROM_ROOM', async ({ roomId, username }) => {})
socket.on('CONNECTED_TO_ROOM', async ({ roomId, username }) => {
await client.lPush(`${roomId}:users`, `${username}`)
await client.hSet(socket.id, { roomId, username })
const users = await client.lRange(`${roomId}:users`, 0, -1)
const roomName = `ROOM:${roomId}`
socket.join(roomName)
io.in(roomName).emit('ROOM:CONNECTION', users)
// Retrieve the current code from Redis and send it to the new user
const code = await client.get(`${roomId}:code`)
socket.emit('CODE_CHANGED', code)
})
socket.on('disconnect', async () => {
// TODO if 2 users have the same name
const { roomId, username } = await client.hGetAll(socket.id)
const users = await client.lRange(`${roomId}:users`, 0, -1)
const newUsers = users.filter((user) => username !== user)
if (newUsers.length) {
await client.del(`${roomId}:users`)
await client.lPush(`${roomId}:users`, newUsers)
} else {
await client.del(`${roomId}:users`)
}
const roomName = `ROOM:${roomId}`
io.in(roomName).emit('ROOM:CONNECTION', newUsers)
})
})
server.listen(3001,'10.101.99.227', () => {
console.log(greenBright.bold('listening on *:3001'))
})