All files / features / dashboard dashboardApi.ts

76.47% Statements 13/17
92.59% Branches 25/27
88.88% Functions 8/9
76.47% Lines 13/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50      60x 56x     56x           15x         56x           15x         56x           15x           56x           15x   56x
import { useQuery } from '@tanstack/react-query'
import { apiClient } from '@/lib/axios'
import type { components } from '@/types/api'
 
type Run = components['schemas']['Run']
type ListRunsResponse = components['schemas']['ListRunsResponse']
 
async function fetchRuns(filters: Record<string, string | number>): Promise<ListRunsResponse> {
  const { data } = await apiClient.get<ListRunsResponse>('/runs', { params: filters })
  return data
}
 
export function useDashboardStats() {
  const running = useQuery({
    queryKey: ['runs', 'dashboard', 'running'],
    queryFn: () => fetchRuns({ phase: 'running', limit: 1 }),
  })
  const today = useQuery({
    queryKey: ['runs', 'dashboard', 'today'],
    queryFn: () => fetchRuns({ created_after: 'today', limit: 1 }),
  })
  const failed = useQuery({
    queryKey: ['runs', 'dashboard', 'failed'],
    queryFn: () => fetchRuns({ phase: 'failed', created_after: '30d', limit: 1 }),
  })
  const recent = useQuery({
    queryKey: ['runs', 'dashboard', 'recent'],
    queryFn: () => fetchRuns({ limit: 50 }),
  })
 
  return {
    stats: {
      running: running.data?.meta?.total_estimate ?? running.data?.meta?.returned ?? 0,
      today: today.data?.meta?.total_estimate ?? today.data?.meta?.returned ?? 0,
      failed: failed.data?.meta?.total_estimate ?? failed.data?.meta?.returned ?? 0,
      tokenInput: (recent.data?.data ?? []).reduce((sum, r) => sum + (r.token_input ?? 0), 0),
      tokenOutput: (recent.data?.data ?? []).reduce((sum, r) => sum + (r.token_output ?? 0), 0),
    },
    runs: (recent.data?.data ?? []) as Run[],
    isLoading: running.isLoading || today.isLoading || failed.isLoading || recent.isLoading,
    error: running.error ?? today.error ?? failed.error ?? recent.error,
    refetch: () => {
      running.refetch()
      today.refetch()
      failed.refetch()
      recent.refetch()
    },
  }
}