|
1 | | -export default function Page() { |
| 1 | +import { sql } from "drizzle-orm"; |
| 2 | +import { getAuth } from "~/lib/auth"; |
| 3 | +import { getDB } from "~/lib/db"; |
| 4 | +import { hai, haiyama } from "~/lib/db/schema"; |
| 5 | +import { dbHaiToHai } from "~/lib/hai"; |
| 6 | +import type { Route } from "./+types/play"; |
| 7 | + |
| 8 | +export async function loader({ context, request }: Route.LoaderArgs) { |
| 9 | + const { env } = context.cloudflare; |
| 10 | + const db = getDB(env); |
| 11 | + const auth = getAuth(env); |
| 12 | + const session = await auth.api.getSession({ headers: request.headers }); |
| 13 | + if (!session?.user?.id) { |
| 14 | + throw new Response("Unauthorized", { status: 401 }); |
| 15 | + } |
| 16 | + const userId = session.user.id; |
| 17 | + |
| 18 | + const randomHaiyama = await db |
| 19 | + .select() |
| 20 | + .from(haiyama) |
| 21 | + .orderBy(sql`RANDOM()`) |
| 22 | + .limit(1); |
| 23 | + |
| 24 | + if (randomHaiyama.length === 0) { |
| 25 | + throw new Response("No haiyama found", { status: 404 }); |
| 26 | + } |
| 27 | + const selectedHaiyama = randomHaiyama[0]; |
| 28 | + const rawHaiData = await db |
| 29 | + .select() |
| 30 | + .from(hai) |
| 31 | + .where(sql`${hai.haiyamaId} = ${selectedHaiyama.id}`) |
| 32 | + .orderBy(hai.order); |
| 33 | + const haiData = rawHaiData.map((hai) => dbHaiToHai(hai)); |
| 34 | + //TODO: store data in redis |
| 35 | + return haiData; |
| 36 | +} |
| 37 | + |
| 38 | +export default function Page({ loaderData }: Route.ComponentProps) { |
| 39 | + console.log(loaderData); |
2 | 40 | return ( |
3 | 41 | <> |
4 | 42 | <p>Play Page</p> |
|
0 commit comments