File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
question-service/src/routes Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ // src/routes/items.ts
2
+ import express , { Request , Response } from 'express' ;
3
+ import { Collection } from 'mongodb' ;
4
+ import { connectToDB } from '../db/mongoClient' ;
5
+ import { UserQuestions } from '../models/types' ;
6
+
7
+ const router = express . Router ( ) ;
8
+ let questionsCollection : Collection < UserQuestions > ;
9
+
10
+ // Middleware to connect to MongoDB and get the collection
11
+ router . use ( async ( _ , res , next ) => {
12
+ try {
13
+ const db = await connectToDB ( ) ;
14
+ questionsCollection = db . collection < UserQuestions > ( 'userQuestions' ) ;
15
+ next ( ) ;
16
+ } catch ( error ) {
17
+ res . status ( 500 ) . json ( { error : "Failed to connect to MongoDB" } ) ;
18
+ }
19
+ } ) ;
20
+
21
+ // GET all items
22
+ router . get ( '/' , async ( req : Request , res : Response ) => {
23
+ try {
24
+ const items = await questionsCollection . find ( ) . toArray ( ) ;
25
+ res . status ( 200 ) . json ( items ) ;
26
+ } catch ( error ) {
27
+ res . status ( 500 ) . json ( { error : "Failed to fetch items" } ) ;
28
+ }
29
+ } ) ;
30
+
31
+ // POST new item
32
+
33
+ export default router ;
You can’t perform that action at this time.
0 commit comments