|
1 | 1 | import { Request, Response } from 'express';
|
| 2 | +import { StatusCodes } from 'http-status-codes'; |
2 | 3 |
|
3 |
| -import { addAttempt } from '../services/post/addAttempt'; |
| 4 | +import { logger } from '@/lib/utils'; |
| 5 | +import { isValidUUID } from '@/lib/uuid'; |
| 6 | +import { getQuestionAttempts } from '@/services/get/get-attempts'; |
| 7 | +import { addAttempt } from '@/services/post/addAttempt'; |
4 | 8 |
|
5 | 9 | // Define the expected request body structure
|
6 | 10 | interface AddAttemptRequestBody {
|
@@ -34,14 +38,40 @@ export const createAttempt = async (
|
34 | 38 | });
|
35 | 39 |
|
36 | 40 | // Respond with success
|
37 |
| - res.status(201).json({ message: 'Attempt added successfully', result }); |
38 |
| - } catch (error) { |
39 |
| - console.error('Error adding attempt:', error); |
| 41 | + res.status(StatusCodes.OK).json({ message: 'Attempt added successfully', result }); |
| 42 | + } catch (err) { |
| 43 | + const { name, message, stack, cause } = err as Error; |
| 44 | + logger.error({ name, message, stack, cause }, 'Error adding attempt'); |
40 | 45 |
|
41 | 46 | // Enhanced error response with error details
|
42 | 47 | res.status(500).json({
|
43 | 48 | error: 'Error adding attempt',
|
44 |
| - details: error instanceof Error ? error.message : 'Unknown error', |
| 49 | + details: err instanceof Error ? err.message : 'Unknown error', |
| 50 | + }); |
| 51 | + } |
| 52 | +}; |
| 53 | + |
| 54 | +export const getAttempts = async ( |
| 55 | + req: Request<unknown, unknown, Partial<Parameters<typeof getQuestionAttempts>[0]>, unknown>, |
| 56 | + res: Response |
| 57 | +) => { |
| 58 | + const { questionId, userId, limit, offset } = req.body; |
| 59 | + |
| 60 | + if (!questionId || isNaN(questionId) || !userId || !isValidUUID(userId)) { |
| 61 | + return res.status(StatusCodes.UNPROCESSABLE_ENTITY).json('Malformed Request'); |
| 62 | + } |
| 63 | + |
| 64 | + try { |
| 65 | + const result = await getQuestionAttempts({ questionId, userId, limit, offset }); |
| 66 | + return res.status(StatusCodes.OK).json(result); |
| 67 | + } catch (err) { |
| 68 | + const { name, message, stack, cause } = err as Error; |
| 69 | + logger.error({ name, message, stack, cause }, 'Error retrieving attempts'); |
| 70 | + |
| 71 | + // Enhanced error response with error details |
| 72 | + res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({ |
| 73 | + error: 'Error retrieving attempts', |
| 74 | + details: err instanceof Error ? err.message : 'Unknown error', |
45 | 75 | });
|
46 | 76 | }
|
47 | 77 | };
|
0 commit comments