2024-05-08 00:19:13 +00:00
|
|
|
import db from '../../../../db';
|
2023-12-28 20:16:36 +00:00
|
|
|
import { error, json } from '@sveltejs/kit';
|
2024-02-15 01:48:47 +00:00
|
|
|
import { asc, count } from 'drizzle-orm';
|
2024-05-08 00:19:13 +00:00
|
|
|
import { games, type Games } from '$db/schema';
|
2023-12-28 20:16:36 +00:00
|
|
|
|
2024-02-15 01:48:47 +00:00
|
|
|
export const GET = async ({ url }) => {
|
2023-12-28 20:16:36 +00:00
|
|
|
const searchParams = Object.fromEntries(url.searchParams);
|
|
|
|
|
const limit = parseInt(searchParams?.limit) || 1;
|
|
|
|
|
|
|
|
|
|
if (limit <= 0 || limit > 6) {
|
|
|
|
|
error(400, { message: 'Limit must be between 1 and 6' });
|
|
|
|
|
}
|
|
|
|
|
|
2024-02-06 07:18:13 +00:00
|
|
|
try {
|
2024-02-07 01:08:03 +00:00
|
|
|
const totalGames = await db
|
|
|
|
|
.select({
|
2024-05-08 00:19:13 +00:00
|
|
|
value: count(games.id),
|
2024-02-07 01:08:03 +00:00
|
|
|
})
|
|
|
|
|
.from(games);
|
|
|
|
|
const numberOfGames = totalGames[0].value || 0;
|
|
|
|
|
const randomIndex = Math.floor(Math.random() * numberOfGames);
|
2024-05-08 00:19:13 +00:00
|
|
|
const randomGames: Games[] = await db
|
|
|
|
|
.select()
|
2024-02-06 07:18:13 +00:00
|
|
|
.from(games)
|
|
|
|
|
.orderBy(asc(games.id))
|
|
|
|
|
.limit(limit)
|
|
|
|
|
.offset(randomIndex);
|
|
|
|
|
return json(randomGames);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
|
|
|
|
throw error(500, { message: 'Something went wrong' });
|
|
|
|
|
}
|
2024-05-08 00:19:13 +00:00
|
|
|
};
|