|
| 1 | +import { withAuth } from '@/lib/middleware/withAuth'; |
| 2 | +import { withLogging } from '@/lib/middleware/withLogging'; |
| 3 | +import { NextRequest } from 'next/server'; |
| 4 | +import { Op } from 'sequelize'; |
| 5 | +import Challenge from '@/database/models/Challenge'; |
| 6 | +import Users from '@/database/models/User'; |
| 7 | +import ChallengeParticipants from '@/database/models/ChallengeParticipants'; |
| 8 | +import resUtil from '@/lib/utils/responseUtil'; |
| 9 | +import getUserFromRequest from '@/lib/utils/getUserFromRequest'; |
| 10 | + |
| 11 | +async function getHandler(req: NextRequest) { |
| 12 | + try { |
| 13 | + const challengeId = Number(req.nextUrl.pathname.split('/')[3]); |
| 14 | + if (!challengeId) { |
| 15 | + return resUtil.successFalse({ |
| 16 | + status: 400, |
| 17 | + message: '챌린지 ID가 제공되지 않았습니다', |
| 18 | + }); |
| 19 | + } |
| 20 | + |
| 21 | + const challenge = await Challenge.findOne({ |
| 22 | + where: { id: challengeId }, |
| 23 | + include: [ |
| 24 | + { |
| 25 | + model: Users, |
| 26 | + as: 'User', |
| 27 | + attributes: ['name', 'profileImg'], |
| 28 | + }, |
| 29 | + ], |
| 30 | + }); |
| 31 | + |
| 32 | + if (!challenge) { |
| 33 | + return resUtil.successFalse({ |
| 34 | + status: 404, |
| 35 | + message: '해당 챌린지를 찾을 수 없습니다', |
| 36 | + }); |
| 37 | + } |
| 38 | + |
| 39 | + const userId = challenge.userId; |
| 40 | + |
| 41 | + const totalChallenges = await Challenge.count({ |
| 42 | + where: { userId }, |
| 43 | + }); |
| 44 | + |
| 45 | + const recentChallenges = await Challenge.findAll({ |
| 46 | + where: { |
| 47 | + userId, |
| 48 | + id: { [Op.ne]: challengeId }, |
| 49 | + }, |
| 50 | + order: [['createdAt', 'DESC']], |
| 51 | + limit: 6, |
| 52 | + }); |
| 53 | + |
| 54 | + const loginUser = await getUserFromRequest(); |
| 55 | + |
| 56 | + let joinStatus: 'not_joined' | 'in_progress' | 'completed' | 'failed' = |
| 57 | + 'not_joined'; |
| 58 | + |
| 59 | + if (loginUser) { |
| 60 | + const participant = await ChallengeParticipants.findOne({ |
| 61 | + where: { |
| 62 | + challengeId, |
| 63 | + userId: loginUser.id, |
| 64 | + }, |
| 65 | + }); |
| 66 | + |
| 67 | + if (participant) { |
| 68 | + if (participant.status === 'completed') { |
| 69 | + joinStatus = 'completed'; |
| 70 | + } else if (participant.status === 'failed') { |
| 71 | + joinStatus = 'failed'; |
| 72 | + } else { |
| 73 | + joinStatus = 'in_progress'; |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return resUtil.successTrue({ |
| 79 | + status: 200, |
| 80 | + message: '챌린지 조회 성공', |
| 81 | + data: { |
| 82 | + challenge, |
| 83 | + totalChallenges, |
| 84 | + recentChallenges, |
| 85 | + joinStatus, |
| 86 | + }, |
| 87 | + }); |
| 88 | + } catch (err) { |
| 89 | + return resUtil.unknownError({ data: { err } }); |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +const GetChallengeById = withLogging(withAuth(getHandler)); |
| 94 | +export const GET = GetChallengeById; |
0 commit comments