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

feat: 대기방 정보 SSE로 교체 #144

Merged
merged 2 commits into from
Nov 23, 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
23 changes: 0 additions & 23 deletions src/axios/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,33 +41,10 @@ export const getValidRoomCode = async (code: string | null) => {
return http.get<RoomCodeExistsResponse>(`/lobbies/code/exist?code=${code}`);
};

export const useChatsQuery = () => {
const { data: chats, ...rest } = useSuspenseQuery({
queryKey: ['chats', localStorage.getItem('auth')],
queryFn: () => getChats(),
// refetchInterval: 500,
// staleTime: 500,
});
return {
chats,
...rest,
};
};

export const getRoomsStatus = () => {
return http.get<GameStatus>('/games/status');
};

export const useGamesInfoQuery = () => {
const { data: gameInfo, ...rest } = useSuspenseQuery({
queryKey: ['games', 'info', localStorage.getItem('auth')],
queryFn: () => getGamesInfo(),
refetchInterval: 500,
staleTime: 500,
});
return { gameInfo, ...rest };
};

export const getGamesInfo = () => {
return http.get<GameInfo>(`/games/info`);
};
Expand Down
33 changes: 29 additions & 4 deletions src/pages/Game.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { useRecoilState, useSetRecoilState } from 'recoil';
import { getChats, getGamesInfo, getMyJob } from '../axios/http';
import { BASE_URL } from '../axios/instances';
import { gameRound, myJobState, roomInfoState } from '../recoil/roominfo/atom';
import { ChatArray, ChatResponse, GameStatus } from '../type';
import { ChatArray, ChatResponse, GameStatus, WaitingRoomInfo } from '../type';
import Day from './Day';
import Night from './Night';
import Result from './Result';
Expand All @@ -19,6 +19,16 @@ export default function Game() {

const [chatSubscribeId, setChatSubscribeId] = useState<StompJs.StompSubscription | null>(null);
const [roomsInfoState, setRoomsInfoState] = useRecoilState(roomInfoState); // 방 정보
const [waitingRoomInfoState, setWaitingRoomInfoState] = useState<WaitingRoomInfo>({
totalPlayers: 1,
isMaster: true,
myName: '내이름',
lobbyPlayerResponses: [
{
name: '이름',
},
],
});
const [finishSocketConneted, setFinishSocketConnetd] = useState(false); // 웹 소켓 연결이 끝난다는 트리거(채팅 구독이 연결 전에 실행될 때를 대비해 다시 실행하기 위함)

const setGameRoundState = useSetRecoilState(gameRound);
Expand All @@ -45,6 +55,10 @@ export default function Game() {
setGameStatus(JSON.parse(response.data));
}) as EventListener);

eventSource.current.addEventListener('lobbyInfo', ((response: MessageEvent) => {
setWaitingRoomInfoState(JSON.parse(response.data));
}) as EventListener);

return () => {
eventSource.current?.close();
};
Expand Down Expand Up @@ -115,8 +129,6 @@ export default function Game() {
return () => unsubscribeChat();
}, [gamesStatus.statusType, finishSocketConneted]);

useEffect(() => {});

// 웹소켓 연결
useEffect(() => {
connect();
Expand All @@ -130,6 +142,17 @@ export default function Game() {
const roomInfoResponse = await getGamesInfo();
setRoomsInfoState(roomInfoResponse);

// 대기방 SSE이벤트를 받기전에 처음값
setWaitingRoomInfoState({
...waitingRoomInfoState,
totalPlayers: roomInfoResponse.totalPlayers,
isMaster: roomInfoResponse.isMaster,
myName: roomInfoResponse.myName,
lobbyPlayerResponses: roomInfoResponse.players.map(player => {
return { name: player.name };
}),
});

// 내 직업
if (gamesStatus.statusType !== 'WAIT' && !myJobRecoilState) {
const myJobResponse = await getMyJob();
Expand All @@ -147,7 +170,9 @@ export default function Game() {

return (
<>
{gamesStatus.statusType === 'WAIT' && <WaitingRoom />}
{gamesStatus.statusType === 'WAIT' && (
<WaitingRoom waitingRoomInfoState={waitingRoomInfoState} />
)}
{(gamesStatus.statusType === 'DAY_INTRO' ||
gamesStatus.statusType === 'NOTICE' ||
gamesStatus.statusType === 'DAY' ||
Expand Down
26 changes: 15 additions & 11 deletions src/pages/WaitingRoom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Suspense, useEffect, useState } from 'react';
import { Toaster } from 'react-hot-toast';
import { useNavigate } from 'react-router-dom';

import { getRoomsCode, startGame, useGamesInfoQuery } from '../axios/http';
import { getRoomsCode, startGame } from '../axios/http';
import { DOMAIN } from '../axios/instances';
import BigButton from '../components/button/BigButton';
import { Loading } from '../components/etc/Loading';
Expand All @@ -14,17 +14,21 @@ import PlayerWaiting from '../components/player/PlayerWaiting';
import { notifyUseToast } from '../components/toast/NotifyToast';
import TopEnter from '../components/top/TopEnter';
import { VariablesCSS } from '../styles/VariablesCSS';
import { Player } from '../type';
import { lobbyPlayer, WaitingRoomInfo } from '../type';

export default function WaitingRoom() {
type PropsType = {
waitingRoomInfoState: WaitingRoomInfo;
};

export default function WaitingRoom({ waitingRoomInfoState }: PropsType) {
const [openAnimation, setOpenAnimation] = useState(false);

/* 참가목록 받아오기 */
const [players, setPlayers] = useState<Player[]>([]);
const { gameInfo } = useGamesInfoQuery();
const [players, setPlayers] = useState<lobbyPlayer[]>([]);

const getVirtualPlayers = () => {
const virtualPlayersLength = gameInfo.totalPlayers - gameInfo.players.length;
const virtualPlayersLength =
waitingRoomInfoState.totalPlayers - waitingRoomInfoState.lobbyPlayerResponses.length;
const virtualPlayer = {
name: '',
isAlive: true,
Expand All @@ -34,8 +38,8 @@ export default function WaitingRoom() {
};

useEffect(() => {
setPlayers(gameInfo.players);
}, [gameInfo.players]);
setPlayers(waitingRoomInfoState.lobbyPlayerResponses);
}, [waitingRoomInfoState]);

/* 초대하기 모달 */
// 띄우고 끄기
Expand Down Expand Up @@ -82,7 +86,7 @@ export default function WaitingRoom() {

/* 게임시작 */
const canStartGame = () => {
return gameInfo.isMaster && players.length === gameInfo.totalPlayers;
return waitingRoomInfoState.isMaster && players.length === waitingRoomInfoState.totalPlayers;
};
const navigate = useNavigate();
const onGameStart = async () => {
Expand All @@ -101,7 +105,7 @@ export default function WaitingRoom() {
<div css={textGroup}>
<p css={subTitle}>참가목록</p>
<p css={number}>
{players.length}/{gameInfo.totalPlayers}
{players.length}/{waitingRoomInfoState.totalPlayers}
</p>
</div>
<PlayerGrid>
Expand All @@ -111,7 +115,7 @@ export default function WaitingRoom() {
</PlayerGrid>
</div>
<div css={bottom} onClick={onGameStart}>
{gameInfo.isMaster && (
{waitingRoomInfoState.isMaster && (
<BigButton vatiety="emphasis" use="gameStart" ready={canStartGame()} />
)}
</div>
Expand Down
11 changes: 11 additions & 0 deletions src/type/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,17 @@ export interface GameInfo {
players: Player[];
}

export interface WaitingRoomInfo {
totalPlayers: number;
isMaster: boolean;
myName: string;
lobbyPlayerResponses: lobbyPlayer[];
}

export interface lobbyPlayer {
name: string;
}

export interface MyJobResponse {
job: Job;
}
Expand Down
Loading