Files
bibdle/src/routes/api/daily-verse/+server.ts
T

38 lines
1.3 KiB
TypeScript

import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getVerseForDate } from '$lib/server/daily-verse';
import { getBookById } from '$lib/server/bible';
import { recordEvent } from '$lib/server/stats/events';
export const POST: RequestHandler = async ({ request, locals }) => {
const body = await request.json();
const { date, anonymousId } = body;
if (!date || !/^\d{4}-\d{2}-\d{2}$/.test(date)) {
return json({ error: 'A valid date (YYYY-MM-DD) is required' }, { status: 400 });
}
const dateStr = date;
const dailyVerse = await getVerseForDate(dateStr);
const correctBook = getBookById(dailyVerse.bookId) ?? null;
// Instrumentation B: a player "started" the puzzle for this date. The unique
// partial index dedupes reloads, so this is safe to call on every load.
// Never let analytics failures affect the response.
// Prefer the signed-in user's ID so the started→finished funnel matches
// completions (which are keyed to the user ID for logged-in players).
const playerId =
locals.user?.id ??
(typeof anonymousId === 'string' && anonymousId.length > 0 ? anonymousId : null);
if (playerId) {
void recordEvent({ name: 'verse_served', anonymousId: playerId, date: dateStr });
}
return json({
dailyVerse,
correctBookId: dailyVerse.bookId,
correctBook,
});
};