refactor(usage): consolidate query logic to eliminate DRY violations
Breaking Changes: - Removed useAutoUsageQuery hook (119 lines) - Unified all usage queries into single useUsageQuery hook Technical Improvements: - Eliminated duplicate state management (React Query + manual useState) - Fixed single source of truth principle violation - Replaced manual setInterval with React Query's built-in refetchInterval - Reduced UsageFooter complexity by 28% (54 → 39 lines) New Features: - useUsageQuery now accepts autoQueryInterval option - Automatic query interval control (0 = disabled, min 1 minute) - Built-in lastQueriedAt timestamp from dataUpdatedAt - Auto-query only enabled for currently active provider Architecture Benefits: - Single data source: manual and auto queries share same cache - No more state inconsistency between manual/auto query results - Leverages React Query's caching, deduplication, and background updates - Cleaner separation of concerns Code Changes: - src/lib/query/queries.ts: Enhanced useUsageQuery with auto-query support - src/components/UsageFooter.tsx: Simplified to use single query hook - src/hooks/useAutoUsageQuery.ts: Deleted (redundant) - All type checks passed
This commit is contained in:
@@ -83,17 +83,33 @@ export const useSettingsQuery = (): UseQueryResult<Settings> => {
|
||||
});
|
||||
};
|
||||
|
||||
export interface UseUsageQueryOptions {
|
||||
enabled?: boolean;
|
||||
autoQueryInterval?: number; // 自动查询间隔(分钟),0 表示禁用
|
||||
}
|
||||
|
||||
export const useUsageQuery = (
|
||||
providerId: string,
|
||||
appId: AppId,
|
||||
enabled: boolean = true,
|
||||
): UseQueryResult<UsageResult> => {
|
||||
return useQuery({
|
||||
options?: UseUsageQueryOptions,
|
||||
) => {
|
||||
const { enabled = true, autoQueryInterval = 0 } = options || {};
|
||||
|
||||
const query = useQuery<UsageResult>({
|
||||
queryKey: ["usage", providerId, appId],
|
||||
queryFn: async () => usageApi.query(providerId, appId),
|
||||
enabled: enabled && !!providerId,
|
||||
refetchInterval:
|
||||
autoQueryInterval > 0
|
||||
? Math.max(autoQueryInterval, 1) * 60 * 1000 // 最小1分钟
|
||||
: false,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
staleTime: 5 * 60 * 1000, // 5分钟
|
||||
});
|
||||
|
||||
return {
|
||||
...query,
|
||||
lastQueriedAt: query.dataUpdatedAt || null,
|
||||
};
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user