diff --git a/src/apis/v1/exam/controller.ts b/src/apis/v1/exam/controller.ts index 1b9ebde..3c51e22 100644 --- a/src/apis/v1/exam/controller.ts +++ b/src/apis/v1/exam/controller.ts @@ -52,3 +52,9 @@ export const deleteExam = async (req: RequestWithUser, res: Response) => { res.send(fmt.formatResponse(result, Date.now() - req.startTime, 'OK')); }; + +export const getExamsBySubjectId = async (req: RequestWithUser, res: Response) => { + const input: ParamsExamDto = req.params; + const result = await service.getExamsBySubjectId(input.id); + res.send(fmt.formatResponse(result, Date.now() - req.startTime, 'OK')); +}; diff --git a/src/apis/v1/exam/index.ts b/src/apis/v1/exam/index.ts index 628c47b..15fe1af 100644 --- a/src/apis/v1/exam/index.ts +++ b/src/apis/v1/exam/index.ts @@ -24,6 +24,13 @@ router.get( asyncRouteHandler(controller.getExamById) ); +router.get( + '/subject/:id', + authMiddleware, + validationMiddleware(ParamsExamDto, APP_CONSTANTS.params), + asyncRouteHandler(controller.getExamsBySubjectId) +); + router.post( '/', authMiddleware, diff --git a/src/apis/v1/exam/service.ts b/src/apis/v1/exam/service.ts index 98a3c88..0caaf0c 100644 --- a/src/apis/v1/exam/service.ts +++ b/src/apis/v1/exam/service.ts @@ -177,3 +177,25 @@ export const deleteExam = async (id: string) => { throw new HttpException(400, ErrorCodes.BAD_REQUEST.MESSAGE, ErrorCodes.BAD_REQUEST.CODE); } }; + +export const getExamsBySubjectId = async (subjectId: string) => { + try { + const results = ExamModel.find({ is_approved: true, subject: subjectId }) + .populate('author', '-is_blocked -roles -created_at -updated_at -__v') + .populate('question', '-is_blocked -roles -created_at -updated_at -__v') + .populate('subject', '-is_deleted -created_at -updated_at -__v'); + + const subject = SubjectModel.findOne({ _id: subjectId }); + + const resultAll = await Promise.all([results, subject]); + + logger.info(`Get all exams by subjectId successfully`); + return { + exams: resultAll[0], + subject: resultAll[1], + }; + } catch (error) { + logger.error(`Error while get exams by subjectId: ${error}`); + throw new HttpException(400, ErrorCodes.BAD_REQUEST.MESSAGE, ErrorCodes.BAD_REQUEST.CODE); + } +};