-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket.ts
63 lines (54 loc) · 1.42 KB
/
socket.ts
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
import { NextRequest } from 'next/server'
import { Server } from 'socket.io'
import { PORT } from '@/const/socketConstants'
import { loadGameForPlayer } from '@/lib/sqliteDb'
import {
ClientToServerEvents,
InterServerEvents,
NextApiResponseWithSocket,
ServerToClientEvents,
SocketData,
} from '@/types/socketTypes'
import onSocketConnection from '../../lib/onSocketConnection'
export const config = {
api: {
externalResolver: true,
},
}
export default async function handler(
_: NextRequest,
res: NextApiResponseWithSocket,
) {
if (res.socket.server.io) {
console.log('Server already started!')
res.end()
return
}
const io = new Server<
ClientToServerEvents,
ServerToClientEvents,
InterServerEvents,
SocketData
>({
path: '/api/socket',
addTrailingSlash: false,
cors: { origin: '*' },
}).listen(PORT + 1)
res.socket.server.io = io
// Register a Middleware to load a Game for a given session ID (player ID)
// and prefill socket.data.
io.use(async (socket, next) => {
const sessionId = socket.handshake.auth.sessionId
if (sessionId) {
const gameState = await loadGameForPlayer(sessionId)
socket.data.sessionId = sessionId
if (gameState?.id !== -1) {
socket.data.gameState = gameState
}
}
return next()
})
io.on('connection', onSocketConnection)
console.log('Socket server started successfully!')
res.end()
}