Skip to content

Commit cb3300c

Browse files
committed
update question logic to handle "all" difficulties and/or categories
1 parent a75a455 commit cb3300c

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

backend/question-service/controllers/questionsController.ts

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -226,16 +226,27 @@ export async function getSuitableQuestion(message: EachMessagePayload) {
226226

227227
async function findSuitableQuestion(categoryName: string, difficulty: string) {
228228
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+
});
232235

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+
});
235246
}
236247

237248
let question = await questionModel.findOne({
238-
categories: category._id,
249+
...(category ? { categories: category._id } : {}),
239250
difficulty: new RegExp(`^${difficulty}$`, "i"),
240251
});
241252

@@ -248,21 +259,21 @@ async function findSuitableQuestion(categoryName: string, difficulty: string) {
248259
throw new Error(`Invalid difficulty level: ${difficulty}`);
249260
}
250261

251-
// Find lower difficulty question if not found
262+
// Find lower difficulty question if exact match is not found
252263
for (let i = difficultyIndex - 1; i >= 0; i--) {
253264
question = await questionModel.findOne({
254-
categories: category._id,
265+
...(category ? { categories: category._id } : {}),
255266
difficulty: new RegExp(`^${DIFFICULTIES[i]}$`, "i"),
256267
});
257268
if (question) {
258269
return question;
259270
}
260271
}
261272

262-
// Find higher difficulty question if not found
273+
// Find higher difficulty question if lower difficulty not found
263274
for (let i = difficultyIndex + 1; i < DIFFICULTIES.length; i++) {
264275
question = await questionModel.findOne({
265-
categories: category._id,
276+
...(category ? { categories: category._id } : {}),
266277
difficulty: new RegExp(`^${DIFFICULTIES[i]}$`, "i"),
267278
});
268279
if (question) {

0 commit comments

Comments
 (0)