import useSWR from 'swr' interface UploadTemplateDto { id: string name: string description: string | null status: string materialType: string materialKind?: string version: number fieldGroups: any displayConfig: any createdAt: string updatedAt: string fields: any[] } const fetcher = async (url: string) => { const res = await fetch(url) if (!res.ok) { const error: any = new Error('获取模板列表失败') error.status = res.status throw error } return res.json() } /** * 使用SWR缓存模板列表 * @param shouldFetch 是否应该获取数据(默认true) * @returns SWR返回对象 */ export function useTemplates(shouldFetch: boolean = true) { const { data, error, isLoading, mutate } = useSWR( shouldFetch ? '/api/admin/upload-templates' : null, fetcher, { // 缓存配置 revalidateOnFocus: false, // 窗口聚焦时不重新验证 revalidateOnReconnect: true, // 重新连接时重新验证 dedupingInterval: 5000, // 5秒内的重复请求会被去重 // 错误重试配置 errorRetryCount: 3, errorRetryInterval: 1000, } ) return { templates: data, isLoading, isError: error, mutate, // 用于手动刷新数据 } } /** * 使用SWR缓存单个模板详情 * @param templateId 模板ID * @param shouldFetch 是否应该获取数据(默认true) * @returns SWR返回对象 */ export function useTemplate(templateId: string | null, shouldFetch: boolean = true) { const { data, error, isLoading, mutate } = useSWR( shouldFetch && templateId ? `/api/admin/upload-templates/${templateId}` : null, fetcher, { revalidateOnFocus: false, revalidateOnReconnect: true, dedupingInterval: 5000, errorRetryCount: 3, errorRetryInterval: 1000, } ) return { template: data, isLoading, isError: error, mutate, } }