Skip to content

Commit

Permalink
fix(client & server): fixes bug with too many people in the room (#14)
Browse files Browse the repository at this point in the history
fix #6

Co-authored-by: Asman Umbetov <[email protected]>
  • Loading branch information
fastndead and Asman Umbetov authored Nov 25, 2023
1 parent bfcf017 commit 7999d4b
Show file tree
Hide file tree
Showing 6 changed files with 193 additions and 159 deletions.
67 changes: 25 additions & 42 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,62 +1,45 @@
module.exports = {
'env': {
'browser': true,
'es2021': true,
'node': true
env: {
browser: true,
es2021: true,
node: true,
},
'extends': [
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:@typescript-eslint/recommended'
'plugin:@typescript-eslint/recommended',
],
'overrides': [
],
'parser': '@typescript-eslint/parser',
'parserOptions': {
'ecmaVersion': 'latest',
'sourceType': 'module'
overrides: [],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
},
'plugins': [
'react',
'eslint-plugin-react-hooks',
'@typescript-eslint',
],
'rules': {
plugins: ['react', 'eslint-plugin-react-hooks', '@typescript-eslint'],
rules: {
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
'no-debugger':'off',
'no-debugger': 'off',
'keyword-spacing': ['error'],
'space-infix-ops': ['error'],
'@typescript-eslint/quotes': [
'error',
'single',
{
'avoidEscape': true,
'allowTemplateLiterals': true
}
avoidEscape: true,
allowTemplateLiterals: true,
},
],
'jsx-quotes': ['error', 'prefer-single'],
'react/jsx-first-prop-new-line': ['error', 'always'],
'object-curly-spacing': ['error', 'always'],
'react/jsx-max-props-per-line': ['error', { 'maximum': 1, 'when': 'always' }],
'react/jsx-closing-bracket-location': ['error', 'tag-aligned'],
'react/jsx-max-props-per-line': ['error', { maximum: 1, when: 'always' }],
'react/jsx-closing-bracket-location': ['error', 'tag-aligned'],
'react/jsx-closing-tag-location': ['error'],
'react/jsx-child-element-spacing': ['error'],
'indent': [
'error',
2
],
'linebreak-style': [
'error',
'unix'
],
'quotes': [
'error',
'single'
],
'semi': [
'error',
'never'
]
}
}
'indent': ['error', 2],
'linebreak-style': ['error', 'unix'],
'quotes': ['error', 'single'],
'semi': ['error', 'never'],
},
};
8 changes: 4 additions & 4 deletions .prettierrc.cjs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
module.exports = {
printWidth: 100,
semi: false,
trailingComma: "es5",
trailingComma: 'es5',
useTabs: false,
tabWidth: 2,
singleQuote: true,
quoteProps: "consistent",
quoteProps: 'consistent',
jsxSingleQuote: true,
arrowParens: "always",
endOfLine: "lf",
arrowParens: 'always',
endOfLine: 'lf',
};
83 changes: 50 additions & 33 deletions server/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

import express, { Express, NextFunction, Request, Response } from 'express'
import session from 'express-session'
import path from 'path'
Expand All @@ -12,7 +11,7 @@ const app: Express = express()

const users: Record<string, Player> = {}

const rooms: Record<string, {[key: string]: Player}> = {}
const rooms: Record<string, { [key: string]: Player }> = {}

const createNewUser = (name: string, id: string) => {
users[id] = {
Expand All @@ -24,17 +23,23 @@ const createNewUser = (name: string, id: string) => {
return users[id]
}

const createRoom = (name:string) => {
const createRoom = (name: string) => {
rooms[name] = {}
}

app.use(cors(
{
const broadcastUpdate = (socket: Socket, roomName: string) => {
const room = rooms[roomName]
const serializedRoom = Object.keys(room).map((key) => room[key])
socket.broadcast.to(roomName).emit('update', { players: serializedRoom })
}

app.use(
cors({
origin: isDev && 'http://localhost:3000',
methods: ['GET', 'POST'],
credentials: true
}
))
credentials: true,
})
)
app.use(express.static(path.join(__dirname, '..')))
const sessionMiddleware = session({
secret: 'changeit',
Expand All @@ -43,7 +48,7 @@ const sessionMiddleware = session({
})

app.use(sessionMiddleware)
app.use(express.json())
app.use(express.json())
app.get('/*', (_req: Request, res: Response) => {
res.sendFile(path.join(__dirname, '..', 'index.html'))
})
Expand All @@ -65,27 +70,26 @@ const io = new Server(server, {
cors: {
origin: isDev && 'http://localhost:3000',
methods: ['GET', 'POST'],
credentials: true
}
credentials: true,
},
})

io.engine.use(sessionMiddleware)

export type Card = {
value?: string,
value?: string
}

export type Player = {
id: string,
value: string | null
name: string,
id: string
value: string | null
name: string
}

io.on('connection', (socket) => {
const sessionId = socket.request.session.id


socket.on('mynameis', ({ name }: {name: string}) => {
socket.on('mynameis', ({ name }: { name: string }) => {
createNewUser(name, sessionId)
socket.emit('mynameis', { name })
})
Expand All @@ -98,34 +102,47 @@ io.on('connection', (socket) => {
})
})


socket.on('join', ({ roomName }: {roomName: string}) => {
socket.on('join', ({ roomName }: { roomName: string }) => {
if (!users[sessionId]) {
createNewUser('Anonimous', sessionId)
}

if (!rooms[roomName]) {
createRoom(roomName)
}
const room = rooms[roomName]
room[sessionId] = users[sessionId]

const room = rooms[roomName]

const isRoomFull = Object.keys(room).length >= 8

if (!isRoomFull) {
room[sessionId] = users[sessionId]
}

socket.join(roomName)
const serializedRoom = Object.keys(room).filter((key) => key !== sessionId).map((key) => room[key])
socket.emit('initial_state', { players: [...serializedRoom] })
const serializedRoom = Object.keys(room)
.filter((key) => key !== sessionId)
.map((key) => room[key])

socket.emit('initial_state', { players: serializedRoom, spectator: isRoomFull, id: sessionId })

socket.broadcast.to(roomName).emit('new_player', { player: users[sessionId] })
broadcastUpdate(socket, roomName)
})

socket.on('vote', ({ voteValue }: {voteValue: string}) => {
socket.on('vote', ({ voteValue }: { voteValue: string }) => {
socket.rooms.forEach((roomName) => {
try {
if (rooms[roomName]) {
rooms[roomName][sessionId].value = voteValue
}
socket.broadcast.to(roomName).emit('player_voted', { value: voteValue, playerId: sessionId })
} catch {
socket.emit('business_error', { error: 'Internal server error. Your vote was not counted, Please reload the page' })
socket.broadcast
.to(roomName)
.emit('player_voted', { value: voteValue, playerId: sessionId })
} catch (e) {
console.log(e)
socket.emit('business_error', {
error: 'Internal server error. Your vote was not counted, Please reload the page',
})
}
})
})
Expand Down Expand Up @@ -155,21 +172,21 @@ io.on('connection', (socket) => {
})
})

socket.on('leave', ({ roomId }: {roomId: string}) => {
if (rooms[roomId]){
socket.on('leave', ({ roomId }: { roomId: string }) => {
if (rooms[roomId]) {
delete rooms[roomId][sessionId]
socket.broadcast.to(roomId).emit('player_disconnect', { playerId: sessionId })

if (Object.keys(rooms[roomId]).length === 0) {
delete rooms[roomId]
} else {
broadcastUpdate(socket, roomId)
}
}
})

socket.on('disconnecting', () => {
if (users[sessionId]) {
socket.rooms.forEach((roomName) => {
if (rooms[roomName]){
if (rooms[roomName]) {
delete rooms[roomName][sessionId]
socket.broadcast.to(roomName).emit('player_disconnect', { playerId: sessionId })
}
Expand Down
Loading

0 comments on commit 7999d4b

Please sign in to comment.