-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
62 lines (51 loc) · 2.09 KB
/
index.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
import express from 'express'
import mongodb from './src/clients/mongodb.js'
import { createServer } from 'http'
import { Server } from 'socket.io'
import path from './src/utils/path.js'
import gameApiController from './src/controllers/api/game.controller.js'
import * as gameSocketController from './src/controllers/socket/game.controller.js'
import authApiController from './src/controllers/api/authentication.controller.js'
import { getByKey as getGameByKey } from './src/services/games.js'
const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(express.static(path('/public')))
const httpServer = createServer(app);
const io = new Server(httpServer, { });
app.get('/', (req, res) => res.sendFile(path('/src/templates/home.html')))
app.get('/g/:key', (req, res) => res.sendFile(path('/src/templates/game.html')))
app.get('/404', (req, res) => res.sendFile(path('/src/templates/404.html')))
app.use('/api/login', authApiController);
app.use('/api/games', gameApiController);
io.on('connection', (socket) => {
socket.on('connected', (gameKey) => {
socket.join(`room-${gameKey}`)
})
socket.on('join', async (data) => {
const player = await gameSocketController.joinGame(data.token, data.gameKey)
if (player) {
io.to(`room-${data.gameKey}`).emit('joined', { playerUsername: player.username, game: await getGameByKey(data.gameKey) })
}
})
socket.on('start', async (data) => {
if (await gameSocketController.startGame(data.token, data.gameKey)) {
io.to(`room-${data.gameKey}`).emit('started', { game: await getGameByKey(data.gameKey) })
}
})
socket.on('shake', async (data) => {
const result = await gameSocketController.shake(data.token, data.gameKey)
if (result != false) {
io.to(`room-${data.gameKey}`).emit('shaked', { playerUsername: result.player.username, diceNumber: result.diceNumber, game: await getGameByKey(data.gameKey) })
}
})
socket.on('disconnect', () => {
//
})
})
httpServer.listen(3000, () => {
console.log(`Listening on port ${3000}`)
})
httpServer.on('close', () => {
mongodb.close()
})