@@ -226,16 +226,27 @@ export async function getSuitableQuestion(message: EachMessagePayload) {
226
226
227
227
async function findSuitableQuestion ( categoryName : string , difficulty : string ) {
228
228
try {
229
- const category = await categoryModel . findOne ( {
230
- name : new RegExp ( `^${ categoryName } $` , "i" ) ,
231
- } ) ;
229
+ let category = null ;
230
+
231
+ if ( categoryName . toLowerCase ( ) !== "all" ) {
232
+ category = await categoryModel . findOne ( {
233
+ name : new RegExp ( `^${ categoryName } $` , "i" ) ,
234
+ } ) ;
232
235
233
- if ( ! category ) {
234
- throw new Error ( `Category '${ categoryName } ' not found.` ) ;
236
+ if ( ! category ) {
237
+ throw new Error ( `Category '${ categoryName } ' not found.` ) ;
238
+ }
239
+ }
240
+
241
+ // If difficulty is "any", return any question from the category
242
+ if ( difficulty . toLowerCase ( ) === "all" ) {
243
+ return await questionModel . findOne ( {
244
+ ...( category ? { categories : category . _id } : { } ) ,
245
+ } ) ;
235
246
}
236
247
237
248
let question = await questionModel . findOne ( {
238
- categories : category . _id ,
249
+ ... ( category ? { categories : category . _id } : { } ) ,
239
250
difficulty : new RegExp ( `^${ difficulty } $` , "i" ) ,
240
251
} ) ;
241
252
@@ -248,21 +259,21 @@ async function findSuitableQuestion(categoryName: string, difficulty: string) {
248
259
throw new Error ( `Invalid difficulty level: ${ difficulty } ` ) ;
249
260
}
250
261
251
- // Find lower difficulty question if not found
262
+ // Find lower difficulty question if exact match is not found
252
263
for ( let i = difficultyIndex - 1 ; i >= 0 ; i -- ) {
253
264
question = await questionModel . findOne ( {
254
- categories : category . _id ,
265
+ ... ( category ? { categories : category . _id } : { } ) ,
255
266
difficulty : new RegExp ( `^${ DIFFICULTIES [ i ] } $` , "i" ) ,
256
267
} ) ;
257
268
if ( question ) {
258
269
return question ;
259
270
}
260
271
}
261
272
262
- // Find higher difficulty question if not found
273
+ // Find higher difficulty question if lower difficulty not found
263
274
for ( let i = difficultyIndex + 1 ; i < DIFFICULTIES . length ; i ++ ) {
264
275
question = await questionModel . findOne ( {
265
- categories : category . _id ,
276
+ ... ( category ? { categories : category . _id } : { } ) ,
266
277
difficulty : new RegExp ( `^${ DIFFICULTIES [ i ] } $` , "i" ) ,
267
278
} ) ;
268
279
if ( question ) {
0 commit comments