All files / features / runs runsApi.ts

53.12% Statements 17/32
50% Branches 3/6
54.54% Functions 12/22
57.14% Lines 16/28

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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67        38x 34x     6x 6x             150x   38x       48x   6x 1x 66x       254x 254x               2x   1x                             2x 2x                  
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { apiClient } from '@/lib/axios'
import type { components } from '@/types/api'
import { toast } from 'sonner'
 
type Run = components['schemas']['Run']
type ListRunsResponse = components['schemas']['ListRunsResponse']
type CreateRunRequest = components['schemas']['CreateRunRequest']
 
interface RunsFilters {
  limit?: number
  offset?: number
  phase?: string
  project_id?: string
  pipeline_id?: string
  source_type?: string
  created_after?: string
  sort?: string
  order?: string
}
 
async function fetchRuns(filters: RunsFilters): Promise<ListRunsResponse> {
  const { data } = await apiClient.get<ListRunsResponse>('/runs', {
    params: filters,
  })
  return data
}
 
async function fetchRun(id: string): Promise<Run> {
  const { data } = await apiClient.get<Run>(`/runs/${id}`)
  return data
}
 
async function createRun(body: CreateRunRequest): Promise<Run> {
  const { data } = await apiClient.post<Run>('/runs', body)
  return data
}

export function useRuns(filters: RunsFilters = {}) {
  return useQuery({
    queryKey: ['runs', filters],
    queryFn: () => fetchRuns(filters),
  })
}
 
export function useRun(id: string) {
  return useQuery({
    queryKey: ['run', id],
    queryFn: () => fetchRun(id),
    enabled: !!id,
    refetchInterval: (query) =>
      (query.state.data as Run | undefined)?.phase === 'running' ? 5000 : false,
  })
}
 
export function useCreateRun() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: createRun,
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['runs'] })
      toast.success('Run triggered')
    },
    onError: () => toast.error('Failed to trigger run'),
  })
}