mirror of
https://github.com/pupperpowell/bibdle.git
synced 2026-04-06 01:43:32 -04:00
Added streak counter
This commit is contained in:
36
src/routes/api/streak/+server.ts
Normal file
36
src/routes/api/streak/+server.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
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 });
|
||||
};
|
||||
Reference in New Issue
Block a user