import { useQuery } from "@tanstack/react-query"; import type { DashboardResponse, MetaResponse, MetricsBucket, TargetMetricsResponse } from "../../shared/api"; const queryKeys = { dashboard: () => ["dashboard", "24h", 30] as const, meta: () => ["meta"] as const, metrics: (targetId: string, from: string, to: string, bucket: "auto" | MetricsBucket) => ["metrics", targetId, from, to, bucket] as const, }; export async function fetchJson(url: string): Promise { const response = await fetch(url); if (!response.ok) throw new Error(`HTTP ${response.status}`); return response.json() as Promise; } export function useDashboard(refetchInterval: false | number) { return useQuery({ queryFn: () => fetchJson("/api/dashboard?window=24h&recentLimit=30"), queryKey: queryKeys.dashboard(), refetchInterval, refetchIntervalInBackground: false, }); } export function useMeta() { return useQuery({ queryFn: () => fetchJson("/api/meta"), queryKey: queryKeys.meta(), staleTime: Infinity, }); } export function useTargetMetrics(targetId: null | string, from: string, to: string, bucket: "auto" | MetricsBucket) { return useQuery({ enabled: targetId !== null && !!from && !!to, queryFn: () => { if (targetId === null) throw new Error("未选择目标"); return fetchJson( `/api/targets/${targetId}/metrics?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}&bucket=${bucket}`, ); }, queryKey: targetId !== null && from && to ? queryKeys.metrics(targetId, from, to, bucket) : ["metrics", "disabled"], }); }