1
- // src/routes/items.ts
2
1
import express , { Request , Response } from 'express' ;
3
2
import { Collection , ObjectId } from 'mongodb' ;
4
3
import { connectToDB } from '../db/mongoClient' ;
@@ -21,20 +20,27 @@ router.use(async (_, res, next) => {
21
20
}
22
21
} ) ;
23
22
24
- // GET all items
23
+ // GET all items with filters
25
24
router . get ( '/' , async ( req : Request , res : Response ) => {
26
25
try {
27
- const { difficulty, status, topics } = req . query ;
26
+ const { difficulty, status, topics, search } = req . query ;
28
27
29
- let query = { } ;
28
+ let query : any = { } ;
30
29
if ( difficulty ) {
31
- query = { ... query , difficulty : parseInt ( difficulty as string ) } ;
30
+ query . difficulty = parseInt ( difficulty as string ) ;
32
31
}
33
32
if ( status ) {
34
- query = { ... query , status : status as string } ;
33
+ query . status = status as string ;
35
34
}
36
- if ( topics ) {
37
- query = { ...query , topics : topics as string [ ] } ;
35
+ if ( topics && typeof topics === 'string' ) {
36
+ const topicsArray = topics . split ( ',' ) ;
37
+ query . tags = { $in : topicsArray } ;
38
+ }
39
+ if ( search && typeof search === 'string' ) {
40
+ query . $or = [
41
+ { title : { $regex : search , $options : 'i' } } , // only search in title
42
+ // { description: { $regex: search, $options: 'i' } },
43
+ ] ;
38
44
}
39
45
40
46
const items = await questionsCollection . find ( query ) . toArray ( ) ;
@@ -142,4 +148,23 @@ router.delete('/:id', async (req: Request, res: Response) => {
142
148
}
143
149
} ) ;
144
150
151
+ // GET all unique tags
152
+ router . get ( '/tags' , async ( _ : Request , res : Response ) => {
153
+ try {
154
+ const uniqueTags = await questionsCollection
155
+ . aggregate ( [
156
+ { $unwind : '$tags' } ,
157
+ { $group : { _id : '$tags' } } ,
158
+ { $project : { _id : 0 , tag : '$_id' } } ,
159
+ ] )
160
+ . toArray ( ) ;
161
+
162
+ const tags = uniqueTags . map ( ( item ) => item . tag ) ;
163
+ res . status ( 200 ) . json ( tags ) ;
164
+ } catch ( error ) {
165
+ console . error ( 'Error fetching tags:' , error ) ;
166
+ res . status ( 500 ) . json ( { error : 'Failed to fetch tags' } ) ;
167
+ }
168
+ } ) ;
169
+
145
170
export default router ;
0 commit comments