| 1 | import { useQuery } from "@tanstack/react-query";
|
| 2 | import { apiClient, Insight, InsightType, InsightPeriod } from "@/lib/api";
|
| 3 |
|
| 4 | export const insightKeys = {
|
| 5 | all: () => ["insights"] as const,
|
| 6 | lists: () => [...insightKeys.all(), "list"] as const,
|
| 7 | list: (filters?: InsightFilters) =>
|
| 8 | [...insightKeys.lists(), filters] as const,
|
| 9 | byType: (type: InsightType) => [...insightKeys.all(), "type", type] as const,
|
| 10 | };
|
| 11 |
|
| 12 | interface InsightFilters {
|
| 13 | type?: InsightType;
|
| 14 | period?: InsightPeriod;
|
| 15 | limit?: number;
|
| 16 | }
|
| 17 |
|
| 18 | const INSIGHT_STALE_TIMES: Record<InsightPeriod, number> = {
|
| 19 | DAILY: 1000 * 60 * 30, // 30 min, regenerates during the day
|
| 20 | WEEKLY: 1000 * 60 * 60 * 4, // 4h only changes on cron or mutations
|
| 21 | MONTHLY: 1000 * 60 * 60 * 24, // 24h
|
| 22 | };
|
| 23 |
|
| 24 | const INSIGHT_PERIOD: Record<InsightType, InsightPeriod> = {
|
| 25 | DAILY_ENERGY: "DAILY",
|
| 26 | MOOD_TREND: "WEEKLY",
|
| 27 | ENERGY_SLEEP_CORRELATION: "WEEKLY",
|
| 28 | TRIGGER_PATTERN: "WEEKLY",
|
| 29 | };
|
| 30 |
|
| 31 | export const useInsight = (type: InsightType) => {
|
| 32 | const period = INSIGHT_PERIOD[type];
|
| 33 | const staleTime = INSIGHT_STALE_TIMES[period];
|
| 34 |
|
| 35 | return useQuery({
|
| 36 | queryKey: insightKeys.byType(type),
|
| 37 | queryFn: () =>
|
| 38 | apiClient
|
| 39 | .getInsights({ type, limit: 1 })
|
| 40 | .then((res) => res.insights[0] ?? null),
|
| 41 | staleTime,
|
| 42 | });
|
| 43 | };
|
| 44 |
|
| 45 | export const useInsights = (filters?: InsightFilters) => {
|
| 46 | return useQuery({
|
| 47 | queryKey: insightKeys.list(filters),
|
| 48 | queryFn: () => apiClient.getInsights(filters).then((res) => res.insights),
|
| 49 | staleTime: 1000 * 60 * 15,
|
| 50 | });
|
| 51 | };
|