All files / features / runs runsApi.ts

68.75% Statements 11/16
66.66% Branches 2/3
72.72% Functions 8/11
68.75% Lines 11/16

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        18x 17x     3x 3x             78x   18x       22x   3x   32x       124x 124x                                                                      
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'),
  })
}