1
- import { and , arrayOverlaps , eq , ilike , notInArray , sql } from 'drizzle-orm' ;
1
+ import { and , arrayOverlaps , eq , ilike , inArray , not , sql } from 'drizzle-orm' ;
2
2
3
3
import { db } from '@/lib/db/index' ;
4
4
import { questions } from '@/lib/db/schema' ;
@@ -92,31 +92,45 @@ export const getQuestionDetailsService = async (
92
92
export const getRandomQuestionService = async (
93
93
payload : IGetRandomQuestionPayload
94
94
) : Promise < IGetRandomQuestionResponse > => {
95
- const { attemptedQuestions , difficulty, topic } = payload ;
95
+ const { difficulty, topic, attemptedQuestions } = payload ;
96
96
const whereClause = [ ] ;
97
97
98
+ console . log ( 'Starting query construction' ) ;
99
+
98
100
if ( difficulty ) {
101
+ console . log ( `Adding difficulty filter: ${ difficulty } ` ) ;
99
102
whereClause . push ( eq ( questions . difficulty , difficulty ) ) ;
100
103
}
101
104
102
- if ( topic && topic . length > 0 ) {
103
- whereClause . push ( arrayOverlaps ( questions . topic , topic ) ) ;
105
+ const topicArray = ( Array . isArray ( topic ) ? topic : [ topic ] ) . filter (
106
+ ( t ) : t is string => t !== undefined
107
+ ) ;
108
+ if ( topicArray . length > 0 ) {
109
+ whereClause . push ( arrayOverlaps ( questions . topic , topicArray ) ) ;
104
110
}
105
111
106
112
if ( attemptedQuestions && attemptedQuestions . length > 0 ) {
107
- whereClause . push ( notInArray ( questions . id , attemptedQuestions ) ) ;
113
+ console . log ( `Excluding attempted questions: ${ attemptedQuestions . join ( ', ' ) } ` ) ;
114
+ whereClause . push ( not ( inArray ( questions . id , attemptedQuestions ) ) ) ;
108
115
}
109
116
110
- // randomize the order of questions
111
- const query = db
112
- . select ( )
113
- . from ( questions )
114
- . where ( and ( ...whereClause ) )
115
- . orderBy ( sql `RANDOM()` )
116
- . limit ( 1 ) ;
117
+ console . log ( `Where clause conditions: ${ whereClause . length } ` ) ;
118
+
119
+ let query = db . select ( ) . from ( questions ) ;
120
+
121
+ if ( whereClause . length > 0 ) {
122
+ query = query . where ( and ( ...whereClause ) ) as typeof query ;
123
+ }
124
+
125
+ query = ( query as any ) . orderBy ( sql `RANDOM()` ) . limit ( 1 ) ;
126
+
127
+ console . log ( 'Executing query' ) ;
128
+ console . log ( query . toSQL ( ) ) ; // This will log the SQL query
117
129
118
130
const result = await query ;
119
131
132
+ console . log ( `Query result: ${ JSON . stringify ( result ) } ` ) ;
133
+
120
134
if ( result . length === 0 ) {
121
135
return {
122
136
code : StatusCodes . NOT_FOUND ,
@@ -126,7 +140,6 @@ export const getRandomQuestionService = async (
126
140
} ,
127
141
} ;
128
142
}
129
-
130
143
return {
131
144
code : StatusCodes . OK ,
132
145
data : { question : result [ 0 ] } ,
0 commit comments