export const prerender = false; import type { APIRoute } from "astro"; import { and, desc, eq } from "drizzle-orm"; import { createDb } from "@/db"; import { comments, events, markets, notifications, positions, profiles } from "@/db/schema"; import { authenticate } from "@/lib/auth"; export const GET: APIRoute = async ({ request, locals }) => { const runtime = locals.runtime as { env: { DATABASE_URL: string } }; const db = createDb(runtime.env.DATABASE_URL); const profile = await authenticate(request, db); if (!profile) { return Response.json({ error: "Unauthorized" }, { status: 401 }); } const [positionRows, notificationRows] = await Promise.all([ db .select({ side: positions.side, shares: positions.shares, avgPrice: positions.avgPrice, realizedPnl: positions.realizedPnl, marketSlug: markets.slug, eventSlug: events.slug, }) .from(positions) .innerJoin(markets, eq(positions.marketId, markets.id)) .innerJoin(events, eq(markets.eventId, events.id)) .where(eq(positions.profileId, profile.id)), db .select({ id: notifications.id, type: notifications.type, read: notifications.read, createdAt: notifications.createdAt, actorUsername: profiles.username, actorName: profiles.name, commentId: notifications.commentId, commentBody: comments.body, eventId: notifications.eventId, eventSlug: events.slug, eventTitle: events.title, }) .from(notifications) .innerJoin(profiles, eq(notifications.actorId, profiles.id)) .innerJoin(comments, eq(notifications.commentId, comments.id)) .innerJoin(events, eq(notifications.eventId, events.id)) .where(and(eq(notifications.profileId, profile.id), eq(notifications.read, false))) .orderBy(desc(notifications.createdAt)) .limit(20), ]); const active = positionRows.filter((r) => parseFloat(r.shares) > 0); const closed = positionRows.filter((r) => parseFloat(r.shares) === 0 && parseFloat(r.realizedPnl) !== 0); const unreadIds = notificationRows.map((n) => n.id); if (unreadIds.length > 0) { await db .update(notifications) .set({ read: true }) .where(and(eq(notifications.profileId, profile.id), eq(notifications.read, false))); } return Response.json({ username: profile.username, name: profile.name, bio: profile.bio, balance: profile.balance, positions: { active, closed }, notifications: notificationRows, }); };