mirror of
https://github.com/pupperpowell/bibdle.git
synced 2026-04-05 17:33:31 -04:00
37 lines
1.1 KiB
TypeScript
37 lines
1.1 KiB
TypeScript
import { json, error } from '@sveltejs/kit';
|
|
import type { RequestHandler } from './$types';
|
|
import { db } from '$lib/server/db';
|
|
import { dailyCompletions } from '$lib/server/db/schema';
|
|
import { eq, desc } from 'drizzle-orm';
|
|
|
|
export const GET: RequestHandler = async ({ url }) => {
|
|
const anonymousId = url.searchParams.get('anonymousId');
|
|
const localDate = url.searchParams.get('localDate');
|
|
|
|
if (!anonymousId || !localDate) {
|
|
error(400, 'Missing anonymousId or localDate');
|
|
}
|
|
|
|
// Fetch all completion dates for this user, newest first
|
|
const rows = await db
|
|
.select({ date: dailyCompletions.date })
|
|
.from(dailyCompletions)
|
|
.where(eq(dailyCompletions.anonymousId, anonymousId))
|
|
.orderBy(desc(dailyCompletions.date));
|
|
|
|
const completedDates = new Set(rows.map((r) => r.date));
|
|
|
|
// Walk backwards from localDate, counting consecutive completed days
|
|
let streak = 0;
|
|
let cursor = new Date(`${localDate}T00:00:00`);
|
|
|
|
while (true) {
|
|
const dateStr = cursor.toLocaleDateString('en-CA'); // YYYY-MM-DD
|
|
if (!completedDates.has(dateStr)) break;
|
|
streak++;
|
|
cursor.setDate(cursor.getDate() - 1);
|
|
}
|
|
|
|
return json({ streak });
|
|
};
|