Support authenticated users in stats and page loading

This commit is contained in:
George Powell
2026-02-05 17:46:53 -05:00
parent 86f81cf9dd
commit 96024d5048
3 changed files with 35 additions and 11 deletions

View File

@@ -3,13 +3,19 @@ import { dailyCompletions, type DailyCompletion } from '$lib/server/db/schema';
import { eq, desc } from 'drizzle-orm';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ url }) => {
export const load: PageServerLoad = async ({ url, locals }) => {
const userId = url.searchParams.get('userId');
const anonymousId = url.searchParams.get('anonymousId');
if (!anonymousId) {
// Prioritize userId (authenticated user) over anonymousId
const targetId = userId || anonymousId;
if (!targetId) {
return {
stats: null,
error: 'No anonymous ID provided'
error: 'No user ID provided',
user: locals.user,
session: locals.session
};
}
@@ -18,7 +24,7 @@ export const load: PageServerLoad = async ({ url }) => {
const completions = await db
.select()
.from(dailyCompletions)
.where(eq(dailyCompletions.anonymousId, anonymousId))
.where(eq(dailyCompletions.anonymousId, targetId))
.orderBy(desc(dailyCompletions.date));
if (completions.length === 0) {
@@ -39,7 +45,9 @@ export const load: PageServerLoad = async ({ url }) => {
currentStreak: 0,
bestStreak: 0,
recentCompletions: []
}
},
user: locals.user,
session: locals.session
};
}
@@ -126,14 +134,18 @@ export const load: PageServerLoad = async ({ url }) => {
currentStreak,
bestStreak,
recentCompletions
}
},
user: locals.user,
session: locals.session
};
} catch (error) {
console.error('Error fetching user stats:', error);
return {
stats: null,
error: 'Failed to fetch stats'
error: 'Failed to fetch stats',
user: locals.user,
session: locals.session
};
}
};