-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
86 lines (72 loc) · 2.23 KB
/
index.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import express from "express";
import bodyParser from "body-parser";
import cors from "cors";
import { createServer } from "http";
import { Server, Socket } from "socket.io";
import { originUrls, serverPort } from "./constants/runtime.js";
import signupRouter from "./routers/user.js";
import pushRouter from "./routers/push.js";
import { router as loginRouter } from "./auth/router.js";
import gameRouterFactory from "./routers/game.js";
import { archiveOldGames } from "./services/lobby.js";
import { sendActiveGameNotifications } from "./services/mail.js";
import { removePlayerClient } from "./socketClients.js";
import handlers from "./handlers.js";
import User from "./models/user";
interface ServerToClientEvents {
message: (message: { type: string; payload }) => void;
}
interface ClientToServerEvents {
message: (message: { type: string; payload }) => void;
disconnect: () => void;
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface InterServerEvents {}
interface SocketData {
playerId: number;
gameId: number;
user: User;
}
export type MyServer = Server<
ClientToServerEvents,
ServerToClientEvents,
InterServerEvents,
SocketData
>;
export type MySocket = Socket<
ClientToServerEvents,
ServerToClientEvents,
InterServerEvents,
SocketData
>;
const app = express();
const http = createServer(app);
const webSocketsServer: MyServer = new Server(http, {
path: "/socket",
cors: {
origin: originUrls,
},
});
const bodyParserMiddleware = bodyParser.json();
const corsMiddleware = cors();
app.use(corsMiddleware);
app.use(bodyParserMiddleware);
const gameRouter = gameRouterFactory(webSocketsServer);
app.use(signupRouter);
app.use(loginRouter);
app.use(gameRouter);
app.use(pushRouter);
webSocketsServer.on("connection", async (socket) => {
socket.data.playerId = -1;
socket.on("message", (message) => {
handlers[message.type](webSocketsServer, socket, message.payload);
});
socket.on("disconnect", () => {
removePlayerClient(socket);
});
});
http.listen(serverPort, () => console.log(`Listening on port: ${serverPort}`));
archiveOldGames();
setInterval(archiveOldGames, 1000 * 60 * 60 * 24);
sendActiveGameNotifications();
setInterval(sendActiveGameNotifications, 1000 * 60 * 60 * 24);