eletrotupi / tcc/ frontend/hooks/useInsights.queries.tsf74f10c623d080f34b937b43a9f16e47920c975b
1.5 KB | 52 lines Raw
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
  DAILY_SLEEP: "DAILY",
30
};
31

32
export const useInsight = (type: InsightType) => {
33
  const period = INSIGHT_PERIOD[type];
34
  const staleTime = INSIGHT_STALE_TIMES[period];
35

36
  return useQuery({
37
    queryKey: insightKeys.byType(type),
38
    queryFn: () =>
39
      apiClient
40
        .getInsights({ type, limit: 1 })
41
        .then((res) => res.insights[0] ?? null),
42
    staleTime,
43
  });
44
};
45

46
export const useInsights = (filters?: InsightFilters) => {
47
  return useQuery({
48
    queryKey: insightKeys.list(filters),
49
    queryFn: () => apiClient.getInsights(filters).then((res) => res.insights),
50
    staleTime: 1000 * 60 * 15,
51
  });
52
};