70 lines
1.9 KiB
TypeScript
70 lines
1.9 KiB
TypeScript
import 'dotenv/config';
|
|
import { drizzle } from 'drizzle-orm/node-postgres';
|
|
import { sql, eq, and } from 'drizzle-orm';
|
|
import arrayShuffle from 'array-shuffle';
|
|
import { tasks, questions, categories_db } from '@/src/db/schema';
|
|
import type { BasicQuestion } from '~/types';
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const query = getQuery(event);
|
|
const category = query.category;
|
|
const categories = [
|
|
'A',
|
|
'B',
|
|
'C',
|
|
'D',
|
|
'T',
|
|
'AM',
|
|
'A1',
|
|
'A2',
|
|
'B1',
|
|
'C1',
|
|
'D1',
|
|
'PT',
|
|
];
|
|
|
|
if (category === '' || typeof category !== 'string') {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage:
|
|
'category argument has to be string (or not to be defined at all)',
|
|
});
|
|
}
|
|
if (!categories.includes(`${category.toUpperCase()}`)) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: `category argument has to be equal to: ${categories}`,
|
|
});
|
|
}
|
|
|
|
async function getFromDb(points: number, limit: number, category: string) {
|
|
return await db
|
|
.select({
|
|
id: tasks.id,
|
|
correct_answer: tasks.correct_answer,
|
|
media_url: tasks.media_url,
|
|
weight: tasks.weight,
|
|
text: questions.text,
|
|
})
|
|
.from(tasks)
|
|
.leftJoin(questions, eq(questions.task_id, tasks.id))
|
|
.leftJoin(categories_db, eq(categories_db.task_id, tasks.id))
|
|
.where(
|
|
and(
|
|
eq(categories_db.name, category.toUpperCase()),
|
|
eq(questions.lang, 'PL'),
|
|
eq(tasks.weight, points),
|
|
),
|
|
)
|
|
.orderBy(sql`RANDOM()`)
|
|
.limit(limit);
|
|
}
|
|
const db = drizzle(process.env.DATABASE_URL!);
|
|
|
|
const randomizedQuestions: BasicQuestion[] = [];
|
|
|
|
for (const [key, value] of Object.entries({ 1: 4, 2: 6, 3: 10 })) {
|
|
randomizedQuestions.push(...(await getFromDb(+key, value, category)));
|
|
}
|
|
return arrayShuffle(randomizedQuestions);
|
|
});
|