useWorkflowManagement.ts61 lines · main
| 1 | import { useEffect, useState } from 'react' |
| 2 | |
| 3 | import { useActionRunQuery } from '@/data/actions/action-detail-query' |
| 4 | import { useActionRunLogsQuery } from '@/data/actions/action-logs-query' |
| 5 | |
| 6 | interface UseWorkflowManagementProps { |
| 7 | workflowRunId?: string |
| 8 | projectRef?: string |
| 9 | onWorkflowComplete?: (status: 'SUCCESS' | 'FAILED') => void |
| 10 | } |
| 11 | |
| 12 | export const useWorkflowManagement = ({ |
| 13 | workflowRunId, |
| 14 | projectRef, |
| 15 | onWorkflowComplete, |
| 16 | }: UseWorkflowManagementProps) => { |
| 17 | const [hasRefetched, setHasRefetched] = useState(false) |
| 18 | |
| 19 | const { data: workflowRun } = useActionRunQuery( |
| 20 | { projectRef, runId: workflowRunId }, |
| 21 | { |
| 22 | refetchInterval: (query) => { |
| 23 | return query.state.error?.code === 404 ? false : 2000 |
| 24 | }, |
| 25 | refetchOnMount: 'always', |
| 26 | staleTime: 0, |
| 27 | } |
| 28 | ) |
| 29 | |
| 30 | const { data: workflowRunLogs } = useActionRunLogsQuery( |
| 31 | { projectRef, runId: workflowRunId }, |
| 32 | { |
| 33 | refetchInterval: (query) => { |
| 34 | return query.state.error?.code === 404 ? false : 2000 |
| 35 | }, |
| 36 | refetchOnMount: 'always', |
| 37 | staleTime: 0, |
| 38 | } |
| 39 | ) |
| 40 | |
| 41 | // Handle workflow completion |
| 42 | useEffect(() => { |
| 43 | if (!workflowRun || !workflowRunId) return |
| 44 | |
| 45 | // Only refetch once per workflow completion |
| 46 | if (!!workflowRun.status && workflowRun.status !== 'RUNNING' && !hasRefetched) { |
| 47 | setHasRefetched(true) |
| 48 | onWorkflowComplete?.(workflowRun.status) |
| 49 | } |
| 50 | }, [workflowRunId, hasRefetched, onWorkflowComplete, workflowRun]) |
| 51 | |
| 52 | // Reset refetch flag when workflow ID changes |
| 53 | useEffect(() => { |
| 54 | setHasRefetched(false) |
| 55 | }, [workflowRunId]) |
| 56 | |
| 57 | return { |
| 58 | run: workflowRun, |
| 59 | logs: workflowRunLogs, |
| 60 | } |
| 61 | } |