Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Improve room and player validation #159

Merged
merged 4 commits into from
Nov 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion server/src/chat/chat.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Server, Socket } from 'socket.io';
import { ChatService } from './chat.service';
import { UseFilters } from '@nestjs/common';
import { WsExceptionFilter } from 'src/filters/ws-exception.filter';
import { BadRequestException } from 'src/exceptions/game.exception';
import { BadRequestException, PlayerNotFoundException, RoomNotFoundException } from 'src/exceptions/game.exception';

@WebSocketGateway({
cors: '*',
Expand All @@ -22,6 +22,11 @@ export class ChatGateway {

if (!roomId || !playerId) throw new BadRequestException('Room ID and Player ID are required');

const roomExists = this.chatService.existsRoom(roomId);
if (!roomExists) throw new RoomNotFoundException('Room not found');
const playerExists = this.chatService.existsPlayer(roomId, playerId);
if (!playerExists) throw new PlayerNotFoundException('Player not found in room');

client.data.roomId = roomId;
client.data.playerId = playerId;

Expand Down
10 changes: 10 additions & 0 deletions server/src/chat/chat.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,14 @@ export class ChatRepository {
score: parseInt(player.score, 10) || 0,
} as Player;
}

async existsRoom(roomId: string) {
const exists = await this.redisService.exists(`room:${roomId}`);
return exists === 1;
}

async existsPlayer(roomId: string, playerId: string) {
const exists = await this.redisService.exists(`room:${roomId}:player:${playerId}`);
return exists === 1;
}
}
8 changes: 8 additions & 0 deletions server/src/chat/chat.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,12 @@ export class ChatService {
createdAt: new Date(),
};
}

async existsRoom(roomId: string) {
return await this.chatRepository.existsRoom(roomId);
}

async existsPlayer(roomId: string, playerId: string) {
return await this.chatRepository.existsPlayer(roomId, playerId);
}
}
10 changes: 9 additions & 1 deletion server/src/drawing/drawing.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ import {
WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { BadRequestException } from 'src/exceptions/game.exception';
import { BadRequestException, PlayerNotFoundException, RoomNotFoundException } from 'src/exceptions/game.exception';
import { WsExceptionFilter } from 'src/filters/ws-exception.filter';
import { DrawingService } from './drawing.service';

@WebSocketGateway({
cors: '*',
Expand All @@ -20,12 +21,19 @@ export class DrawingGateway implements OnGatewayConnection {
@WebSocketServer()
server: Server;

constructor(private readonly drawingService: DrawingService) {}

handleConnection(client: Socket) {
const roomId = client.handshake.auth.roomId;
const playerId = client.handshake.auth.playerId;

if (!roomId || !playerId) throw new BadRequestException('Room ID and Player ID are required');

const roomExists = this.drawingService.existsRoom(roomId);
if (!roomExists) throw new RoomNotFoundException('Room not found');
const playerExists = this.drawingService.existsPlayer(roomId, playerId);
if (!playerExists) throw new PlayerNotFoundException('Player not found in room');

client.data.roomId = roomId;
client.data.playerId = playerId;

Expand Down
6 changes: 5 additions & 1 deletion server/src/drawing/drawing.module.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { Module } from '@nestjs/common';
import { DrawingGateway } from './drawing.gateway';
import { RedisModule } from 'src/redis/redis.module';
import { DrawingService } from './drawing.service';
import { DrawingRepository } from './drawing.repository';

@Module({
providers: [DrawingGateway],
imports: [RedisModule],
providers: [DrawingGateway, DrawingService, DrawingRepository],
})
export class DrawingModule {}
17 changes: 17 additions & 0 deletions server/src/drawing/drawing.repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Injectable } from '@nestjs/common';
import { RedisService } from 'src/redis/redis.service';

@Injectable()
export class DrawingRepository {
constructor(private readonly redisService: RedisService) {}

async existsRoom(roomId: string) {
const exists = await this.redisService.exists(`room:${roomId}`);
return exists === 1;
}

async existsPlayer(roomId: string, playerId: string) {
const exists = await this.redisService.exists(`room:${roomId}:player:${playerId}`);
return exists === 1;
}
}
15 changes: 15 additions & 0 deletions server/src/drawing/drawing.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Injectable } from '@nestjs/common';
import { DrawingRepository } from './drawing.repository';

@Injectable()
export class DrawingService {
constructor(private readonly drawingRepository: DrawingRepository) {}

async existsRoom(roomId: string) {
return await this.drawingRepository.existsRoom(roomId);
}

async existsPlayer(roomId: string, playerId: string) {
return await this.drawingRepository.existsPlayer(roomId, playerId);
}
}
5 changes: 5 additions & 0 deletions server/src/exceptions/game.exception.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,8 @@ export class ForbiddenException extends GameException {
super(SocketErrorCode.FORBIDDEN, message);
}
}
export class GameAlreadyStartedException extends GameException {
constructor(message: string = 'Game already started') {
super(SocketErrorCode.GAME_ALREADY_STARTED, message);
}
}
10 changes: 8 additions & 2 deletions server/src/game/game.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import { GameService } from './game.service';
import { UseFilters } from '@nestjs/common';
import { WsExceptionFilter } from 'src/filters/ws-exception.filter';
import { Player, Room, RoomSettings } from 'src/common/types/game.types';
import { BadRequestException } from 'src/exceptions/game.exception';
import { PlayerRole } from 'src/common/enums/game.status.enum';
import { BadRequestException, GameAlreadyStartedException, RoomNotFoundException } from 'src/exceptions/game.exception';
import { PlayerRole, RoomStatus } from 'src/common/enums/game.status.enum';
import { TimerService } from 'src/common/services/timer.service';
import { TimerType } from 'src/common/enums/game.timer.enum';

Expand All @@ -36,6 +36,12 @@ export class GameGateway implements OnGatewayDisconnect {

@SubscribeMessage('joinRoom')
async handleJoinRoom(@ConnectedSocket() client: Socket, @MessageBody() data: { roomId: string }) {
const roomStatus = await this.gameService.getRoomStatus(data.roomId);
if (!roomStatus) throw new RoomNotFoundException('Room not found');
if (roomStatus === RoomStatus.GUESSING || roomStatus === RoomStatus.DRAWING) {
throw new GameAlreadyStartedException('Cannot join room while game is in progress');
}

const { room, roomSettings, player, players } = await this.gameService.joinRoom(data.roomId);

client.data.playerId = player.playerId;
Expand Down
4 changes: 4 additions & 0 deletions server/src/game/game.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ export class GameRepository {
await multi.exec();
}

async getRoomStatus(roomId: string) {
return this.redisService.hget(`room:${roomId}`, 'status') as Promise<RoomStatus>;
}

async getRoomSettings(roomId: string) {
const settings = await this.redisService.hgetall(`room:${roomId}:settings`);

Expand Down
12 changes: 8 additions & 4 deletions server/src/game/game.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ export class GameService {
return { room, roomSettings, player, players: updatedPlayers };
}

getRoomStatus(roomId: string) {
return this.gameRepository.getRoomStatus(roomId);
}

async reconnect(roomId: string, playerId: string) {
const [room, roomSettings, players] = await Promise.all([
this.gameRepository.getRoom(roomId),
Expand Down Expand Up @@ -266,14 +270,14 @@ export class GameService {
await Promise.all(
updatedPlayers.map((p) => this.gameRepository.updatePlayer(roomId, p.playerId, { score: p.score })),
);

const winner = currentPlayer;
const painters = updatedPlayers.filter((p) => p.role === PlayerRole.PAINTER);
const winner = updatedPlayers.find((p) => p.playerId === playerId);

return {
isCorrect,
roundNumber: room.currentRound,
word: room.currentWord,
winner,
winners: [winner, ...painters],
players: updatedPlayers,
};
}
Expand Down Expand Up @@ -324,7 +328,7 @@ export class GameService {
return {
roundNumber: room.currentRound,
word: room.currentWord,
winner,
winners: [winner],
players: updatedPlayers,
};
}
Expand Down
4 changes: 4 additions & 0 deletions server/src/redis/redis.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ export class RedisService {
await this.redis.lrem(key, count, value);
}

async exists(key: string): Promise<number> {
return await this.redis.exists(key);
}

multi() {
return this.redis.multi();
}
Expand Down