"use client"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import type { ContentItem } from "@muse/shared"; import { API_BASE_URL } from "@/lib/api"; async function fetchDetail( platform: string, id: string ): Promise { const res = await fetch( `${API_BASE_URL}/api/tikhub/${platform}/detail?id=${encodeURIComponent(id)}` ); if (!res.ok) { const data = await res.json().catch(() => ({})); throw new Error(data.error || `请求失败: ${res.status}`); } const data = await res.json(); return data.data; } /** * Look up an item from TanStack Query's trending list cache. * Checks both platform-specific and "all" caches. */ function findCachedItem( queryClient: ReturnType, platform: string, id: string ): ContentItem | undefined { const keys = [["content", platform], ["content", "all"]]; for (const key of keys) { const items = queryClient.getQueryData(key); if (items) { const found = items.find( (item) => item.id === id && item.platform === platform ); if (found) return found; } } return undefined; } export function useDetailQuery(platform: string, id: string) { const queryClient = useQueryClient(); const cached = findCachedItem(queryClient, platform, id); return useQuery({ queryKey: ["detail", platform, id], queryFn: () => fetchDetail(platform, id), // Skip API call if item already in trending cache enabled: !!platform && !!id && !cached, initialData: cached, staleTime: 5 * 60 * 1000, retry: 1, }); }