@@ -28,4 +28,77 @@ router.get('/', async (req: Request, res: Response) => {
28
28
}
29
29
} ) ;
30
30
31
+ // Update a question
32
+ router . put ( '/:questionId' , async ( req : Request , res : Response ) => {
33
+ const { questionId } = req . params ;
34
+ const updatedQuestion : Questions = req . body ;
35
+
36
+ try {
37
+ if ( ! updatedQuestion || typeof updatedQuestion !== 'object' ) {
38
+ return res . status ( 400 ) . json ( { error : 'Invalid question data.' } ) ;
39
+ }
40
+
41
+ const result = await questionsCollection . updateOne (
42
+ { _question_id : Number ( questionId ) } ,
43
+ { $set : updatedQuestion }
44
+ ) ;
45
+
46
+ if ( result . matchedCount === 0 ) {
47
+ return res . status ( 404 ) . json ( { error : 'Question not found.' } ) ;
48
+ }
49
+
50
+ res . status ( 200 ) . json ( { message : 'Question updated successfully' } ) ;
51
+ } catch ( error ) {
52
+ console . error ( 'Error updating question:' , error ) ;
53
+ res . status ( 500 ) . json ( { error : 'Failed to update question' } ) ;
54
+ }
55
+ } ) ;
56
+
57
+ // POST a new question
58
+ router . post ( '/' , async ( req : Request , res : Response ) => {
59
+ try {
60
+ const newQuestion : Questions = req . body ; // Assume the body contains a question object
61
+
62
+ const { _question_id, difficulty, description, examples, constraints, tags, title_slug, title, pictures } = newQuestion ;
63
+
64
+ if (
65
+ typeof _question_id !== 'number' ||
66
+ typeof difficulty !== 'number' ||
67
+ typeof description !== 'string' ||
68
+ ! Array . isArray ( examples ) ||
69
+ typeof constraints !== 'string' ||
70
+ ! Array . isArray ( tags ) ||
71
+ typeof title_slug !== 'string' ||
72
+ typeof title !== 'string'
73
+ ) {
74
+ return res . status ( 400 ) . json ( { error : 'Invalid question data. Please check your input.' } ) ;
75
+ }
76
+
77
+ const result = await questionsCollection . insertOne ( newQuestion ) ;
78
+
79
+ res . status ( 201 ) . json ( { message : 'Question inserted successfully' , questionId : result . insertedId } ) ;
80
+ } catch ( error ) {
81
+ console . error ( 'Error inserting question:' , error ) ;
82
+ res . status ( 500 ) . json ( { error : 'Failed to insert question' } ) ;
83
+ }
84
+ } ) ;
85
+
86
+ // DELETE a question
87
+ router . delete ( '/:questionId' , async ( req : Request , res : Response ) => {
88
+ const { questionId } = req . params ;
89
+
90
+ try {
91
+ const result = await questionsCollection . deleteOne ( { _question_id : Number ( questionId ) } ) ;
92
+
93
+ if ( result . deletedCount === 0 ) {
94
+ return res . status ( 404 ) . json ( { error : 'Question not found.' } ) ;
95
+ }
96
+
97
+ res . status ( 200 ) . json ( { message : 'Question deleted successfully' } ) ;
98
+ } catch ( error ) {
99
+ console . error ( 'Error deleting question:' , error ) ;
100
+ res . status ( 500 ) . json ( { error : 'Failed to delete question' } ) ;
101
+ }
102
+ } ) ;
103
+
31
104
export default router ;
0 commit comments