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] API 중복 호출 방지 & 중복 투표 오류 해결 #402

Open
wants to merge 11 commits into
base: develop
Choose a base branch
from
Open
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
7 changes: 4 additions & 3 deletions frontend/src/constants/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import { ErrorCode } from '@/types/error';

export const ERROR_MESSAGE: Record<ErrorCode, string> = {
// 방 관련 에러 (room)
NOT_READY_ROOM: '해당 방의 게임이 이미 시작되었어요. 게임이 끝날 때까지 기다려볼까요?', // 게임 시작된 방에 참가 요청할 때
NOT_READY_ROOM: '이미 게임이 시작되었어요. 게임이 끝날 때까지 기다려볼까요?', // 게임 시작된 방에 참가 요청할 때
NOT_PROGRESSED_ROOM: '이미 게임이 종료되었어요. 최종 결과를 확인해볼까요?', // FIXME: 방장이 최종 결과 화면으로 넘어갔는데, 화면 안보고 있었으면 투표 화면에 갇힘
NOT_FINISHED_ROOM: '해당 방의 게임이 아직 종료되지 않았어요.',
NOT_FOUND_ROOM: '해당 방을 찾을 수 없어요. 방을 새로 만들어주세요!', // 없는 방 또는 모두 나간 방에 참여를 요청할 때
NOT_FINISHED_ROOM: '게임이 아직 종료되지 않았어요. 게임이 끝날 때까지 기다려볼까요?',
NOT_FOUND_ROOM: '방을 찾을 수 없어요. 방을 새로 만들어주세요!', // 없는 방 또는 모두 나간 방에 참여를 요청할 때
CAN_NOT_JOIN_ROOM: '방에 참여할 수 없어요. 방의 진행 상태를 확인해주세요!', // 게임이 대기 상태가 아닐 때 or 잘못된 링크로 접속했을 때

// 유저 관련 에러 (master)
INVALID_NICKNAME: '닉네임은 최소 1글자 이상 최대 12글자 이하여야 합니다.',
Expand Down
1 change: 1 addition & 0 deletions frontend/src/constants/queryKeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ export const QUERY_KEYS = {
isRoomInitial: 'isRoomInitial',
categoryList: 'categoryList',
getUserInfo: 'getUserInfo',
isJoinable: 'isJoinable',
} as const;
21 changes: 21 additions & 0 deletions frontend/src/hooks/useDefaultMutationErrorHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import AlertModal from '@/components/AlertModal/AlertModal';
import useModal from '@/hooks/useModal';
import useToast from '@/hooks/useToast';
import { CustomError, NetworkError } from '@/utils/error';

const useDefaultMutationErrorHandler = () => {
const { show } = useToast();
const { show: showModal } = useModal();

return (error: unknown) => {
if (error instanceof NetworkError) {
show(error.message);
return;
}
if (error instanceof CustomError) {
showModal(AlertModal, { title: '에러', message: error.message });
}
};
};

export default useDefaultMutationErrorHandler;
21 changes: 21 additions & 0 deletions frontend/src/hooks/useThrottle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useRef } from 'react';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const useThrottle = <T extends (...args: any[]) => void>(
func: T,
delay = 3000,
): ((...args: Parameters<T>) => void) => {
const isThrottledRef = useRef(false);

return (...args: Parameters<T>) => {
if (!isThrottledRef.current) {
func(...args);
isThrottledRef.current = true;
setTimeout(() => {
isThrottledRef.current = false;
}, delay);
}
};
};

export default useThrottle;
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,49 @@ import { useMutation } from '@tanstack/react-query';
import { useParams } from 'react-router-dom';

import { voteBalanceContent } from '@/apis/balanceContent';
import useDefaultMutationErrorHandler from '@/hooks/useDefaultMutationErrorHandler';
import useGetUserInfo from '@/hooks/useGetUserInfo';
import useThrottle from '@/hooks/useThrottle';

interface UseSelectCompleteMutationProps {
selectedId: number;
contentId?: number;
contentId: number;
completeSelection: () => void;
cancelSelection: () => void;
}

const useCompleteSelectionMutation = ({
selectedId,
contentId,
completeSelection,
cancelSelection,
}: UseSelectCompleteMutationProps) => {
const { roomId } = useParams();
const {
member: { memberId },
} = useGetUserInfo();
const handleError = useDefaultMutationErrorHandler();

return useMutation({
mutationFn: async () => {
if (typeof contentId === 'undefined') {
throw new Error('contentId 가 존재하지 않습니다.');
}
return await voteBalanceContent({
const completeSelectionMutation = useMutation({
mutationFn: async () =>
await voteBalanceContent({
roomId: Number(roomId),
optionId: selectedId,
contentId,
memberId: Number(memberId),
});
},
onSuccess: () => {
}),
onMutate: () => {
completeSelection();
},
onError: (error) => {
cancelSelection();
handleError(error);
},
});

const throttledVote = useThrottle(completeSelectionMutation.mutate);

return { ...completeSelectionMutation, vote: throttledVote };
};

export default useCompleteSelectionMutation;
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,36 @@ import useCompleteSelectionMutation from './SelectButton.hook';

import Button from '@/components/common/Button/Button';
import { bottomButtonLayout } from '@/components/common/Button/Button.styled';
import { SelectedOption } from '@/types/balanceContent';

interface SelectButtonProps {
contentId: number;
selectedId: number;
selectedOption: SelectedOption;
completeSelection: () => void;
cancelSelection: () => void;
}

const SelectButton = ({ contentId, selectedId, completeSelection }: SelectButtonProps) => {
const {
data,
isPending,
mutate: vote,
} = useCompleteSelectionMutation({
const SelectButton = ({
contentId,
selectedOption,
completeSelection,
cancelSelection,
}: SelectButtonProps) => {
const { id: selectedId, isVoted } = selectedOption;

const { isSuccess, isPending, vote } = useCompleteSelectionMutation({
selectedId,
contentId,
completeSelection,
cancelSelection,
});

return (
<div css={bottomButtonLayout}>
<Button
bottom
disabled={data || !selectedId || isPending}
text={data || isPending ? '선택 완료' : '선택'}
disabled={!selectedId || isVoted || isSuccess || isPending}
text={isSuccess || isPending ? '선택 완료' : '선택'}
onClick={vote}
/>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@ import useBalanceContentQuery from '@/hooks/useBalanceContentQuery';
const SelectContainer = () => {
const { roomId } = useParams();
const { balanceContent } = useBalanceContentQuery(Number(roomId));
const { selectedOption, handleClickOption, completeSelection } = useSelectOption();
const { selectedOption, handleClickOption, completeSelection, cancelSelection } =
useSelectOption();

return (
<div css={selectContainerLayout}>
<Timer
selectedId={selectedOption.id}
isVoted={selectedOption.isCompleted}
selectedOption={selectedOption}
completeSelection={completeSelection}
cancelSelection={cancelSelection}
/>
<section role="radiogroup" css={selectSection}>
<SelectOption
Expand All @@ -35,8 +36,9 @@ const SelectContainer = () => {
</section>
<SelectButton
contentId={balanceContent.contentId}
selectedId={selectedOption.id}
selectedOption={selectedOption}
completeSelection={completeSelection}
cancelSelection={cancelSelection}
/>
</div>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const 클릭되지_않은_옵션: Story = {
option: { name: '100억 빚 송강', optionId: 1 },
selectedOption: {
id: 0,
isCompleted: false,
isVoted: false,
},
},
};
Expand All @@ -29,7 +29,7 @@ export const 클릭된_옵션: Story = {
option: { name: '100억 부자 송강호', optionId: 2 },
selectedOption: {
id: 2,
isCompleted: false,
isVoted: false,
},
},
};
Expand All @@ -39,7 +39,7 @@ export const 선택_완료된_옵션: Story = {
option: { name: '100억 부자 송강호', optionId: 2 },
selectedOption: {
id: 2,
isCompleted: true,
isVoted: true,
},
},
};
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
import { SelectOptionLayout } from './SelectOption.styled';

import { BalanceContent } from '@/types/balanceContent';

interface SelectedOption {
id: number;
isCompleted: boolean;
}
import { BalanceContent, SelectedOption } from '@/types/balanceContent';

interface SelectOptionProps {
option: BalanceContent['firstOption'];
Expand All @@ -14,14 +9,14 @@ interface SelectOptionProps {
}

const SelectOption = ({ option, selectedOption, handleClickOption }: SelectOptionProps) => {
const { id: selectedId, isCompleted } = selectedOption;
const { id: selectedId, isVoted } = selectedOption;

return (
<button
role="radio"
css={SelectOptionLayout(selectedId === option.optionId, isCompleted)}
css={SelectOptionLayout(selectedId === option.optionId, isVoted)}
onClick={() => handleClickOption(option.optionId)}
disabled={isCompleted}
disabled={isVoted}
aria-checked={selectedId === option.optionId}
>
{option.name}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,23 @@ import useVoteIsFinished from '../hooks/useVoteIsFinished';
import DdangkongTimer from '@/assets/images/ddangkongTimer.webp';
import A11yOnly from '@/components/common/a11yOnly/A11yOnly';
import useBalanceContentQuery from '@/hooks/useBalanceContentQuery';
import { SelectedOption } from '@/types/balanceContent';

interface TimerProps {
selectedId: number;
isVoted: boolean;
selectedOption: SelectedOption;
completeSelection: () => void;
cancelSelection: () => void;
}

const Timer = ({ selectedId, isVoted, completeSelection }: TimerProps) => {
const Timer = ({ selectedOption, completeSelection, cancelSelection }: TimerProps) => {
const { roomId } = useParams();
const { balanceContent, isFetching } = useBalanceContentQuery(Number(roomId));
const { leftRoundTime, isAlmostFinished, timeLimit } = useVoteTimer({
roomId: Number(roomId),
selectedId,
isVoted,
selectedId: selectedOption.id,
isVoted: selectedOption.isVoted,
completeSelection,
cancelSelection,
});
const screenReaderLeftRoundTime = `${leftRoundTime}초 남았습니다.`;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,24 @@ interface UseVoteTimerProps {
selectedId: number;
isVoted: boolean;
completeSelection: () => void;
cancelSelection: () => void;
}

const useVoteTimer = ({ roomId, selectedId, isVoted, completeSelection }: UseVoteTimerProps) => {
const useVoteTimer = ({
roomId,
selectedId,
isVoted,
completeSelection,
cancelSelection,
}: UseVoteTimerProps) => {
const { balanceContent } = useBalanceContentQuery(roomId);
const timeLimit = convertMsecToSecond(balanceContent.timeLimit) || DEFAULT_TIME_LIMIT_SEC;

const { mutate: vote } = useCompleteSelectionMutation({
const { vote } = useCompleteSelectionMutation({
selectedId,
contentId: balanceContent.contentId,
completeSelection,
cancelSelection,
});

const { leftRoundTime, isAlmostFinished } = useTimer({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
import { useState } from 'react';

import { SelectedOption } from '@/types/balanceContent';

const useSelectOption = () => {
const [selectedOption, setSelectedOption] = useState({
const [selectedOption, setSelectedOption] = useState<SelectedOption>({
id: 0,
isCompleted: false,
isVoted: false,
});

const handleClickOption = (selectedId: number) => {
setSelectedOption((prev) => ({ ...prev, id: selectedId }));
};

const completeSelection = () => {
setSelectedOption((prev) => ({ ...prev, isCompleted: true }));
setSelectedOption((prev) => ({ ...prev, isVoted: true }));
};

const cancelSelection = () => {
setSelectedOption((prev) => ({ ...prev, isVoted: false }));
};

return { selectedOption, handleClickOption, completeSelection };
return { selectedOption, handleClickOption, completeSelection, cancelSelection };
};

export default useSelectOption;
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import useGetUserInfo from '@/hooks/useGetUserInfo';

const FinalButton = () => {
const { roomId } = useParams();
const { mutate: resetRoom, isPending } = useResetRoomMutation(Number(roomId));
const { mutate: resetRoom, isPending, isSuccess } = useResetRoomMutation(Number(roomId));
const {
member: { isMaster },
} = useGetUserInfo();
Expand All @@ -18,9 +18,9 @@ const FinalButton = () => {
<div css={bottomButtonLayout}>
<Button
style={{ width: '100%' }}
text={getFinalButtonText(isMaster, isPending)}
text={getFinalButtonText(isMaster, isPending, isSuccess)}
onClick={resetRoom}
disabled={!isMaster || isPending}
disabled={!isMaster || isPending || isSuccess}
/>
</div>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const getFinalButtonText = (isMaster: boolean, isPending: boolean) => {
if (isMaster && isPending) return '로딩중...';
const getFinalButtonText = (isMaster: boolean, isPending: boolean, isSuccess: boolean) => {
if (isMaster && (isPending || isSuccess)) return '로딩중...';
if (isMaster) return '대기실로 이동';
return '방장이 진행해 주세요';
};
Expand Down
Loading
Loading