Skip to content

Commit

Permalink
feat: 오답 터뜨리기 api 업데이트
Browse files Browse the repository at this point in the history
  • Loading branch information
rabyeoljji committed Dec 4, 2024
1 parent 47f01d1 commit 748846a
Show file tree
Hide file tree
Showing 9 changed files with 74 additions and 28 deletions.
2 changes: 1 addition & 1 deletion src/features/quiz/components/bomb-quiz/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const BombQuiz = ({
handleExit,
}: Props) => {
const currentQuiz = quizzes[currentIndex]
const currentResult = quizResults[currentIndex]
const currentResult = quizResults[currentIndex] ?? null

return (
<div className="flex h-[70dvh] min-h-fit w-full flex-col items-center justify-between">
Expand Down
43 changes: 31 additions & 12 deletions src/features/quiz/screen/bomb-quiz-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,17 @@ import { getAnswerText } from '../utils'
import { cn } from '@/shared/lib/utils'
import { useQuery } from '@tanstack/react-query'
import { queries } from '@/shared/lib/tanstack-query/query-keys'
import { useUpdateWrongQuizResult } from '@/requests/quiz/hooks'
import { getQueryClient } from '@/shared/lib/tanstack-query/client'
import { useRouter } from 'next/navigation'
// import { quizzes } from '../config'

const BombQuizView = () => {
const router = useRouter()
const queryClient = getQueryClient()
const { data, isPending } = useQuery(queries.quiz.bomb())
const { mutate: updateWrongQuizResultMutate } = useUpdateWrongQuizResult()

const bombQuizList = data?.quizzes ?? []
// const bombQuizList = [...quizzes]

Expand All @@ -29,7 +36,7 @@ const BombQuizView = () => {
currentIndex: currentIndex,
})

const currentQuizInfo = bombQuizList[currentIndex]
const currentQuizInfo = bombQuizList && bombQuizList[currentIndex]
const currentAnswerState = quizResults[currentIndex]?.answer

const onAnswer = ({
Expand All @@ -47,7 +54,7 @@ const BombQuizView = () => {
id,
answer: isRight,
choseAnswer,
elapsedTime: 1, // 임시
elapsedTime: 1,
}
return newResults
})
Expand All @@ -58,20 +65,32 @@ const BombQuizView = () => {
setOpenExplanation(false)
}

const hasNextQuiz = handleNext(currentIndex, bombQuizList.length)
if (hasNextQuiz) {
navigateToNext(currentIndex)
} else {
setProcessingResults(true)
// TODO: 퀴즈 종료 처리 로직 추가 (퀴즈 결과 서버에 전송)
// onSuccess:
// setProcessingResults(false)
// query - 오답 터뜨리기 data 갱신
if (quizResults[currentIndex]) {
const currentResult = {
id: quizResults[currentIndex].id,
answer: quizResults[currentIndex].answer,
}
const requestBody = { quizzes: [currentResult] }
const hasNextQuiz = handleNext(currentIndex, bombQuizList.length)
if (hasNextQuiz) {
updateWrongQuizResultMutate(requestBody, {
onSuccess: () => navigateToNext(currentIndex),
})
} else {
setProcessingResults(true)
updateWrongQuizResultMutate(requestBody, {
onSuccess: async () => {
await queryClient.invalidateQueries(queries.quiz.bomb())
setProcessingResults(false)
},
})
}
}
}

const handleExit = () => {
// TODO:
router.replace('/')
// 추후 결과 업데이트를 list로 확장 시:
// 현재까지 퀴즈 결과 서버에 전송
// onSuccess: 메인 화면으로 이동
}
Expand Down
1 change: 1 addition & 0 deletions src/features/quiz/screen/random-quiz-view/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ interface Props {
const RandomQuizView = ({ bookmarkedCollections }: Props) => {
// 북마크한 컬렉션 가져옴
// 그걸로 컬렉션 리스트 만듦\
// eslint-disable-next-line no-console
console.log(bookmarkedCollections)

// 디렉토리에 생성된 모든 랜덤 퀴즈 가져옴
Expand Down
13 changes: 3 additions & 10 deletions src/firebase/messaging/use-service-worker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,9 @@ import { useEffect } from 'react'
export const useServiceWorker = () => {
useEffect(() => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/firebase-messaging-sw.js')
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.then((registration) => {
// eslint-disable-next-line no-console
console.log('Service Worker 등록 성공: ', registration) // 디버깅용
})
.catch((error) => {
console.error('Service Worker 등록 실패:', error)
})
navigator.serviceWorker.register('/firebase-messaging-sw.js').catch((error) => {
console.error('Service Worker 등록 실패:', error)
})
} else {
console.error('Service Worker가 이 환경에서 지원되지 않습니다.')
}
Expand Down
8 changes: 8 additions & 0 deletions src/requests/quiz/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
fetchDirectoryQuizzes,
fetchTodayQuizSetId,
updateQuizResult,
updateWrongQuizResult,
} from '.'

export const useTodayQuizSetId = () => {
Expand Down Expand Up @@ -44,3 +45,10 @@ export const useUpdateQuizResult = () => {
mutationFn: async (requestBody: Quiz.Request.UpdateQuizResult) => updateQuizResult(requestBody),
})
}

export const useUpdateWrongQuizResult = () => {
return useMutation({
mutationFn: async (requestBody: Quiz.Request.UpdateWrongQuizResult) =>
updateWrongQuizResult(requestBody),
})
}
16 changes: 16 additions & 0 deletions src/requests/quiz/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -202,3 +202,19 @@ export const updateQuizResult = async (requestBody: Quiz.Request.UpdateQuizResul
throw error
}
}

export const updateWrongQuizResult = async (requestBody: Quiz.Request.UpdateWrongQuizResult) => {
const session = await auth()

try {
const response = await http.patch(API_ENDPOINTS.QUIZ.PATCH.UPDATE_WRONG_RESULT, requestBody, {
headers: {
Authorization: `Bearer ${session?.user.accessToken}`,
},
})
// eslint-disable-next-line no-console
console.log(response) // 디버깅용
} catch (error: unknown) {
throw error
}
}
2 changes: 1 addition & 1 deletion src/shared/configs/endpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ export const API_ENDPOINTS = {
UPDATE_RESULT: '/quiz/result',
/** PATCH /quiz/result - 랜덤 퀴즈 결과 업데이트 */
UPDATE_RANDOM_RESULT: '/random-quiz/result',
/** PATCH /quiz/result - 퀴즈 결과 업데이트 */
/** PATCH /quiz/result - 오답 터뜨리기 결과 업데이트 */
UPDATE_WRONG_RESULT: '/wrong-quiz/result',
},
DELETE: {
Expand Down
4 changes: 0 additions & 4 deletions src/shared/hooks/use-messaging.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,6 @@ export const useMessaging = () => {
const token = await getToken()

if (token) {
// eslint-disable-next-line no-console
console.log('FCM 토큰:', token) // 디버깅용

// FCM 토큰을 서버로 전송
postFcmTokenMutate(token)
}
}
Expand Down
13 changes: 13 additions & 0 deletions src/types/quiz.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,14 @@ interface UpdateQuizResultResponse {
currentConsecutiveTodayQuizDate: number
}

/** PATCH /api/v2/wrong-quiz/result */
interface UpdateWrongQuizResultPayload {
quizzes: {
id: number
answer: boolean
}[]
}

/** POST /api/v2/quizzes/documents/{document_id}/custom-quiz-set */
interface CreateReplayQuizSetPayload {
quizType: ReplayQuizType
Expand Down Expand Up @@ -183,6 +191,11 @@ declare namespace Quiz {
* 사용자가 생성한 기존 문서에서 직접 퀴즈 세트 생성(랜덤, OX, 객관식) - 다시풀기 세트 만들기
*/
type CreateReplayQuizSet = CreateReplayQuizSetPayload

/** PATCH /api/v2/wrong-quiz/result
* 오답 터뜨리기 결과 업데이트
*/
type UpdateWrongQuizResult = UpdateWrongQuizResultPayload
}

declare namespace Response {
Expand Down

0 comments on commit 748846a

Please sign in to comment.