Skip to content

Commit

Permalink
[♻️refactor]: useWebsocket useIngameWebsocket 분리
Browse files Browse the repository at this point in the history
  • Loading branch information
yejinleee committed Apr 10, 2024
1 parent aa4ba20 commit 1bd5293
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 56 deletions.
25 changes: 19 additions & 6 deletions src/pages/GamePage/GamePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ const GamePage = () => {
const { roomId, setRoomInfo, roomInfo } = useRoomInfoStore();
const {
publishGameRoom,
onIngameConnected,
publishIngame,
handleConnectIngame,
// onIngameConnected,
// publishIngame,
// handleConnectIngame,
stompClient,
ingameSubscription,
} = useWebsocket(roomId);

const { gameRoomRes, isRoomWsError, didAdminStart, allMembers } =
Expand Down Expand Up @@ -112,10 +114,21 @@ const GamePage = () => {
return (
<IngameWebsocketLayer
userId={userId}
publishIngame={publishIngame}
onIngameConnected={onIngameConnected}
handleConnectIngame={handleConnectIngame}
stompClient={stompClient}
ingameSubscription={ingameSubscription}
/>
);
};
export default GamePage;

/*
useWebsocket 분리..
처음 GamePage 들어오면 useWebsocket 연결하면서 게임대기룸 웹소켓 연결함
인게임 시작되면 인게임 웹소켓도 연결해야함. 교체아님 쌓여야함
인게임 종료되면 인게임 웹소켓 끊어야함!!! <- 쌓이지 않게
인게임 웹소켓을 분리하고 싶다..
구상1
usWebsocekt에서 ingameSubscription를 반환한다.
이걸로 인게임 unsubscribe 해야해서 ..
*/
20 changes: 12 additions & 8 deletions src/pages/GamePage/IngameWebsocketLayer.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import React, { Suspense, useEffect } from 'react';
import { Client, StompSubscription } 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;
// publishIngame: PublishIngameType;
// onIngameConnected: () => void;
// handleConnectIngame: (roomId: number) => void;
stompClient: MutableRefObject<Client | undefined>;
ingameSubscription: MutableRefObject<StompSubscription | undefined>;
}

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

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

const { onIngameConnected, handleConnectIngame, publishIngame } =
useIngameWebsocket({ roomId, stompClient, ingameSubscription });
useEffect(() => {
onIngameConnected(); // 인게임 엔드포인트 구독
handleConnectIngame(roomId); // 해당 인게임 연결 발행
Expand Down
68 changes: 68 additions & 0 deletions src/pages/GamePage/hooks/useIngameWebsocket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { Client, StompSubscription } from '@stomp/stompjs';
import { MutableRefObject } 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>;
ingameSubscription: MutableRefObject<StompSubscription | undefined>;
}
const useIngameWebsocket = ({
roomId,
stompClient,
ingameSubscription,
}: I_useIngame) => {
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;
45 changes: 3 additions & 42 deletions src/pages/GamePage/hooks/useWebsocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import useGameWaitingRoomStore from '@/store/useGameWaitingRoomStore';
import useIngameStore from '@/store/useIngameStore.ts';
import { checkIsEmptyObj } from '@/utils/checkIsEmptyObj';
import { getToken } from '@/utils/getToken';
import { PayloadType } from '../types/websocketType.ts';

const useWebsocket = (roomId: number | null) => {
const stompClient = useRef<Client>();
Expand All @@ -17,7 +16,7 @@ const useWebsocket = (roomId: number | null) => {

const { setGameRoomRes, setIsRoomWsError, setDidAdminStart, setAllMembers } =
useGameWaitingRoomStore();
const { setIsIngameWsError, setIngameRoomRes } = useIngameStore();
const { setIngameRoomRes } = useIngameStore();

useEffect(() => {
const client = new Client({
Expand Down Expand Up @@ -99,48 +98,10 @@ const useWebsocket = (roomId: number | null) => {
});
};

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 {
publishGameRoom,
onIngameConnected,
handleConnectIngame,
publishIngame,
stompClient,
ingameSubscription,
};
};

Expand Down

0 comments on commit 1bd5293

Please sign in to comment.