1
1
import { Request , Response } from "express" ;
2
2
import Question from "../models/Question.ts" ;
3
+ import { checkIsExistingQuestion } from "../utils/utils.ts" ;
4
+ import { DUPLICATE_QUESTION_RESPONSE_MESSAGE } from "../utils/constants.ts" ;
3
5
4
6
export const createQuestion = async (
5
7
req : Request ,
@@ -8,14 +10,10 @@ export const createQuestion = async (
8
10
try {
9
11
const { title, description, complexity, category } = req . body ;
10
12
11
- const existingQuestion = await Question . findOne ( {
12
- title : new RegExp ( `^${ title } $` , "i" ) ,
13
- } ) ;
14
-
13
+ const existingQuestion = await checkIsExistingQuestion ( title ) ;
15
14
if ( existingQuestion ) {
16
15
res . status ( 400 ) . json ( {
17
- message :
18
- "Duplicate question: A question with the same title already exists." ,
16
+ message : DUPLICATE_QUESTION_RESPONSE_MESSAGE ,
19
17
} ) ;
20
18
return ;
21
19
}
@@ -44,14 +42,26 @@ export const updateQuestion = async (
44
42
) : Promise < void > => {
45
43
try {
46
44
const { id } = req . params ;
47
- const updatedQuestion = await Question . findByIdAndUpdate ( id , req . body , {
48
- new : true ,
49
- } ) ;
50
- if ( ! updatedQuestion ) {
45
+ const { title } = req . body ;
46
+
47
+ const currentQuestion = await Question . findById ( id ) ;
48
+ if ( ! currentQuestion ) {
51
49
res . status ( 404 ) . json ( { message : "Question not found" } ) ;
52
50
return ;
53
51
}
54
52
53
+ const existingQuestion = await checkIsExistingQuestion ( title , id ) ;
54
+ if ( existingQuestion ) {
55
+ res . status ( 400 ) . json ( {
56
+ message : DUPLICATE_QUESTION_RESPONSE_MESSAGE ,
57
+ } ) ;
58
+ return ;
59
+ }
60
+
61
+ const updatedQuestion = await Question . findByIdAndUpdate ( id , req . body , {
62
+ new : true ,
63
+ } ) ;
64
+
55
65
res . status ( 200 ) . json ( {
56
66
message : "Question updated successfully" ,
57
67
question : updatedQuestion ,
0 commit comments