Skip to content

Commit

Permalink
[hotfix] [BE] 개설된 게임방 페이지네이션 (#182)
Browse files Browse the repository at this point in the history
* feat: 전체 방 목록 조회 시 메타데이터 포함

* chore: 에러 메시지 정리
  • Loading branch information
student079 authored Nov 27, 2024
1 parent 1f75e4f commit a991eff
Show file tree
Hide file tree
Showing 9 changed files with 136 additions and 137 deletions.
11 changes: 11 additions & 0 deletions be/gameServer/src/common/constant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export enum ErrorMessages {
ROOM_NOT_FOUND = 'RoomNotFound',
GAME_NOT_FOUND = 'GameNotFound',
ROOM_FULL = 'RoomFull',
NICKNAME_TAKEN = 'NicknameTaken',
PLAYER_NOT_FOUND = 'PlayerNotFound',
ONLY_HOST_CAN_START = 'HostOnlyStart',
INTERNAL_ERROR = 'InternalError',
ALL_PLAYERS_MUST_BE_READY = 'AllPlayersMustBeReady',
NOT_ENOUGH_PLAYERS = 'NotEnoughPlayers',
}
25 changes: 11 additions & 14 deletions be/gameServer/src/modules/games/games.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import { RoomDataDto } from '../rooms/dto/room-data.dto';
import { GameDataDto } from './dto/game-data.dto';
import { TurnDataDto } from './dto/turn-data.dto';
import { VoiceResultFromServerDto } from './dto/voice-result-from-server.dto';
import { ErrorResponse } from '../rooms/dto/error-response.dto';
import {
createTurnData,
selectCurrentPlayer,
Expand All @@ -25,6 +24,7 @@ import {
numberToNote,
transformScore,
} from './games-utils';
import { ErrorMessages } from '../../common/constant';

const VOICE_SERVERS = 'voice-servers';
const PRONOUNCE_SCORE_THRESOLHD = 50;
Expand Down Expand Up @@ -58,30 +58,30 @@ export class GamesGateway implements OnGatewayDisconnect {

if (!roomData) {
this.logger.warn(`Room not found: ${roomId}`);
client.emit('error', 'Room not found');
client.emit('error', ErrorMessages.ROOM_NOT_FOUND);
return;
}

if (roomData.hostNickname !== playerNickname) {
this.logger.warn(
`User ${client.data.playerNickname} is not the host of room ${roomId}`,
);
client.emit('error', 'Only the host can start the game');
client.emit('error', ErrorMessages.ONLY_HOST_CAN_START);
return;
}

if (roomData.players.length <= 1) {
this.logger.warn(
`Not enough players to start the game in room ${roomId}`,
);
client.emit('error', 'Game cannot start');
client.emit('error', ErrorMessages.NOT_ENOUGH_PLAYERS);
return;
}

const allReady = checkPlayersReady(roomData);
if (!allReady) {
this.logger.warn(`Not all players are ready in room: ${roomId}`);
client.emit('error', 'All players must be ready to start the game');
client.emit('error', ErrorMessages.ALL_PLAYERS_MUST_BE_READY);
return;
}

Expand Down Expand Up @@ -129,10 +129,7 @@ export class GamesGateway implements OnGatewayDisconnect {
this.logger.error(
`Error starting game in room ${roomId}: ${error.message}`,
);
const errorResponse: ErrorResponse = {
message: 'Failed to start the game',
};
client.emit('error', errorResponse);
client.emit('error', ErrorMessages.INTERNAL_ERROR);
}
}

Expand All @@ -153,7 +150,7 @@ export class GamesGateway implements OnGatewayDisconnect {
`game:${roomId}`,
);
if (!gameDataString) {
return client.emit('error', { message: `game ${roomId} not found` });
return client.emit('error', ErrorMessages.ROOM_NOT_FOUND);
}

const gameData: GameDataDto = JSON.parse(gameDataString);
Expand All @@ -180,7 +177,7 @@ export class GamesGateway implements OnGatewayDisconnect {
);
if (!roomData) {
this.logger.warn(`Room not found: ${roomId}`);
client.emit('error', 'Room not found');
client.emit('error', ErrorMessages.ROOM_NOT_FOUND);
return;
}

Expand All @@ -202,7 +199,7 @@ export class GamesGateway implements OnGatewayDisconnect {
}
} catch (error) {
this.logger.error('Error handling next:', error);
client.emit('error', { message: 'Internal server error' });
client.emit('error', ErrorMessages.INTERNAL_ERROR);
}
}

Expand All @@ -223,7 +220,7 @@ export class GamesGateway implements OnGatewayDisconnect {
`game:${roomId}`,
);
if (!gameDataString) {
return client.emit('error', { message: `game ${roomId} not found` });
return client.emit('error', ErrorMessages.GAME_NOT_FOUND);
}

const gameData: GameDataDto = JSON.parse(gameDataString);
Expand Down Expand Up @@ -300,7 +297,7 @@ export class GamesGateway implements OnGatewayDisconnect {
await this.redisService.set(`game:${roomId}`, JSON.stringify(gameData));
} catch (error) {
this.logger.error('Error handling voiceResult:', error);
client.emit('error', { message: 'Internal server error' });
client.emit('error', ErrorMessages.INTERNAL_ERROR);

// 오류 일때
}
Expand Down
70 changes: 0 additions & 70 deletions be/gameServer/src/modules/rooms/dto/error-response.dto.ts

This file was deleted.

12 changes: 12 additions & 0 deletions be/gameServer/src/modules/rooms/dto/paginated-room.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { RoomDataDto } from './room-data.dto';

export class PaginatedRoomDto {
rooms: RoomDataDto[];
pagination: {
currentPage: number;
totalPages: number;
totalItems: number;
hasNextPage: boolean;
hasPreviousPage: boolean;
};
}
10 changes: 6 additions & 4 deletions be/gameServer/src/modules/rooms/dto/room-data.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,14 @@ export class RoomDataDto {
type: [PlayerDataDto],
example: [
{
nickname: 'hostNickname123',
ready: true,
playerNickname: 'hostNic123',
isReady: true,
isMuted: false,
},
{
nickname: 'player1',
ready: false,
playerNickname: 'player1',
isReady: false,
isMuted: true,
},
],
description: '현재 방에 참여한 플레이어 목록과 준비 상태',
Expand Down
80 changes: 73 additions & 7 deletions be/gameServer/src/modules/rooms/rooms.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ import {
Param,
NotFoundException,
Query,
Delete,
} from '@nestjs/common';
import { RedisService } from '../../redis/redis.service';
import { RoomDataDto } from './dto/room-data.dto';
import { PaginatedRoomDto } from './dto/paginated-room.dto';
import {
ApiTags,
ApiOperation,
Expand Down Expand Up @@ -272,14 +274,37 @@ export class RoomController {
@ApiResponse({
status: 200,
description: '게임 방 목록이 성공적으로 반환됩니다.',
type: [RoomDataDto],
schema: {
example: {
rooms: [
{
roomId: '6f42377f-42ea-42cc-ac1a-b5d2b99d4ced',
roomName: '게임방123',
hostNickname: 'hostNickname123',
players: [
{ playerNickname: 'hostNic123', isReady: true, isMuted: false },
{ playerNickname: 'player1', isReady: false, isMuted: true },
],
status: 'waiting',
},
],
pagination: {
currentPage: 1,
totalPages: 5,
totalItems: 50,
hasNextPage: true,
hasPreviousPage: false,
},
},
},
})
async getRooms(@Query('page') page: number = 1): Promise<RoomDataDto[]> {
async getRooms(@Query('page') page = 1): Promise<PaginatedRoomDto> {
this.logger.log(`게임 방 목록 조회 시작 (페이지: ${page})`);

const totalRooms = await this.redisService.llen('roomsList');
const totalPages = Math.ceil(totalRooms / ROOM_LIMIT);
const start = (page - 1) * ROOM_LIMIT;
const end = start + ROOM_LIMIT - 1;
this.logger.log(
`게임 방 목록 조회 시작 (페이지: ${page}, 범위: ${start}-${end})`,
);

const paginatedKeys = await this.redisService.lrange(
'roomsList',
Expand All @@ -292,11 +317,52 @@ export class RoomController {
const roomData = await this.redisService.hgetAll<RoomDataDto>(
`room:${key}`,
);
return roomData;

return {
roomId: key,
roomName: roomData.roomName,
hostNickname: roomData.hostNickname,
players: roomData.players,
status: roomData.status,
} as RoomDataDto;
}),
);

this.logger.log(`게임 방 목록 조회 완료, ${rooms.length}개 방 반환`);
return rooms;

return {
rooms: rooms,
pagination: {
currentPage: Number(page),
totalPages,
totalItems: totalRooms,
hasNextPage: page < totalPages,
hasPreviousPage: page > 1,
},
};
}

@Delete('Error Messages')
@ApiOperation({
summary: '에러 메시지 목록',
description: 'API에서 발생할 수 있는 에러 메시지 목록',
})
@ApiResponse({
status: 200,
description: '에러 메시지 목록',
example: [
'RoomNotFound: 방을 찾을 수 없음',
'GameNotFound: 게임을 찾을 수 없음',
'RoomFull: 방이 가득 참',
'NicknameTaken: 닉네임이 이미 사용 중',
'PlayerNotFound: 플레이어를 찾을 수 없음',
'HostOnlyStart: 호스트만 게임을 시작할 수 있음',
'InternalError: 내부 서버 오류',
'AllPlayersMustBeReady: 모든 플레이어가 준비 상태여야 함',
'NotEnoughPlayers: 플레이어가 충분하지 않음',
],
})
getErrorMessages() {
return;
}
}
Loading

0 comments on commit a991eff

Please sign in to comment.