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

Feature/#156 밤 마피아 구독 url 변경 #157

Merged
merged 7 commits into from
Dec 26, 2024
1 change: 1 addition & 0 deletions src/constant/localStroge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const CODE = 'code';
33 changes: 19 additions & 14 deletions src/pages/Game.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import { useEffect, useRef, useState } from 'react';
import { useRecoilState, useSetRecoilState } from 'recoil';

import { getChats, getGamesInfo, getMyJob } from '../axios/http';
import { BASE_URL, DOMAIN } from '../axios/instances';
import { CODE } from '../constant/localStroge';
import { gameRound, myJobState, roomInfoState } from '../recoil/roominfo/atom';
import { BORKER_URL, CHAT_PUB, CHAT_SUB, JOB_SKILL_PUB, JOB_SKILL_SUB } from '../socket/url';
import { EVENTSOURCE_URL } from '../sse/url';
import { ChatArray, ChatResponse, GameStatus, SkillResponse, WaitingRoomInfo } from '../type';
import Day from './Day';
import Night from './Night';
Expand All @@ -20,7 +22,6 @@ export default function Game() {
const [chatSubscribeId, setChatSubscribeId] = useState<StompJs.StompSubscription | null>(null);
const [skillSubscribeId, setSkillSubscribeId] = useState<StompJs.StompSubscription | null>(null);
const [mafiaSkillPlayer, setMafiaSkillPlayer] = useState<string | null>(null);
const [roomsInfoState, setRoomsInfoState] = useRecoilState(roomInfoState); // 방 정보
const [waitingRoomInfoState, setWaitingRoomInfoState] = useState<WaitingRoomInfo>({
totalPlayers: 1,
isMaster: true,
Expand All @@ -34,6 +35,7 @@ export default function Game() {
const [finishSocketConneted, setFinishSocketConnetd] = useState(false); // 웹 소켓 연결이 끝난다는 트리거(채팅 구독이 연결 전에 실행될 때를 대비해 다시 실행하기 위함)

const setGameRoundState = useSetRecoilState(gameRound);
const [roomsInfoState, setRoomsInfoState] = useRecoilState(roomInfoState); // 방 정보

// 방 상태 불러오기
const [gamesStatus, setGameStatus] = useState<GameStatus>({ statusType: 'WAIT' });
Expand All @@ -47,7 +49,7 @@ export default function Game() {

const EventSource = EventSourcePolyfill;

eventSource.current = new EventSource(`${BASE_URL}/games/subscribe`, {
eventSource.current = new EventSource(EVENTSOURCE_URL, {
headers: { Authorization: `Basic ${auth}` },
heartbeatTimeout: 1000 * 60 * 60 * 12,
withCredentials: true,
Expand All @@ -69,7 +71,7 @@ export default function Game() {
// WebSocket
const connect = () => {
const socket = new StompJs.Client({
brokerURL: `wss://${DOMAIN}/api/stomp`,
brokerURL: BORKER_URL,
reconnectDelay: 10000,
});

Expand Down Expand Up @@ -97,7 +99,7 @@ export default function Game() {
// 채팅구독함수
const subscribeChat = () => {
if (!socketClientState.current?.connected) return;
const chatSubscribeId = socketClientState.current.subscribe(`/sub/chat/${auth}`, response => {
const chatSubscribeId = socketClientState.current.subscribe(CHAT_SUB(auth), response => {
const msg: ChatResponse = JSON.parse(response.body);

const isOwner = msg.name == roomsInfoState.myName;
Expand All @@ -118,7 +120,7 @@ export default function Game() {
if (!socketClientState.current?.connected) return;

socketClientState.current.publish({
destination: `/pub/chat/${auth}`,
destination: CHAT_PUB(auth),
body: JSON.stringify({ content: content }),
});
};
Expand All @@ -142,11 +144,15 @@ export default function Game() {
// 밤 직업구독 함수
const subscribeSkill = async () => {
if (!socketClientState.current?.connected) return;
const code = localStorage.getItem(CODE);

const mafiaSubscribeId = socketClientState.current.subscribe(`/sub/mafia/${auth}`, response => {
const msg: SkillResponse = JSON.parse(response.body);
setMafiaSkillPlayer(msg.content);
});
const mafiaSubscribeId = socketClientState.current.subscribe(
JOB_SKILL_SUB(code, myJobRecoilState),
response => {
const msg: SkillResponse = JSON.parse(response.body);
setMafiaSkillPlayer(msg.result);
},
);

setSkillSubscribeId(mafiaSubscribeId);
};
Expand All @@ -162,8 +168,9 @@ export default function Game() {
if (!socketClientState.current?.connected) return;

socketClientState.current.publish({
destination: `/pub/skill/${auth}`,
destination: JOB_SKILL_PUB,
body: JSON.stringify({ target: name }),
headers: { Authorization: `Basic ${auth}` },
});
};

Expand All @@ -173,7 +180,7 @@ export default function Game() {

subscribeSkill();
return () => unsubscribeSkill();
}, [gamesStatus.statusType, finishSocketConneted]);
}, [gamesStatus.statusType, finishSocketConneted, myJobRecoilState]);

// 방 정보 저장 (방 상태가 바뀔때만 작동?)
useEffect(() => {
Expand All @@ -196,8 +203,6 @@ export default function Game() {
// 내 직업
if (gamesStatus.statusType !== 'WAIT' && !myJobRecoilState) {
const myJobResponse = await getMyJob();
console.log(myJobResponse);

setMyJobRecoilState(myJobResponse.job);
}
})();
Expand Down
7 changes: 7 additions & 0 deletions src/pages/InputName.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import BottomButton from '../components/button/BottomButton';
import AppContainerCSS from '../components/layout/AppContainerCSS';
import { notifyUseToast } from '../components/toast/NotifyToast';
import TopEnter from '../components/top/TopEnter';
import { CODE } from '../constant/localStroge';
import { VariablesCSS } from '../styles/VariablesCSS';

export default function InputName() {
Expand All @@ -33,8 +34,14 @@ export default function InputName() {

if (canParticipateRoom()) {
try {
// auth저장
const auth = await participateRooms({ code: code, name: name });
localStorage.setItem('auth', auth.auth);

// 코드저장
const codeParams = !searchParams.get('code') ? '' : searchParams.get('code');
localStorage.setItem(CODE, codeParams?.toString() || '');

navigate('/game');
// eslint-disable-next-line
} catch (error: any) {
Expand Down
15 changes: 15 additions & 0 deletions src/socket/url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { DOMAIN } from '../axios/instances';
import { Job } from '../type';

// *연결*
export const BORKER_URL = `wss://${DOMAIN}/api/stomp`;

// *채팅*
// chat
export const CHAT_SUB = (auth: string | null) => `/sub/chat/${auth}`;
export const CHAT_PUB = (auth: string | null) => `/pub/chat/${auth}`;

// skill
export const JOB_SKILL_SUB = (code: string | null, job: Job) =>
`/sub/jobs/skill/${job?.toLocaleLowerCase()}/${code}`;
export const JOB_SKILL_PUB = `/pub/jobs/skill`;
3 changes: 3 additions & 0 deletions src/sse/url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { BASE_URL } from '../axios/instances';

export const EVENTSOURCE_URL = `${BASE_URL}/games/subscribe`;
Loading