| import { useCallback, useState } from "react"; | |
| import { waitForServerReady } from "../utils/healthCheck"; | |
| interface HealthCheckProgress { | |
| attempt: number; | |
| maxAttempts: number; | |
| } | |
| interface UseHealthCheckOptions { | |
| maxAttempts?: number; | |
| intervalMs?: number; | |
| onSuccess?: () => void; | |
| onError?: (error: Error) => void; | |
| logPrefix?: string; | |
| } | |
| interface UseHealthCheckReturn { | |
| healthCheckProgress: HealthCheckProgress | null; | |
| isHealthChecking: boolean; | |
| startHealthCheck: (healthUrl: string, options?: UseHealthCheckOptions) => Promise<void>; | |
| resetHealthCheck: () => void; | |
| } | |
| export const useHealthCheck = (): UseHealthCheckReturn => { | |
| const [healthCheckProgress, setHealthCheckProgress] = useState<HealthCheckProgress | null>(null); | |
| const [isHealthChecking, setIsHealthChecking] = useState<boolean>(false); | |
| const startHealthCheck = useCallback(async ( | |
| healthUrl: string, | |
| options: UseHealthCheckOptions = {} | |
| ) => { | |
| const { | |
| maxAttempts = 60, | |
| intervalMs = 1000, | |
| onSuccess, | |
| onError, | |
| logPrefix = "Health check" | |
| } = options; | |
| setIsHealthChecking(true); | |
| setHealthCheckProgress({ attempt: 0, maxAttempts }); | |
| try { | |
| await waitForServerReady(healthUrl, maxAttempts, intervalMs, (attempt, maxAttempts) => { | |
| console.log(`${logPrefix} progress: ${attempt}/${maxAttempts}`); | |
| setHealthCheckProgress({ attempt, maxAttempts }); | |
| }); | |
| console.log(`${logPrefix} completed successfully!`); | |
| if (onSuccess) { | |
| onSuccess(); | |
| } | |
| } catch (error) { | |
| console.error(`${logPrefix} failed:`, error); | |
| if (onError) { | |
| onError(error as Error); | |
| } | |
| } finally { | |
| setIsHealthChecking(false); | |
| setHealthCheckProgress(null); | |
| } | |
| }, []); | |
| const resetHealthCheck = useCallback(() => { | |
| setHealthCheckProgress(null); | |
| setIsHealthChecking(false); | |
| }, []); | |
| return { | |
| healthCheckProgress, | |
| isHealthChecking, | |
| startHealthCheck, | |
| resetHealthCheck, | |
| }; | |
| }; | |