-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
164 lines (145 loc) · 4.26 KB
/
app.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
const express = require("express");
const http = require("http");
const WebSocket = require("ws");
const cors = require("cors");
const { generateUserId } = require("./src/userId/generate");
const { leaveRoom } = require("./src/room/leave");
const { changeUserState } = require("./src/userId/changeState");
const { joinRoom } = require("./src/room/join");
const { getRoomInfo } = require("./src/room/getRoomInfo");
const { updateKeys } = require("./src/room/interaction/updateKeys");
const { guessWord } = require("./src/room/interaction/guessWord");
const { refreshRoom } = require("./src/room/refresh");
const { roomUpdate$ } = require("./src/room/rooms");
const { HTTPError } = require("./src/errors/httpError");
const { InternalServerError } = require("./src/errors/internalServerError");
const { BadRequestError } = require("./src/errors/badRequestError");
const { endTurn } = require("./src/room/interaction/endTurn");
const { ForbiddenError } = require("./src/errors/forbiddenError");
const app = express();
const port = process.env.PORT || 3000;
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const corsPass = (req, callback) => {
const corsPassOptions = {
origin: true,
};
callback(null, corsPassOptions);
};
app.use(express.json());
app.use(cors(corsPass));
app.get("/", (req, res) => {
res.redirect("https://github.com/nertc/CodeNames-Back");
});
wss.on("connection", (ws) => {
let roomId = null;
let isJoining = false;
const userId = generateUserId();
const ping = setInterval(() => ws.ping(), 10000);
const sendRoomInfo = () => {
ws.send(JSON.stringify(getRoomInfo(roomId, userId)));
};
const sendError = (err) => {
ws.send(JSON.stringify(getError(err).message));
};
ws.on("message", (data, isBinary) => {
const newRoomId = JSON.parse(isBinary ? data : data.toString()).roomId;
// Checking
if (isJoining) {
sendError(new ForbiddenError("Source is already joining a room"));
return;
}
if (typeof newRoomId !== "number") {
sendError(new BadRequestError("RoomId is NaN"));
return;
}
if (roomId === newRoomId) {
sendError(new BadRequestError("RoomId is not different"));
return;
}
isJoining = true;
// Leave
if (typeof roomId === "number") {
roomUpdate$.off(roomId, sendRoomInfo);
leaveRoom(roomId, userId);
roomId = null;
}
// Join
joinRoom(newRoomId, userId)
.then(() => {
roomUpdate$.on(newRoomId, sendRoomInfo);
roomId = newRoomId;
sendRoomInfo();
})
.catch(sendError)
.then(() => {
isJoining = false;
});
});
ws.on("close", () => {
clearInterval(ping);
if (roomId !== null) {
roomUpdate$.off(roomId, sendRoomInfo);
leaveRoom(roomId, userId);
changeUserState(userId, false);
}
});
ws.send(
JSON.stringify({
userId,
})
);
});
app.post("/room/:roomId/keys", (req, res, next) => {
const roomId = req.params.roomId;
const { userid: userId } = req.headers;
const { word, count } = req.body;
try {
updateKeys(roomId, userId, { word, count });
res.send();
} catch (err) {
next(err);
}
});
app.post("/room/:roomId/guess", (req, res, next) => {
const { roomId } = req.params;
const { userid: userId } = req.headers;
const { wordIndex } = req.body;
try {
const guess = guessWord(roomId, userId, wordIndex);
res.json(guess);
} catch (err) {
next(err);
}
});
app.post("/room/:roomId/endturn", (req, res, next) => {
const { roomId } = req.params;
const { userid: userId } = req.headers;
try {
const enemyIndex = endTurn(roomId, userId);
res.json(enemyIndex);
} catch (err) {
next(err);
}
});
app.post("/room/:roomId/refresh", (req, res, next) => {
const { roomId } = req.params;
const { userid: userId } = req.headers;
refreshRoom(roomId, userId)
.then(() => res.send())
.catch((err) => next(err));
});
function getError(err) {
if (!(err instanceof HTTPError)) {
console.error(err);
err = new InternalServerError();
}
return err;
}
app.use((err, req, res, next) => {
err = getError(err);
res.status(err.status).send(err.message);
});
server.listen(port, () => {
console.log(`CodeNames app listening on http://localhost:${port}`);
});