40 lines
1.5 KiB
TypeScript
40 lines
1.5 KiB
TypeScript
import { getLabResults, getRoutines, getSkinSnapshots } from '$lib/api';
|
|
import type { Routine, SkinConditionSnapshot } from '$lib/types';
|
|
import type { PageServerLoad } from './$types';
|
|
|
|
export const load: PageServerLoad = async () => {
|
|
const [routines, snapshots, labResults] = await Promise.all([
|
|
getRoutines({ from_date: recentDate(14) }),
|
|
getSkinSnapshots({ from_date: recentDate(60) }),
|
|
getLabResults({ latest_only: true, limit: 8 })
|
|
]);
|
|
return {
|
|
recentRoutines: getFreshestRoutines(routines).slice(0, 10),
|
|
recentSnapshots: snapshots,
|
|
latestSnapshot: getFreshestSnapshot(snapshots),
|
|
recentLabResults: labResults.items
|
|
};
|
|
};
|
|
|
|
function recentDate(daysAgo: number): string {
|
|
const d = new Date();
|
|
d.setDate(d.getDate() - daysAgo);
|
|
return d.toISOString().slice(0, 10);
|
|
}
|
|
|
|
function getFreshestSnapshot(snapshots: SkinConditionSnapshot[]): SkinConditionSnapshot | null {
|
|
if (!snapshots.length) return null;
|
|
return snapshots.reduce((freshest, current) => {
|
|
if (current.snapshot_date > freshest.snapshot_date) return current;
|
|
if (current.snapshot_date < freshest.snapshot_date) return freshest;
|
|
return current.created_at > freshest.created_at ? current : freshest;
|
|
});
|
|
}
|
|
|
|
function getFreshestRoutines(routines: Routine[]): Routine[] {
|
|
return [...routines].sort((a, b) => {
|
|
if (a.routine_date !== b.routine_date) return b.routine_date.localeCompare(a.routine_date);
|
|
if (a.part_of_day !== b.part_of_day) return b.part_of_day.localeCompare(a.part_of_day);
|
|
return b.created_at.localeCompare(a.created_at);
|
|
});
|
|
}
|