test leaving challange invited to

This commit is contained in:
2026-01-30 19:45:22 -05:00
parent 94c9e28393
commit 75d6eb8bbc
3 changed files with 69 additions and 1 deletions

View File

@@ -213,6 +213,43 @@ router.post('/:id/respond', authMiddleware, asyncHandler(async (req, res) => {
res.json({ status });
}));
// Leave a challenge (participants only, not creator)
router.post('/:id/leave', authMiddleware, asyncHandler(async (req, res) => {
const challengeId = req.params.id;
// Get challenge to verify it exists and user is not creator
const challenges = await query(
'SELECT * FROM challenges WHERE id = ?',
[challengeId]
);
if (challenges.length === 0) {
throw new AppError('Challenge not found', 404);
}
const challenge = challenges[0];
if (challenge.created_by === req.user.userId) {
throw new AppError('Challenge creator cannot leave. Delete the challenge instead.', 403);
}
// Check if user is a participant
const participation = await query(
'SELECT * FROM challenge_participants WHERE challenge_id = ? AND user_id = ?',
[challengeId, req.user.userId]
);
if (participation.length === 0) {
throw new AppError('You are not a participant of this challenge', 404);
}
// Delete user's participation and predictions
await query('DELETE FROM predictions WHERE challenge_id = ? AND user_id = ?', [challengeId, req.user.userId]);
await query('DELETE FROM challenge_participants WHERE challenge_id = ? AND user_id = ?', [challengeId, req.user.userId]);
res.json({ success: true, message: 'Left challenge successfully' });
}));
// Delete a challenge (only creator can delete)
router.delete('/:id', authMiddleware, asyncHandler(async (req, res) => {
const challengeId = req.params.id;