-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
59 lines (50 loc) · 1.58 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
import { createServer } from 'http';
import { Server } from 'socket.io';
import { v4 as uuidv4 } from 'uuid';
import { config } from 'dotenv';
config()
const origin = process.env.ORIGIN;
if (!origin) throw new Error('This program requires a valid CORS origin value in an environment variable called `ORIGIN` see cors package for more information https://github.com/expressjs/cors#readme')
const app = createServer();
const io = new Server(app, {
cors: {
origin: eval(origin),
credentials: true
}
});
const getRandom = (max) => {
return Math.floor(Math.random() * (max) + 1);
}
io.on('connection', (socket) => {
socket.on("connect_error", (err) => {
console.log(`Connection error due to ${err.message}`);
});
socket.on('join game', data => {
console.log(`ID: ${socket.id} | Name: "${data.name}" has joined game "${data.game}"`);
socket.join(data.game);
});
socket.on('leave game', data => {
console.log(`ID: ${socket.id} | Name: "${data.name}" has left game "${data.game}"`);
socket.leave(data.game)
});
socket.on('new roll', data => {
const diceThrow = data.dice.map((die) => {
const newRoll = getRandom(die);
return {
id: `${uuidv4()}`,
d: die,
value: newRoll
}
})
const res = {
game: data.game,
name: data.name || 'Anon',
roll: diceThrow,
mod: data.mod,
total: diceThrow.reduce((sum, roll) => sum + roll.value, 0) + data?.mod
}
console.dir(res, { depth: null });
io.sockets.to(data.game).emit('receive roll', res)
});
});
app.listen(process.env.PORT ?? 8080);