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] useWebsocket 리팩토링 #317

Merged
merged 6 commits into from
Apr 18, 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: 6 additions & 17 deletions src/pages/GamePage/GamePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,9 @@ const GamePage = () => {
const navigate = useNavigate();

const { roomId, setRoomInfo, roomInfo } = useRoomInfoStore();
const {
handlePubReadyGame,
handlePubStartGame,
handlePubKickUser,
onIngameConnected,
publishIngame,
handleConnectIngame,
} = useWebsocket(roomId);

const { gameRoomRes, isWsError, didAdminStart, allMembers } =
const { publishGameRoom, stompClient } = useWebsocket(roomId);

const { gameRoomRes, isRoomWsError, didAdminStart, allMembers } =
useGameWaitingRoomStore();

//Todo => useSuspenseQuery로 변경...
Expand Down Expand Up @@ -77,7 +70,7 @@ const GamePage = () => {
}
}, [gameRoomRes]);

if (!roomId || isWsError) {
if (!roomId || isRoomWsError) {
yejinleee marked this conversation as resolved.
Show resolved Hide resolved
navigate('/main', { replace: true });
navigate(0);
}
Expand Down Expand Up @@ -105,9 +98,7 @@ const GamePage = () => {
<GameWaitingRoom
allMembers={allMembers}
roomInfo={roomInfo}
handlePubReadyGame={handlePubReadyGame}
handlePubStartGame={handlePubStartGame}
handlePubKickUser={handlePubKickUser}
publishGameRoom={publishGameRoom}
userId={userId}
/>
);
Expand All @@ -116,9 +107,7 @@ const GamePage = () => {
return (
<IngameWebsocketLayer
userId={userId}
publishIngame={publishIngame}
onIngameConnected={onIngameConnected}
handleConnectIngame={handleConnectIngame}
stompClient={stompClient}
/>
);
};
Expand Down
16 changes: 5 additions & 11 deletions src/pages/GamePage/GameWaitingRoom/GameReadyAndStart.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,17 @@
import {
HandlePubReadyGameType,
HandlePubStartGameType,
I_AllMember,
} from '../types/websocketType';
import { I_AllMember, PublishGameRoomType } from '../types/websocketType';

interface GameReadyAndStartProps {
isAdmin: boolean;
userId: number;
allMembers: I_AllMember[];
handlePubReadyGame: HandlePubReadyGameType;
handlePubStartGame: HandlePubStartGameType;
publishGameRoom: PublishGameRoomType;
}

const GameReadyAndStart = ({
isAdmin,
userId,
allMembers,
handlePubReadyGame,
handlePubStartGame,
publishGameRoom,
}: GameReadyAndStartProps) => {
const isAllUserReady =
allMembers.every((user) => user.readyStatus === true) &&
Expand All @@ -31,7 +25,7 @@ const GameReadyAndStart = ({
return (
<button
onClick={() => {
isAllUserReady && handlePubStartGame();
isAllUserReady && publishGameRoom('/start');
}}
className={`font-[Giants-Inline] w-[25%] h-[10rem] flex justify-center items-center text-[3rem] transition-all duration-300 shadow-md shadow-black/50 relative
overflow-hidden
Expand All @@ -53,7 +47,7 @@ bg-coral-50
return (
<button
onClick={() => {
handlePubReadyGame();
publishGameRoom('/ready');
}}
className={`font-[Giants-Inline] group w-[24.1rem] h-[10rem] flex justify-center items-center text-[3rem] ${isUserReady ? 'bg-coral-100' : 'bg-coral-50'}
relative overflow-hidden
Expand Down
9 changes: 5 additions & 4 deletions src/pages/GamePage/GameWaitingRoom/GameRoomUserItem.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import { useMemo } from 'react';
import { TRACK_CARS } from '@/assets/canvasCars';
import close from '@/assets/close.webp';
import { HandlePubKickUserType, I_AllMember } from '../types/websocketType';
import { I_AllMember, PublishGameRoomType } from '../types/websocketType';

const GameRoomUserItem = ({
idx,
hostId,
gameRoomUser,
userId,
handlePubKickUser,
publishGameRoom,
}: {
idx: number;
hostId: number | undefined;
gameRoomUser: I_AllMember;
userId: number;
handlePubKickUser: HandlePubKickUserType;
publishGameRoom: PublishGameRoomType;
}) => {
const {
memberId,
Expand All @@ -33,7 +33,8 @@ const GameRoomUserItem = ({
<div className='h-[3rem] self-end'>
<button
onClick={() => {
handlePubKickUser(memberId);
publishGameRoom(`/kick/${memberId}`);
// handlePubKickUser(memberId);
}}>
{isAdminMe && !isMe && (
<img
Expand Down
8 changes: 4 additions & 4 deletions src/pages/GamePage/GameWaitingRoom/GameRoomUserList.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { HandlePubKickUserType, I_AllMember } from '../types/websocketType';
import { I_AllMember, PublishGameRoomType } from '../types/websocketType';
import GameRoomUserItem from './GameRoomUserItem';

const GameRoomUserList = ({
gameRoomUserList,
hostId,
userId,
handlePubKickUser,
publishGameRoom,
}: {
gameRoomUserList: I_AllMember[];
hostId: number | undefined;
userId: number;
handlePubKickUser: HandlePubKickUserType;
publishGameRoom: PublishGameRoomType;
}) => {
return (
<>
Expand All @@ -23,7 +23,7 @@ const GameRoomUserList = ({
hostId={hostId}
gameRoomUser={gameRoomUser}
userId={userId}
handlePubKickUser={handlePubKickUser}
publishGameRoom={publishGameRoom}
/>
))}
</main>
Expand Down
19 changes: 6 additions & 13 deletions src/pages/GamePage/GameWaitingRoom/GameWaitingRoom.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { useCallback, useEffect, useState } from 'react';
import Backward from '@/common/Backward/Backward';
import useCarImgStore from '@/store/useCarStore';
import { NumberIndexSignatureType } from '../../../types/indexSignatureType';
import DisconnectModal from '../common/DisconnectModal';
import { NumberIndexSignatureType } from '../types/ingameTypes';
import {
HandlePubKickUserType,
HandlePubReadyGameType,
HandlePubStartGameType,
I_AllMember,
I_RoomInfo,
PublishGameRoomType,
} from '../types/websocketType';
import GameModeDescription from './GameModeDescription';
import GameReadyAndStart from './GameReadyAndStart';
Expand All @@ -19,16 +17,12 @@ import GameRoomUserList from './GameRoomUserList';
const GameWaitingRoom = ({
allMembers,
roomInfo,
handlePubReadyGame,
handlePubStartGame,
handlePubKickUser,
publishGameRoom,
userId,
}: {
allMembers: I_AllMember[];
roomInfo: I_RoomInfo;
handlePubReadyGame: HandlePubReadyGameType;
handlePubStartGame: HandlePubStartGameType;
handlePubKickUser: HandlePubKickUserType;
publishGameRoom: PublishGameRoomType;
userId: number;
}) => {
const [isAlert, setIsAlert] = useState(false);
Expand Down Expand Up @@ -72,7 +66,7 @@ const GameWaitingRoom = ({
gameRoomUserList={allMembers}
hostId={roomInfo?.hostId}
userId={userId}
handlePubKickUser={handlePubKickUser}
publishGameRoom={publishGameRoom}
/>
)}
<footer className='w-[114.8rem] h-[10rem] flex gap-[5rem]'>
Expand All @@ -86,8 +80,7 @@ const GameWaitingRoom = ({
isAdmin={isAdmin}
userId={userId}
allMembers={allMembers}
handlePubReadyGame={handlePubReadyGame}
handlePubStartGame={handlePubStartGame}
publishGameRoom={publishGameRoom}
/>
</footer>
</div>
Expand Down
15 changes: 7 additions & 8 deletions src/pages/GamePage/IngameWebsocketLayer.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import React, { Suspense, useEffect } from 'react';
import { Client } from '@stomp/stompjs';
import React, { MutableRefObject, Suspense, useEffect } from 'react';
import Spinner from '@/common/Spinner/Spinner';
import useIngameStore from '@/store/useIngameStore';
import useRoomInfoStore from '@/store/useRoomInfoStore';
import { checkIsEmptyObj } from '@/utils/checkIsEmptyObj';
import RoundWaitModal from './common/RoundWaitModal';
import WsError from './common/WsError';
import { PublishIngameType } from './types/websocketType';
import useIngameWebsocket from './hooks/useIngameWebsocket';

interface IngameWebsocketLayerProps {
userId: number;
publishIngame: PublishIngameType;
onIngameConnected: () => void;
handleConnectIngame: (roomId: number) => void;
stompClient: MutableRefObject<Client | undefined>;
}

const GameCode = React.lazy(() => import('./GameCode/GameCode'));
Expand All @@ -21,14 +20,14 @@ const GameSentence = React.lazy(() => import('./GameSentence/GameSentence'));

const IngameWebsocketLayer = ({
userId,
publishIngame,
onIngameConnected,
handleConnectIngame,
stompClient,
}: IngameWebsocketLayerProps) => {
const { roomId, roomInfo } = useRoomInfoStore();
const { ingameRoomRes, isIngameWsError, isRoundWaiting, setIsRoundWaiting } =
useIngameStore();

const { onIngameConnected, handleConnectIngame, publishIngame } =
useIngameWebsocket({ roomId, stompClient });
useEffect(() => {
onIngameConnected(); // 인게임 엔드포인트 구독
handleConnectIngame(roomId); // 해당 인게임 연결 발행
Expand Down
2 changes: 1 addition & 1 deletion src/pages/GamePage/common/CanvasTrack.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
} from '@/common/Ingame/ingameConstants';
import useCanvas from '@/hooks/useCanvas';
import useCarImgStore from '@/store/useCarStore';
import { NumberIndexSignatureType } from '../types/ingameTypes';
import { NumberIndexSignatureType } from '../../../types/indexSignatureType';
import { I_AllMember } from '../types/websocketType';

interface I_CarCoord {
Expand Down
65 changes: 65 additions & 0 deletions src/pages/GamePage/hooks/useIngameWebsocket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { Client, StompSubscription } from '@stomp/stompjs';
import { MutableRefObject, useRef } from 'react';
import useGameWaitingRoomStore from '@/store/useGameWaitingRoomStore';
import useIngameStore from '@/store/useIngameStore';
import { checkIsEmptyObj } from '@/utils/checkIsEmptyObj';
import { getToken } from '@/utils/getToken';
import { PayloadType } from '../types/websocketType';

interface I_useIngame {
roomId: number;
stompClient: MutableRefObject<Client | undefined>;
}
const useIngameWebsocket = ({ roomId, stompClient }: I_useIngame) => {
const ingameSubscription = useRef<StompSubscription>();

const connectHeaders = getToken();
const { setIsIngameWsError, setIngameRoomRes } = useIngameStore();
const { setAllMembers } = useGameWaitingRoomStore();

const onIngameConnected = () => {
ingameSubscription.current = stompClient.current?.subscribe(
`/from/game/${roomId}`,
(e) => onIngameMessageReceived(e),
connectHeaders
);
};
const disconnectIngameWs = () => {
ingameSubscription.current?.unsubscribe();
};

const handleConnectIngame = (roomId: number) => {
stompClient.current?.publish({
destination: `/to/game/${roomId}/connect`,
headers: connectHeaders,
});
};
const onIngameMessageReceived = ({ body }: { body: string }) => {
const responsePublish = JSON.parse(body);
// eslint-disable-next-line no-console
console.log('ingameResponsePublish-----', responsePublish);
setIngameRoomRes(responsePublish);
if (checkIsEmptyObj(responsePublish)) {
setIsIngameWsError(true);
}
if (responsePublish.type === 'FINISH') {
disconnectIngameWs();
setAllMembers(responsePublish.allMembers);
}
};
const publishIngame = (destination: string, payload: PayloadType) => {
stompClient.current?.publish({
destination: `/to/game/${roomId}${destination}`,
headers: connectHeaders,
body: JSON.stringify(payload),
});
};

return {
onIngameConnected,
handleConnectIngame,
publishIngame,
};
};

export default useIngameWebsocket;
Loading