import type { APIRoute } from 'astro'; import { db } from '@db/database.ts'; import { API_SECRET } from 'astro:env/server'; import { z } from 'astro:schema'; const postSchema = z.object({ user: z.string() }); export const POST: APIRoute = async ({ request }) => { if (API_SECRET && request.headers.get('authorization') !== `Basic ${API_SECRET}`) { return new Response(null, { status: 401 }); } let parsed; try { parsed = await postSchema.parseAsync(await request.json()); } catch (_) { return new Response(null, { status: 400 }); } const user = (await db.getUsersByUuid({ uuid: [parsed.user] }))[parsed.user]; if (user == null) { return new Response(null, { status: 404 }); } const team = await db.getTeamByUserUuid({ uuid: parsed.user }); if (team == null) { return new Response(null, { status: 404 }); } const death = await db.getDeathByUserId({ userId: user.id }); const strikes = await db.getStrikesByTeamId({ teamId: team.team.id }); const response = { team: { name: team.team.name, color: team.team.color }, dead: death != null, strikeWeight: strikes.map((strike) => strike.reason.weight).reduce((a, b) => a + b, 0), lastJoined: team.team.lastJoined ? new Date(team.team.lastJoined).getTime() : null }; return new Response(JSON.stringify(response)); }; const putSchema = z.object({ user: z.string(), lastJoined: z.number() }); export const PUT: APIRoute = async ({ request }) => { if (API_SECRET && request.headers.get('authorization') !== `Basic ${API_SECRET}`) { return new Response(null, { status: 401 }); } let parsed; try { parsed = await putSchema.parseAsync(await request.json()); } catch (_) { return new Response(null, { status: 400 }); } const team = await db.getTeamByUserUuid({ uuid: parsed.user }); if (team == null) { return new Response(null, { status: 404 }); } await db.editTeam({ id: team.team.id, lastJoined: new Date(parsed.lastJoined).toISOString() }); return new Response(null, { status: 200 }); };