Skip to content

Commit 0f63d5b

Browse files
committed
feat: added validation to exam controller
1 parent aa2379a commit 0f63d5b

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

controller/exam.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,27 @@ import {
55
updateExamById,
66
} from "#services/exam";
77
import { logger } from "#util";
8+
import { isEntityIdValid } from "#middleware/entityIdValidation";
9+
import Infrastructure from "#models/infrastructure";
10+
import Course from "#models/course";
11+
import Faculty from "#models/faculty";
812

913
async function addExam(req, res) {
1014
const { date, startTime, duration, infrastructure, supervisor, course } =
1115
req.body;
16+
17+
// Checking if the provided IDs exist in the database
18+
const isInfrastructureValid = await isEntityIdValid(
19+
infrastructure,
20+
Infrastructure,
21+
);
22+
const isSupervisorValid = await isEntityIdValid(supervisor, Faculty);
23+
const isCourseValid = await isEntityIdValid(course, Course);
24+
25+
if (!isInfrastructureValid || !isSupervisorValid || !isCourseValid) {
26+
res.status(400).json({ error: "Invalid ID(s)" });
27+
}
28+
1229
try {
1330
const exam = await createExam(
1431
date,

middleware/EntityIdValidation.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export async function isEntityIdValid(entityId, EntityModel) {
2+
// Checking if the provided ID exists in the database collection
3+
const entity = await EntityModel.findById(entityId);
4+
5+
return !!entity;
6+
}

0 commit comments

Comments
 (0)