Skip to content

Commit

Permalink
Refactor: 모듈화된 서버 요청을 사용하도록 리팩토링
Browse files Browse the repository at this point in the history
  • Loading branch information
pp449 committed Jan 14, 2024
1 parent de8aa96 commit 96e1c26
Show file tree
Hide file tree
Showing 25 changed files with 146 additions and 374 deletions.
14 changes: 2 additions & 12 deletions src/components/Bracket/BracketContents.tsx
Original file line number Diff line number Diff line change
@@ -1,32 +1,22 @@
import { useQuery } from '@tanstack/react-query';
import { useRouter } from 'next/router';
import authAPI from '@apis/authAPI';

import { BracketContents } from '@type/bracket';
import styled from '@emotion/styled';
import Image from 'next/image';
import { fetchBracketContents } from '@apis/bracketContents';

interface Props {
curRound: number;
}

const fetchBracket = async (channelLink: string, curRound: number) => {
const res = await authAPI<BracketContents>({
method: 'get',
url: `/api/match/${channelLink}/${curRound}`,
});

return res.data;
};

const BracketContents = (props: Props) => {
const router = useRouter();

const { data, isSuccess, isError, isLoading } = useQuery(
['bracketContents', props.curRound, router.query.channelLink],
() => {
if (typeof router.query.channelLink === 'string') {
return fetchBracket(router.query.channelLink, props.curRound);
return fetchBracketContents(router.query.channelLink, props.curRound);
}
},
);
Expand Down
4 changes: 2 additions & 2 deletions src/components/Header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import Icon from '@components/Icon';
import { useContext, useState } from 'react';
import Image from 'next/image';
import ProfileContext from '@contexts/ProfileContext';
import authAPI from '@apis/authAPI';
import Cookies from 'js-cookie';
import { logout } from '@apis/mypage';

const Header = () => {
const router = useRouter();
Expand All @@ -32,7 +32,7 @@ const Header = () => {

const handleLogout = async () => {
try {
const res = await authAPI({ method: 'post', url: '/api/member/logout' });
await logout();
Cookies.remove('accessToken');
Cookies.remove('refreshToken');

Expand Down
56 changes: 30 additions & 26 deletions src/components/MakeChannel/SelectRule.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,31 @@ import useMakeGame from '@hooks/useMakeGame';
import { GameMethod, MakeChannelStep } from '@constants/MakeGame';
import CustomRule from './CustomRule';
import { useRef, useState } from 'react';
import authAPI from '@apis/authAPI';
import Image from 'next/image';
import { ChannelCircleProps } from '@type/channelCircle';
import useChannels from '@hooks/useChannels';
import { useRouter } from 'next/router';
import Icon from '@components/Icon';
import { createNewChannel } from '@apis/channels';
import { uploadImage } from '@apis/utils';

interface Props {
handleCurrentModalStep: (step: keyof typeof MakeChannelStep) => void;
handleModal: () => void;
}

export interface NewGameOption {
gameCategory: number;
matchFormat: number;
title: string;
maxPlayer: number;
tier: boolean;
tierMax: number;
tierMin: number;
playCount: boolean;
playCountMin: number;
channelImageUrl: string;
}

const SelectRule = ({ handleCurrentModalStep, handleModal }: Props) => {
const inputRef = useRef<HTMLInputElement | null>(null);

Expand Down Expand Up @@ -52,22 +65,20 @@ const SelectRule = ({ handleCurrentModalStep, handleModal }: Props) => {
}

try {
const res = await authAPI<ChannelCircleProps>({
method: 'post',
url: '/api/channel',
data: {
gameCategory,
matchFormat,
title: basicInfo.title,
maxPlayer: basicInfo.participationNum,
tier: isUseCustomRule.tierMax || isUseCustomRule.tierMin,
tierMax: customRule.tierMax,
tierMin: customRule.tierMin,
playCount: isUseCustomRule.playCount,
playCountMin: customRule.playCountMin,
channelImageUrl: channelImgUrl,
},
});
const newGameOption: NewGameOption = {
gameCategory,
matchFormat,
title: basicInfo.title,
maxPlayer: basicInfo.participationNum,
tier: isUseCustomRule.tierMax || isUseCustomRule.tierMin,
tierMax: customRule.tierMax,
tierMin: customRule.tierMin,
playCount: isUseCustomRule.playCount,
playCountMin: customRule.playCountMin,
channelImageUrl: channelImgUrl,
};

const res = await createNewChannel(newGameOption);
resetState();
router.push('/');
handleModal();
Expand All @@ -86,14 +97,7 @@ const SelectRule = ({ handleCurrentModalStep, handleModal }: Props) => {
formData.append('uploadImage', e.target.files[0]);

try {
const res = await authAPI<{ imgUrl: string }>({
method: 'post',
url: `/api/image`,
data: formData,
headers: {
'Content-Type': 'multipart/form-data',
},
});
const res = await uploadImage(formData);

setImageUrl(res.data.imgUrl);
handleImgUrl(res.data.imgUrl);
Expand Down
17 changes: 4 additions & 13 deletions src/components/Modal/JoinLeague/JoinLeague.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import authAPI from '@apis/authAPI';
import { joinChannelParticipant } from '@apis/channels';
import { fetchUserTier } from '@apis/utils';
import Icon from '@components/Icon';
import { SERVER_URL } from '@config/index';
import { css } from '@emotion/react';
import styled from '@emotion/styled';
import useProfile from '@hooks/useProfile';
Expand Down Expand Up @@ -30,9 +30,7 @@ const JoinLeague = ({ onClose, channelLink }: JoinLeagueProps) => {
return;
}

const userTier: string = (
await authAPI.get(SERVER_URL + `/api/participant/stat/${gameIdVal}/${gameTagVal}`)
).data.tier;
const userTier: string = await fetchUserTier(gameIdVal, gameTagVal);
setTier(userTier);
setGameId(gameIdVal + '#' + gameTagVal);
};
Expand All @@ -53,14 +51,7 @@ const JoinLeague = ({ onClose, channelLink }: JoinLeagueProps) => {

const onClickSubmit: MouseEventHandler<HTMLElement> = async () => {
if (!nickname || !checked) return;
const res = await authAPI({
method: 'post',
url: `/api/${channelLink}/participant`,
data: {
gameId,
nickname,
},
});
const res = await joinChannelParticipant(channelLink, gameId, nickname);

if (res.status !== 200) return;

Expand Down
11 changes: 3 additions & 8 deletions src/components/Modal/ModifyChannel/ModifyChannel.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import authAPI from '@apis/authAPI';
import { fetchChannelInfo } from '@apis/channels';
import Icon from '@components/Icon';
import BasicInfoChannel from '@components/ModifyChannel/BasicInfoChannel';
import BracketInfoChannel from '@components/ModifyChannel/BracketInfoChannel';
Expand All @@ -13,11 +13,6 @@ interface ModifyChannelProps {

type MenuList = 'basicInfo' | 'bracketInfo';

const fetchChannelInfo = async (channelLink: string) => {
const res = await authAPI({ method: 'get', url: `/api/channel/${channelLink}` });
return res.data;
};

const ModifyChannel = ({ channelLink, onClose }: ModifyChannelProps) => {
const [selectedMenu, setSelectedMenu] = useState<MenuList>('basicInfo');

Expand Down Expand Up @@ -45,8 +40,8 @@ const ModifyChannel = ({ channelLink, onClose }: ModifyChannelProps) => {
{selectedMenu === 'basicInfo' && (
<BasicInfoChannel
channelLink={channelLink}
leagueTitle={data?.leagueTitle}
maxPlayer={data?.maxPlayer}
leagueTitle={data ? data.leagueTitle : ''}
maxPlayer={data ? data.maxPlayer : 0}
/>
)}
{selectedMenu === 'bracketInfo' && <BracketInfoChannel />}
Expand Down
14 changes: 5 additions & 9 deletions src/components/Modal/ParticipantLists/ObserverUser.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import authAPI from '@apis/authAPI';
import { fetchOberverUser, promoteToAdmin } from '@apis/channels';
import { Participant } from '@components/Modal/ParticipantLists/ParticipantUser';
import { css } from '@emotion/react';
import styled from '@emotion/styled';
Expand All @@ -11,10 +11,8 @@ const ObserverUser = () => {
const { currentChannel, channelPermission } = useChannels();

const fetchData = async () => {
const res = await authAPI<Participant[]>({
method: 'get',
url: `/api/${currentChannel}/observers`,
});
if (!currentChannel) return;
const res = await fetchOberverUser(currentChannel);
setObservers(res.data);
};

Expand All @@ -23,11 +21,9 @@ const ObserverUser = () => {
};

const onClickPromotionUser = async (observer: Participant) => {
if (!currentChannel) return;
if (!confirm(`${observer.nickname}님을 관리자 권한을 부여하겠습니까?`)) return;
const res = await authAPI({
method: 'post',
url: `/api/${currentChannel}/${observer.pk}/host`,
});
const res = await promoteToAdmin(currentChannel, observer.pk);
if (res.status !== 200) return;
const updatedObservers = observers?.filter((user) => user.pk !== observer.pk);
setObservers(updatedObservers);
Expand Down
14 changes: 5 additions & 9 deletions src/components/Modal/ParticipantLists/ParticipantUser.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import authAPI from '@apis/authAPI';
import { demoteToObserver, fetchParticipantUser } from '@apis/channels';
import { css } from '@emotion/react';
import styled from '@emotion/styled';
import useChannels from '@hooks/useChannels';
Expand All @@ -19,10 +19,8 @@ const ParticipantUser = () => {
const { currentChannel, channelPermission } = useChannels();

const fetchData = async () => {
const res = await authAPI<Participant[]>({
method: 'get',
url: `/api/${currentChannel}/players`,
});
if (!currentChannel) return;
const res = await fetchParticipantUser(currentChannel);
setParticipants(res.data);
};

Expand All @@ -31,11 +29,9 @@ const ParticipantUser = () => {
};

const onClickKickUser = async (participant: Participant) => {
if (!currentChannel) return;
if (!confirm(`${participant.nickname}님을 강퇴하시겠습니까?`)) return;
const res = await authAPI({
method: 'post',
url: `/api/${currentChannel}/${participant.pk}/observer`,
});
const res = await demoteToObserver(currentChannel, participant.pk);
if (res.status !== 200) return;
const updatedParticipants = participants?.filter((user) => user.pk !== participant.pk);
setParticipants(updatedParticipants);
Expand Down
22 changes: 7 additions & 15 deletions src/components/Modal/ParticipantLists/RequestUser.tsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,19 @@
import authAPI from '@apis/authAPI';
import { confirmParticipation, fetchRequestUser, rejectParticipation } from '@apis/channels';
import { Participant } from '@components/Modal/ParticipantLists/ParticipantUser';
import { css } from '@emotion/react';
import styled from '@emotion/styled';
import useChannels from '@hooks/useChannels';
import Image from 'next/image';
import { useEffect, useState } from 'react';

const postData = async (url: string) => {
const res = await authAPI({
method: 'post',
url: url,
});
return res;
};

const RequestUser = () => {
const [requestUsers, setRequestUsers] = useState<Participant[]>();
const { currentChannel, channelPermission } = useChannels();

const fetchData = async () => {
const res = await authAPI<Participant[]>({
method: 'get',
url: `/api/${currentChannel}/player/requests`,
});
if (currentChannel === undefined) return;
const res = await fetchRequestUser(currentChannel);

setRequestUsers(res.data);
};

Expand All @@ -31,13 +22,14 @@ const RequestUser = () => {
};

const onClick = async (requestUser: Participant, mode: boolean) => {
if (!currentChannel) return;
let res;
if (mode) {
if (!confirm(`${requestUser.nickname}님 대회 참가를 수락하시겠습니까?`)) return;
res = await postData(`/api/${currentChannel}/${requestUser.pk}/player`);
res = await confirmParticipation(currentChannel, requestUser.pk);
} else {
if (!confirm(`${requestUser.nickname}님 대회 참가를 거절하시겠습니까?`)) return;
res = await postData(`/api/${currentChannel}/${requestUser.pk}/observer`);
res = await rejectParticipation(currentChannel, requestUser.pk);
}
if (res.status !== 200) return;
const updatedRequestUsers = requestUsers?.filter((user) => user.pk !== requestUser.pk);
Expand Down
38 changes: 12 additions & 26 deletions src/components/ModifyChannel/AssignBracket.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import authAPI from '@apis/authAPI';
import { assignNextRound, fetchAllBracket } from '@apis/brackets';
import styled from '@emotion/styled';
import { useQuery } from '@tanstack/react-query';
import { BracketHeader } from '@type/bracket';
Expand All @@ -7,37 +7,23 @@ import { useRouter } from 'next/router';

type bracketStatus = 'DONE' | 'READY' | 'BAN';

const fetchAllBracket = async (channelLink: string) => {
const res = await authAPI<BracketHeader>({
method: 'get',
url: `/api/match/${channelLink}`,
});

return res.data;
};

const AssignBracket = () => {
const router = useRouter();

const { data, isSuccess } = useQuery<BracketHeader>(['bracketSetting'], () => {
return fetchAllBracket(router.query.channelLink as string);
});

const fetchSetBracket = async (round: number) => {
if (window.confirm(`Round ${round}를 배정하시겠습니까?`)) {
try {
const res = await authAPI({
method: 'post',
url: `/api/match/${router.query.channelLink as string}/${round}`,
});

if (isSuccess) {
data.liveRound = round;
}
} catch (error) {
if (error instanceof AxiosError) {
window.alert(error.response?.data.message);
}
const setBracket = async (round: number) => {
if (!window.confirm(`Round ${round}를 배정하시겠습니까?`)) return;
try {
await assignNextRound(router.query.channelLink as string, round);
if (isSuccess) {
data.liveRound = round;
}
} catch (error) {
if (error instanceof AxiosError) {
window.alert(error.response?.data.message);
}
}
};
Expand All @@ -50,7 +36,7 @@ const AssignBracket = () => {
<BracketHeader>Round {round}</BracketHeader>
{round === data.liveRound && <BracketButton status='DONE'>배정 완료</BracketButton>}
{round === data.liveRound + 1 && (
<BracketButton status='READY' onClick={() => fetchSetBracket(round)}>
<BracketButton status='READY' onClick={() => setBracket(round)}>
배정 하기
</BracketButton>
)}
Expand Down
Loading

0 comments on commit 96e1c26

Please sign in to comment.