mirror of
https://github.com/randyjc/Rahoot.git
synced 2026-03-14 04:25:35 +01:00
feat: improve reconnect, add ESLint configuration for common and socket
This commit is contained in:
208
packages/socket/eslint.config.mjs
Normal file
208
packages/socket/eslint.config.mjs
Normal file
@@ -0,0 +1,208 @@
|
||||
import js from "@eslint/js"
|
||||
import { defineConfig } from "eslint/config"
|
||||
import globals from "globals"
|
||||
import tseslint from "typescript-eslint"
|
||||
|
||||
export default defineConfig([
|
||||
{
|
||||
ignores: ["**/node_modules/**", "**/dist/**"],
|
||||
},
|
||||
{
|
||||
files: ["**/*.ts"],
|
||||
languageOptions: {
|
||||
...js.configs.recommended.languageOptions,
|
||||
parser: tseslint.parser,
|
||||
parserOptions: {
|
||||
projectService: true,
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
globals: {
|
||||
...globals.node,
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
"@typescript-eslint": tseslint.plugin,
|
||||
},
|
||||
rules: {
|
||||
...js.configs.recommended.rules,
|
||||
...tseslint.configs.recommendedTypeChecked[0].rules,
|
||||
|
||||
"array-callback-return": [
|
||||
"error",
|
||||
{ allowImplicit: false, checkForEach: true, allowVoid: true },
|
||||
],
|
||||
"no-await-in-loop": "error",
|
||||
"no-constant-binary-expression": "error",
|
||||
"no-constructor-return": "error",
|
||||
"no-duplicate-imports": ["error", { includeExports: true }],
|
||||
"no-new-native-nonconstructor": "error",
|
||||
"no-promise-executor-return": ["error", { allowVoid: true }],
|
||||
"no-self-compare": "error",
|
||||
"no-template-curly-in-string": "error",
|
||||
"no-unmodified-loop-condition": "error",
|
||||
"no-unreachable-loop": "error",
|
||||
"no-unused-private-class-members": "error",
|
||||
"arrow-body-style": ["error", "as-needed"],
|
||||
camelcase: [
|
||||
"error",
|
||||
{
|
||||
properties: "always",
|
||||
ignoreDestructuring: true,
|
||||
ignoreImports: true,
|
||||
ignoreGlobals: true,
|
||||
},
|
||||
],
|
||||
"capitalized-comments": [
|
||||
"error",
|
||||
"always",
|
||||
{ ignoreConsecutiveComments: true },
|
||||
],
|
||||
"class-methods-use-this": ["error", { enforceForClassFields: true }],
|
||||
complexity: ["warn", 40],
|
||||
"consistent-return": "error",
|
||||
curly: ["error", "all"],
|
||||
"default-param-last": "error",
|
||||
"dot-notation": "error",
|
||||
eqeqeq: ["error", "always"],
|
||||
"func-name-matching": "error",
|
||||
"func-names": "error",
|
||||
"func-style": ["error", "declaration", { allowArrowFunctions: true }],
|
||||
"grouped-accessor-pairs": ["error", "getBeforeSet"],
|
||||
"guard-for-in": "error",
|
||||
"init-declarations": ["error", "always"],
|
||||
"logical-assignment-operators": [
|
||||
"error",
|
||||
"always",
|
||||
{ enforceForIfStatements: true },
|
||||
],
|
||||
"max-classes-per-file": ["error", { ignoreExpressions: true }],
|
||||
"max-depth": ["error", 3],
|
||||
"max-lines": [
|
||||
"error",
|
||||
{ max: 500, skipBlankLines: true, skipComments: true },
|
||||
],
|
||||
"max-nested-callbacks": ["error", 3],
|
||||
"max-params": ["error", 4],
|
||||
"multiline-comment-style": ["error", "separate-lines"],
|
||||
"no-alert": "error",
|
||||
"no-bitwise": "error",
|
||||
"no-caller": "error",
|
||||
"no-else-return": "error",
|
||||
"no-empty-function": "error",
|
||||
"no-empty-static-block": "error",
|
||||
"no-eq-null": "error",
|
||||
"no-eval": "error",
|
||||
"no-extend-native": "error",
|
||||
"no-extra-label": "error",
|
||||
"no-implicit-coercion": "error",
|
||||
"no-implicit-globals": "error",
|
||||
"no-implied-eval": "error",
|
||||
"no-inline-comments": "error",
|
||||
"no-invalid-this": "error",
|
||||
"no-iterator": "error",
|
||||
"no-labels": "error",
|
||||
"no-lone-blocks": "error",
|
||||
"no-lonely-if": "error",
|
||||
"no-loop-func": "error",
|
||||
"no-multi-assign": "error",
|
||||
"no-multi-str": "error",
|
||||
"no-nested-ternary": "error",
|
||||
"no-new": "error",
|
||||
"no-new-func": "error",
|
||||
"no-new-wrappers": "error",
|
||||
"no-object-constructor": "error",
|
||||
"no-octal-escape": "error",
|
||||
"no-param-reassign": "error",
|
||||
"no-plusplus": "error",
|
||||
"no-proto": "error",
|
||||
"no-return-assign": ["error", "always"],
|
||||
"no-script-url": "error",
|
||||
"no-sequences": "error",
|
||||
"no-throw-literal": "error",
|
||||
"no-undef-init": "error",
|
||||
"no-unneeded-ternary": ["error", { defaultAssignment: false }],
|
||||
"no-unused-expressions": ["error", { enforceForJSX: true }],
|
||||
"no-unused-vars": ["error", { argsIgnorePattern: "^_" }],
|
||||
"no-useless-call": "error",
|
||||
"no-useless-computed-key": ["error", { enforceForClassMembers: true }],
|
||||
"no-useless-concat": "error",
|
||||
"no-useless-constructor": "error",
|
||||
"no-useless-rename": "error",
|
||||
"no-useless-return": "error",
|
||||
"no-var": "error",
|
||||
"no-warning-comments": ["error", { terms: ["todo"] }],
|
||||
"object-shorthand": ["error", "always"],
|
||||
"one-var": ["error", "never"],
|
||||
"operator-assignment": ["error", "always"],
|
||||
"prefer-arrow-callback": "error",
|
||||
"prefer-const": [
|
||||
"error",
|
||||
{ destructuring: "any", ignoreReadBeforeAssign: false },
|
||||
],
|
||||
"prefer-destructuring": "error",
|
||||
"prefer-exponentiation-operator": "error",
|
||||
"prefer-numeric-literals": "error",
|
||||
"prefer-object-has-own": "error",
|
||||
"prefer-object-spread": "error",
|
||||
"prefer-promise-reject-errors": "error",
|
||||
"prefer-regex-literals": ["error", { disallowRedundantWrapping: true }],
|
||||
"prefer-rest-params": "error",
|
||||
"prefer-spread": "error",
|
||||
"prefer-template": "error",
|
||||
radix: "error",
|
||||
"require-await": "error",
|
||||
"require-unicode-regexp": "error",
|
||||
"symbol-description": "error",
|
||||
yoda: "error",
|
||||
"line-comment-position": ["error", { position: "above" }],
|
||||
indent: "off",
|
||||
"newline-before-return": "error",
|
||||
"no-undef": "error",
|
||||
"padded-blocks": ["error", "never"],
|
||||
"padding-line-between-statements": [
|
||||
"error",
|
||||
{
|
||||
blankLine: "always",
|
||||
prev: "*",
|
||||
next: [
|
||||
"break",
|
||||
"case",
|
||||
"cjs-export",
|
||||
"class",
|
||||
"continue",
|
||||
"do",
|
||||
"if",
|
||||
"switch",
|
||||
"try",
|
||||
"while",
|
||||
"return",
|
||||
],
|
||||
},
|
||||
{
|
||||
blankLine: "always",
|
||||
prev: [
|
||||
"break",
|
||||
"case",
|
||||
"cjs-export",
|
||||
"class",
|
||||
"continue",
|
||||
"do",
|
||||
"if",
|
||||
"switch",
|
||||
"try",
|
||||
"while",
|
||||
"return",
|
||||
],
|
||||
next: "*",
|
||||
},
|
||||
],
|
||||
quotes: [
|
||||
"error",
|
||||
"double",
|
||||
{ avoidEscape: true, allowTemplateLiterals: true },
|
||||
],
|
||||
"space-before-blocks": "error",
|
||||
semi: ["error", "never"],
|
||||
},
|
||||
},
|
||||
])
|
||||
@@ -5,7 +5,8 @@
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "node esbuild.config.js",
|
||||
"start": "node dist/index.cjs"
|
||||
"start": "node dist/index.cjs",
|
||||
"lint": "eslint"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
@@ -13,12 +14,18 @@
|
||||
"dependencies": {
|
||||
"@rahoot/common": "workspace:*",
|
||||
"@t3-oss/env-core": "^0.13.8",
|
||||
"dayjs": "^1.11.18",
|
||||
"socket.io": "^4.8.1",
|
||||
"uuid": "^13.0.0",
|
||||
"zod": "^4.1.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.38.0",
|
||||
"@types/node": "^24.8.1",
|
||||
"esbuild": "^0.25.10",
|
||||
"tsx": "^4.20.6"
|
||||
"eslint": "^9",
|
||||
"globals": "^16.4.0",
|
||||
"tsx": "^4.20.6",
|
||||
"typescript-eslint": "^8.46.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,30 +1,28 @@
|
||||
import { Server } from "@rahoot/common/types/game/socket"
|
||||
import { inviteCodeValidator } from "@rahoot/common/validators/auth"
|
||||
import env from "@rahoot/socket/env"
|
||||
import Config from "@rahoot/socket/services/config"
|
||||
import Game from "@rahoot/socket/services/game"
|
||||
import {
|
||||
findManagerGameByClientId,
|
||||
findPlayerGameByClientId,
|
||||
withGame,
|
||||
} from "@rahoot/socket/utils/game"
|
||||
import { inviteCodeValidator } from "@rahoot/socket/utils/validator"
|
||||
import Registry from "@rahoot/socket/services/registry"
|
||||
import { withGame } from "@rahoot/socket/utils/game"
|
||||
import { Server as ServerIO } from "socket.io"
|
||||
|
||||
const io: Server = new ServerIO()
|
||||
Config.init()
|
||||
|
||||
let games: Game[] = []
|
||||
const registry = Registry.getInstance()
|
||||
const port = env.SOCKER_PORT || 3001
|
||||
|
||||
console.log(`Socket server running on port ${port}`)
|
||||
io.listen(Number(port))
|
||||
|
||||
io.on("connection", (socket) => {
|
||||
console.log(`A user connected ${socket.id}`)
|
||||
console.log(socket.handshake.auth)
|
||||
console.log(
|
||||
`A user connected: socketId: ${socket.id}, clientId: ${socket.handshake.auth.clientId}`
|
||||
)
|
||||
|
||||
socket.on("player:reconnect", () => {
|
||||
const game = findPlayerGameByClientId(socket.handshake.auth.clientId, games)
|
||||
const game = registry.getPlayerGame(socket.handshake.auth.clientId)
|
||||
|
||||
if (game) {
|
||||
game.reconnect(socket)
|
||||
@@ -36,13 +34,11 @@ io.on("connection", (socket) => {
|
||||
})
|
||||
|
||||
socket.on("manager:reconnect", () => {
|
||||
const game = findManagerGameByClientId(
|
||||
socket.handshake.auth.clientId,
|
||||
games
|
||||
)
|
||||
const game = registry.getManagerGame(socket.handshake.auth.clientId)
|
||||
|
||||
if (game) {
|
||||
game.reconnect(socket)
|
||||
registry.reactivateGame(game.gameId)
|
||||
|
||||
return
|
||||
}
|
||||
@@ -56,6 +52,7 @@ io.on("connection", (socket) => {
|
||||
|
||||
if (password !== config.managerPassword) {
|
||||
socket.emit("manager:errorMessage", "Invalid password")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -72,23 +69,24 @@ io.on("connection", (socket) => {
|
||||
|
||||
if (!quizz) {
|
||||
socket.emit("game:errorMessage", "Quizz not found")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const game = new Game(io, socket, quizz)
|
||||
|
||||
games.push(game)
|
||||
registry.addGame(game)
|
||||
})
|
||||
|
||||
socket.on("player:join", async (inviteCode) => {
|
||||
socket.on("player:join", (inviteCode) => {
|
||||
const result = inviteCodeValidator.safeParse(inviteCode)
|
||||
|
||||
if (result.error) {
|
||||
socket.emit("game:errorMessage", result.error.issues[0].message)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const game = games.find((g) => g.inviteCode === inviteCode)
|
||||
const game = registry.getGameByInviteCode(inviteCode)
|
||||
|
||||
if (!game) {
|
||||
socket.emit("game:errorMessage", "Game not found")
|
||||
@@ -100,53 +98,54 @@ io.on("connection", (socket) => {
|
||||
})
|
||||
|
||||
socket.on("player:login", ({ gameId, data }) =>
|
||||
withGame(gameId, socket, games, (game) => game.join(socket, data.username))
|
||||
withGame(gameId, socket, (game) => game.join(socket, data.username))
|
||||
)
|
||||
|
||||
socket.on("manager:kickPlayer", ({ gameId, data }) =>
|
||||
withGame(gameId, socket, games, (game) =>
|
||||
game.kickPlayer(socket, data.playerId)
|
||||
)
|
||||
withGame(gameId, socket, (game) => game.kickPlayer(socket, data.playerId))
|
||||
)
|
||||
|
||||
socket.on("manager:startGame", ({ gameId }) =>
|
||||
withGame(gameId, socket, games, (game) => game.start(socket))
|
||||
withGame(gameId, socket, (game) => game.start(socket))
|
||||
)
|
||||
|
||||
socket.on("player:selectedAnswer", ({ gameId, data }) =>
|
||||
withGame(gameId, socket, games, (game) =>
|
||||
withGame(gameId, socket, (game) =>
|
||||
game.selectAnswer(socket, data.answerKey)
|
||||
)
|
||||
)
|
||||
|
||||
socket.on("manager:abortQuiz", ({ gameId }) =>
|
||||
withGame(gameId, socket, games, (game) => game.abortRound(socket))
|
||||
withGame(gameId, socket, (game) => game.abortRound(socket))
|
||||
)
|
||||
|
||||
socket.on("manager:nextQuestion", ({ gameId }) =>
|
||||
withGame(gameId, socket, games, (game) => game.nextRound(socket))
|
||||
withGame(gameId, socket, (game) => game.nextRound(socket))
|
||||
)
|
||||
|
||||
socket.on("manager:showLeaderboard", ({ gameId }) =>
|
||||
withGame(gameId, socket, games, (game) => game.showLeaderboard())
|
||||
withGame(gameId, socket, (game) => game.showLeaderboard())
|
||||
)
|
||||
|
||||
socket.on("disconnect", () => {
|
||||
console.log(`user disconnected ${socket.id}`)
|
||||
const managerGame = games.find((g) => g.manager.id === socket.id)
|
||||
|
||||
if (managerGame && !managerGame.started) {
|
||||
console.log("Reset game (manager disconnected)")
|
||||
const managerGame = registry.getGameByManagerSocketId(socket.id)
|
||||
|
||||
managerGame.abortCooldown()
|
||||
io.to(managerGame.gameId).emit("game:reset")
|
||||
if (managerGame) {
|
||||
registry.markGameAsEmpty(managerGame)
|
||||
|
||||
games = games.filter((g) => g.gameId !== managerGame.gameId)
|
||||
if (!managerGame.started) {
|
||||
console.log("Reset game (manager disconnected)")
|
||||
managerGame.abortCooldown()
|
||||
io.to(managerGame.gameId).emit("game:reset")
|
||||
registry.removeGame(managerGame.gameId)
|
||||
|
||||
return
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const game = games.find((g) => g.players.some((p) => p.id === socket.id))
|
||||
const game = registry.getGameByPlayerSocketId(socket.id)
|
||||
|
||||
if (!game || game.started) {
|
||||
return
|
||||
@@ -166,3 +165,13 @@ io.on("connection", (socket) => {
|
||||
console.log(`Removed player ${player.username} from game ${game.gameId}`)
|
||||
})
|
||||
})
|
||||
|
||||
process.on("SIGINT", () => {
|
||||
Registry.getInstance().cleanup()
|
||||
process.exit(0)
|
||||
})
|
||||
|
||||
process.on("SIGTERM", () => {
|
||||
Registry.getInstance().cleanup()
|
||||
process.exit(0)
|
||||
})
|
||||
|
||||
@@ -2,11 +2,19 @@ import { QuizzWithId } from "@rahoot/common/types/game"
|
||||
import fs from "fs"
|
||||
import { resolve } from "path"
|
||||
|
||||
const getPath = (path: string) => resolve(process.cwd(), "../../config", path)
|
||||
const getPath = (path: string = "") =>
|
||||
resolve(process.cwd(), "../../config", path)
|
||||
|
||||
class Config {
|
||||
static init() {
|
||||
const isConfigFolderExists = fs.existsSync(getPath())
|
||||
|
||||
if (!isConfigFolderExists) {
|
||||
fs.mkdirSync(getPath())
|
||||
}
|
||||
|
||||
const isGameConfigExists = fs.existsSync(getPath("game.json"))
|
||||
|
||||
if (!isGameConfigExists) {
|
||||
fs.writeFileSync(
|
||||
getPath("game.json"),
|
||||
@@ -22,6 +30,7 @@ class Config {
|
||||
}
|
||||
|
||||
const isQuizzExists = fs.existsSync(getPath("quizz"))
|
||||
|
||||
if (!isQuizzExists) {
|
||||
fs.mkdirSync(getPath("quizz"))
|
||||
|
||||
@@ -65,20 +74,25 @@ class Config {
|
||||
|
||||
static game() {
|
||||
const isExists = fs.existsSync(getPath("game.json"))
|
||||
|
||||
if (!isExists) {
|
||||
throw new Error("Game config not found")
|
||||
}
|
||||
|
||||
try {
|
||||
const config = fs.readFileSync(getPath("game.json"), "utf-8")
|
||||
|
||||
return JSON.parse(config)
|
||||
} catch (error) {
|
||||
console.error("Failed to read game config:", error)
|
||||
}
|
||||
|
||||
return {}
|
||||
}
|
||||
|
||||
static quizz() {
|
||||
const isExists = fs.existsSync(getPath("quizz"))
|
||||
|
||||
if (!isExists) {
|
||||
return []
|
||||
}
|
||||
@@ -99,9 +113,11 @@ class Config {
|
||||
...config,
|
||||
}
|
||||
})
|
||||
|
||||
return quizz || []
|
||||
} catch (error) {
|
||||
console.error("Failed to read quizz config:", error)
|
||||
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Answer, Player, Quizz } from "@rahoot/common/types/game"
|
||||
import { Server, Socket } from "@rahoot/common/types/game/socket"
|
||||
import { Status, StatusDataMap } from "@rahoot/common/types/game/status"
|
||||
import { Status, STATUS, StatusDataMap } from "@rahoot/common/types/game/status"
|
||||
import { createInviteCode, timeToPoint } from "@rahoot/socket/utils/game"
|
||||
import sleep from "@rahoot/socket/utils/sleep"
|
||||
import { v4 as uuid } from "uuid"
|
||||
@@ -114,7 +114,7 @@ class Game {
|
||||
const playerData = {
|
||||
id: socket.id,
|
||||
clientId: socket.handshake.auth.clientId,
|
||||
username: username,
|
||||
username,
|
||||
points: 0,
|
||||
}
|
||||
|
||||
@@ -148,7 +148,7 @@ class Game {
|
||||
}
|
||||
|
||||
reconnect(socket: Socket) {
|
||||
const clientId = socket.handshake.auth.clientId
|
||||
const { clientId } = socket.handshake.auth
|
||||
const isManager = this.manager.clientId === clientId
|
||||
|
||||
if (!isManager) {
|
||||
@@ -175,7 +175,7 @@ class Game {
|
||||
|
||||
const status = this.managerStatus ||
|
||||
this.lastBroadcastStatus || {
|
||||
name: Status.WAIT,
|
||||
name: STATUS.WAIT,
|
||||
data: { text: "Waiting for players" },
|
||||
}
|
||||
|
||||
@@ -188,7 +188,7 @@ class Game {
|
||||
|
||||
console.log(`Manager reconnected to game ${this.inviteCode}`)
|
||||
|
||||
return
|
||||
return true
|
||||
}
|
||||
|
||||
const player = this.players.find((p) => p.clientId === clientId)!
|
||||
@@ -197,7 +197,7 @@ class Game {
|
||||
|
||||
const status = this.playerStatus.get(oldSocketId) ||
|
||||
this.lastBroadcastStatus || {
|
||||
name: Status.WAIT,
|
||||
name: STATUS.WAIT,
|
||||
data: { text: "Waiting for players" },
|
||||
}
|
||||
|
||||
@@ -223,9 +223,9 @@ class Game {
|
||||
return true
|
||||
}
|
||||
|
||||
async startCooldown(seconds: number) {
|
||||
startCooldown(seconds: number): Promise<void> {
|
||||
if (this.cooldown.active) {
|
||||
return
|
||||
return Promise.resolve()
|
||||
}
|
||||
|
||||
this.cooldown.active = true
|
||||
@@ -237,6 +237,7 @@ class Game {
|
||||
this.cooldown.active = false
|
||||
clearInterval(cooldownTimeout)
|
||||
resolve()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -246,10 +247,8 @@ class Game {
|
||||
})
|
||||
}
|
||||
|
||||
async abortCooldown() {
|
||||
if (this.cooldown.active) {
|
||||
this.cooldown.active = false
|
||||
}
|
||||
abortCooldown() {
|
||||
this.cooldown.active &&= false
|
||||
}
|
||||
|
||||
async start(socket: Socket) {
|
||||
@@ -263,7 +262,7 @@ class Game {
|
||||
|
||||
this.started = true
|
||||
|
||||
this.broadcastStatus(Status.SHOW_START, {
|
||||
this.broadcastStatus(STATUS.SHOW_START, {
|
||||
time: 3,
|
||||
subject: this.quizz.subject,
|
||||
})
|
||||
@@ -290,7 +289,7 @@ class Game {
|
||||
total: this.quizz.questions.length,
|
||||
})
|
||||
|
||||
this.broadcastStatus(Status.SHOW_PREPARED, {
|
||||
this.broadcastStatus(STATUS.SHOW_PREPARED, {
|
||||
totalAnswers: question.answers.length,
|
||||
questionNumber: this.round.currentQuestion + 1,
|
||||
})
|
||||
@@ -301,7 +300,7 @@ class Game {
|
||||
return
|
||||
}
|
||||
|
||||
this.broadcastStatus(Status.SHOW_QUESTION, {
|
||||
this.broadcastStatus(STATUS.SHOW_QUESTION, {
|
||||
question: question.question,
|
||||
image: question.image,
|
||||
cooldown: question.cooldown,
|
||||
@@ -315,7 +314,7 @@ class Game {
|
||||
|
||||
this.round.startTime = Date.now()
|
||||
|
||||
this.broadcastStatus(Status.SELECT_ANSWER, {
|
||||
this.broadcastStatus(STATUS.SELECT_ANSWER, {
|
||||
question: question.question,
|
||||
answers: question.answers,
|
||||
image: question.image,
|
||||
@@ -332,10 +331,11 @@ class Game {
|
||||
await this.showResults(question)
|
||||
}
|
||||
|
||||
async showResults(question: any) {
|
||||
showResults(question: any) {
|
||||
const totalType = this.round.playersAnswers.reduce(
|
||||
(acc: Record<number, number>, { answerId }) => {
|
||||
acc[answerId] = (acc[answerId] || 0) + 1
|
||||
|
||||
return acc
|
||||
},
|
||||
{}
|
||||
@@ -366,7 +366,7 @@ class Game {
|
||||
const rank = index + 1
|
||||
const aheadPlayer = sortedPlayers[index - 1]
|
||||
|
||||
this.sendStatus(player.id, Status.SHOW_RESULT, {
|
||||
this.sendStatus(player.id, STATUS.SHOW_RESULT, {
|
||||
correct: player.lastCorrect,
|
||||
message: player.lastCorrect ? "Nice!" : "Too bad",
|
||||
points: player.lastPoints,
|
||||
@@ -376,7 +376,7 @@ class Game {
|
||||
})
|
||||
})
|
||||
|
||||
this.sendStatus(this.manager.id, Status.SHOW_RESPONSES, {
|
||||
this.sendStatus(this.manager.id, STATUS.SHOW_RESPONSES, {
|
||||
question: question.question,
|
||||
responses: totalType,
|
||||
correct: question.solution,
|
||||
@@ -387,7 +387,7 @@ class Game {
|
||||
this.round.playersAnswers = []
|
||||
}
|
||||
|
||||
async selectAnswer(socket: Socket, answerId: number) {
|
||||
selectAnswer(socket: Socket, answerId: number) {
|
||||
const player = this.players.find((player) => player.id === socket.id)
|
||||
const question = this.quizz.questions[this.round.currentQuestion]
|
||||
|
||||
@@ -405,7 +405,7 @@ class Game {
|
||||
points: timeToPoint(this.round.startTime, question.time),
|
||||
})
|
||||
|
||||
this.sendStatus(socket.id, Status.WAIT, {
|
||||
this.sendStatus(socket.id, STATUS.WAIT, {
|
||||
text: "Waiting for the players to answer",
|
||||
})
|
||||
|
||||
@@ -458,7 +458,7 @@ class Game {
|
||||
if (isLastRound) {
|
||||
this.started = false
|
||||
|
||||
this.broadcastStatus(Status.FINISHED, {
|
||||
this.broadcastStatus(STATUS.FINISHED, {
|
||||
subject: this.quizz.subject,
|
||||
top: sortedPlayers.slice(0, 3),
|
||||
})
|
||||
@@ -466,7 +466,7 @@ class Game {
|
||||
return
|
||||
}
|
||||
|
||||
this.sendStatus(this.manager.id, Status.SHOW_LEADERBOARD, {
|
||||
this.sendStatus(this.manager.id, STATUS.SHOW_LEADERBOARD, {
|
||||
leaderboard: sortedPlayers.slice(0, 5),
|
||||
})
|
||||
}
|
||||
|
||||
158
packages/socket/src/services/registry.ts
Normal file
158
packages/socket/src/services/registry.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
import Game from "@rahoot/socket/services/game"
|
||||
import dayjs from "dayjs"
|
||||
|
||||
interface EmptyGame {
|
||||
since: number
|
||||
game: Game
|
||||
}
|
||||
|
||||
class Registry {
|
||||
private static instance: Registry | null = null
|
||||
private games: Game[] = []
|
||||
private emptyGames: EmptyGame[] = []
|
||||
private cleanupInterval: ReturnType<typeof setTimeout> | null = null
|
||||
private readonly EMPTY_GAME_TIMEOUT_MINUTES = 5
|
||||
private readonly CLEANUP_INTERVAL_MS = 60_000
|
||||
|
||||
private constructor() {
|
||||
this.startCleanupTask()
|
||||
}
|
||||
|
||||
static getInstance(): Registry {
|
||||
Registry.instance ||= new Registry()
|
||||
|
||||
return Registry.instance
|
||||
}
|
||||
|
||||
addGame(game: Game): void {
|
||||
this.games.push(game)
|
||||
console.log(`Game ${game.gameId} added. Total games: ${this.games.length}`)
|
||||
}
|
||||
|
||||
getGameById(gameId: string): Game | undefined {
|
||||
return this.games.find((g) => g.gameId === gameId)
|
||||
}
|
||||
|
||||
getGameByInviteCode(inviteCode: string): Game | undefined {
|
||||
return this.games.find((g) => g.inviteCode === inviteCode)
|
||||
}
|
||||
|
||||
getPlayerGame(clientId: string): Game | undefined {
|
||||
return this.games.find((g) =>
|
||||
g.players.some((p) => p.clientId === clientId)
|
||||
)
|
||||
}
|
||||
|
||||
getManagerGame(clientId: string): Game | undefined {
|
||||
return this.games.find((g) => g.manager.clientId === clientId)
|
||||
}
|
||||
|
||||
getGameByManagerSocketId(socketId: string): Game | undefined {
|
||||
return this.games.find((g) => g.manager.id === socketId)
|
||||
}
|
||||
|
||||
getGameByPlayerSocketId(socketId: string): Game | undefined {
|
||||
return this.games.find((g) => g.players.some((p) => p.id === socketId))
|
||||
}
|
||||
|
||||
markGameAsEmpty(game: Game): void {
|
||||
const alreadyEmpty = this.emptyGames.find(
|
||||
(g) => g.game.gameId === game.gameId
|
||||
)
|
||||
|
||||
if (!alreadyEmpty) {
|
||||
this.emptyGames.push({
|
||||
since: dayjs().unix(),
|
||||
game,
|
||||
})
|
||||
console.log(
|
||||
`Game ${game.gameId} marked as empty. Total empty games: ${this.emptyGames.length}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
reactivateGame(gameId: string): void {
|
||||
const initialLength = this.emptyGames.length
|
||||
this.emptyGames = this.emptyGames.filter((g) => g.game.gameId !== gameId)
|
||||
|
||||
if (this.emptyGames.length < initialLength) {
|
||||
console.log(
|
||||
`Game ${gameId} reactivated. Remaining empty games: ${this.emptyGames.length}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
removeGame(gameId: string): boolean {
|
||||
const initialLength = this.games.length
|
||||
this.games = this.games.filter((g) => g.gameId !== gameId)
|
||||
this.emptyGames = this.emptyGames.filter((g) => g.game.gameId !== gameId)
|
||||
|
||||
const removed = this.games.length < initialLength
|
||||
|
||||
if (removed) {
|
||||
console.log(`Game ${gameId} removed. Total games: ${this.games.length}`)
|
||||
}
|
||||
|
||||
return removed
|
||||
}
|
||||
|
||||
getAllGames(): Game[] {
|
||||
return [...this.games]
|
||||
}
|
||||
|
||||
getGameCount(): number {
|
||||
return this.games.length
|
||||
}
|
||||
|
||||
getEmptyGameCount(): number {
|
||||
return this.emptyGames.length
|
||||
}
|
||||
|
||||
private cleanupEmptyGames(): void {
|
||||
const now = dayjs()
|
||||
const stillEmpty = this.emptyGames.filter(
|
||||
(g) =>
|
||||
now.diff(dayjs.unix(g.since), "minute") <
|
||||
this.EMPTY_GAME_TIMEOUT_MINUTES
|
||||
)
|
||||
|
||||
if (stillEmpty.length === this.emptyGames.length) {
|
||||
return
|
||||
}
|
||||
|
||||
const removed = this.emptyGames.filter((g) => !stillEmpty.includes(g))
|
||||
const removedGameIds = removed.map((r) => r.game.gameId)
|
||||
|
||||
this.games = this.games.filter((g) => !removedGameIds.includes(g.gameId))
|
||||
this.emptyGames = stillEmpty
|
||||
|
||||
console.log(
|
||||
`Removed ${removed.length} empty game(s). Remaining games: ${this.games.length}`
|
||||
)
|
||||
}
|
||||
|
||||
private startCleanupTask(): void {
|
||||
this.cleanupInterval = setInterval(() => {
|
||||
this.cleanupEmptyGames()
|
||||
}, this.CLEANUP_INTERVAL_MS)
|
||||
|
||||
console.log("Game cleanup task started")
|
||||
}
|
||||
|
||||
stopCleanupTask(): void {
|
||||
if (this.cleanupInterval) {
|
||||
clearInterval(this.cleanupInterval)
|
||||
this.cleanupInterval = null
|
||||
console.log("Game cleanup task stopped")
|
||||
}
|
||||
}
|
||||
|
||||
cleanup(): void {
|
||||
this.stopCleanupTask()
|
||||
this.games = []
|
||||
this.emptyGames = []
|
||||
console.log("Registry cleaned up")
|
||||
}
|
||||
}
|
||||
|
||||
export default Registry
|
||||
@@ -1,29 +1,28 @@
|
||||
import { Socket } from "@rahoot/common/types/game/socket"
|
||||
import Game from "@rahoot/socket/services/game"
|
||||
import Registry from "@rahoot/socket/services/registry"
|
||||
|
||||
export const withGame = <T>(
|
||||
export const withGame = (
|
||||
gameId: string | undefined,
|
||||
socket: Socket,
|
||||
games: Game[],
|
||||
handler: (game: Game) => T
|
||||
): T | void => {
|
||||
let game = null
|
||||
|
||||
if (gameId) {
|
||||
game = games.find((g) => g.gameId === gameId)
|
||||
} else {
|
||||
game = games.find(
|
||||
(g) =>
|
||||
g.players.find((p) => p.id === socket.id) || g.manager.id === socket.id
|
||||
)
|
||||
}
|
||||
|
||||
if (!game) {
|
||||
callback: (_game: Game) => void
|
||||
): void => {
|
||||
if (!gameId) {
|
||||
socket.emit("game:errorMessage", "Game not found")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
return handler(game)
|
||||
const registry = Registry.getInstance()
|
||||
const game = registry.getGameById(gameId)
|
||||
|
||||
if (!game) {
|
||||
socket.emit("game:errorMessage", "Game not found")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
callback(game)
|
||||
}
|
||||
|
||||
export const createInviteCode = (length = 6) => {
|
||||
@@ -50,25 +49,3 @@ export const timeToPoint = (startTime: number, secondes: number): number => {
|
||||
|
||||
return points
|
||||
}
|
||||
|
||||
export const findPlayerGameByClientId = (clientId: string, games: Game[]) => {
|
||||
const playerGame = games.find((g) =>
|
||||
g.players.find((p) => p.clientId === clientId)
|
||||
)
|
||||
|
||||
if (playerGame) {
|
||||
return playerGame
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export const findManagerGameByClientId = (clientId: string, games: Game[]) => {
|
||||
const managerGame = games.find((g) => g.manager.clientId === clientId)
|
||||
|
||||
if (managerGame) {
|
||||
return managerGame
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
import z from "zod"
|
||||
|
||||
export const usernameValidator = z
|
||||
.string()
|
||||
.min(4, "Username cannot be less than 4 characters")
|
||||
.max(20, "Username cannot exceed 20 characters")
|
||||
|
||||
export const inviteCodeValidator = z.string().length(6, "Invalid invite code")
|
||||
@@ -3,6 +3,7 @@
|
||||
"compilerOptions": {
|
||||
"target": "ESNext",
|
||||
"module": "ESNext",
|
||||
"types": ["node"],
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
Reference in New Issue
Block a user