Skip to content

Commit 242b222

Browse files
committed
Set up matching web socket
1 parent 53e0926 commit 242b222

File tree

8 files changed

+553
-47
lines changed

8 files changed

+553
-47
lines changed

backend/matching-service/package-lock.json

Lines changed: 209 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

backend/matching-service/package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
"cors": "^2.8.5",
1717
"dotenv": "^16.4.5",
1818
"express": "^4.21.1",
19+
"socket.io": "^4.8.0",
1920
"swagger-ui-express": "^5.0.1",
2021
"yaml": "^2.5.1"
2122
},
@@ -25,6 +26,7 @@
2526
"@types/express": "^5.0.0",
2627
"@types/jest": "^29.5.13",
2728
"@types/node": "^22.7.5",
29+
"@types/socket.io": "^3.0.2",
2830
"@types/supertest": "^6.0.2",
2931
"@types/swagger-ui-express": "^4.1.6",
3032
"cross-env": "^7.0.3",

backend/matching-service/server.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
1+
import http from "http";
12
import app from "./app.ts";
3+
import Websocket from "./src/websocket/websocket.ts";
4+
import { handleMatchRequest } from "./src/websocket/websocketHandlers.ts";
5+
6+
const server = http.createServer(app);
7+
const io = Websocket.getInstance(server);
8+
io.initSocketHandlers([{ path: "/matching", handler: handleMatchRequest }]);
29

310
const PORT = process.env.PORT || 3002;
411

512
if (process.env.NODE_ENV !== "test") {
6-
app.listen(PORT, () => {
13+
server.listen(PORT, () => {
714
console.log(
815
`Matching service server listening on http://localhost:${PORT}`
916
);
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import http from "http";
2+
import { Server, Socket } from "socket.io";
3+
4+
// Adapted from https://dev.to/nickfelix/how-to-implement-socketio-using-typescript-3ne2
5+
const WEBSOCKET_CORS = {
6+
origin: "*",
7+
methods: ["GET", "POST"],
8+
};
9+
10+
interface MatchRequestParams {
11+
user: string;
12+
complexities: string[];
13+
categories: string[];
14+
languages: string[];
15+
timeout: number;
16+
}
17+
18+
class Websocket extends Server {
19+
private static io: Websocket;
20+
21+
constructor(server: http.Server) {
22+
super(server, {
23+
cors: WEBSOCKET_CORS,
24+
});
25+
}
26+
27+
public static getInstance(server: http.Server): Websocket {
28+
if (!Websocket.io) {
29+
Websocket.io = new Websocket(server);
30+
}
31+
32+
return Websocket.io;
33+
}
34+
35+
public initSocketHandlers(socketHandlers: Array<any>) {
36+
socketHandlers.forEach((element) => {
37+
Websocket.io.of(element.path, (socket: Socket) => {
38+
element.handler(socket);
39+
});
40+
});
41+
}
42+
}
43+
44+
export default Websocket;

0 commit comments

Comments
 (0)