All files / src/composables usePollUntilComplete.ts

100% Statements 38/38
83.33% Branches 15/18
100% Functions 6/6
100% Lines 37/37

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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90                                                                371x 371x 371x 371x   371x 371x     221x 35x 35x   221x 35x 35x 35x         36x 36x 36x 36x 36x     41x 41x 40x 40x 41x 18x 18x 22x 10x 10x     1x 1x 1x       36x 36x 36x 36x       371x   371x    
import { onUnmounted, ref } from 'vue'
 
export type JobPollStatus = 'idle' | 'pending' | 'processing' | 'completed' | 'failed'
 
export interface JobProgress {
  done: number
  total: number
}
 
// Shape shared by every job-status endpoint this composable is built for
// (export/import job polling) — `result` is only ever populated once
// `status` is 'completed'.
export interface JobStatusResponse<TResult> {
  status: 'pending' | 'processing' | 'completed' | 'failed'
  progress?: JobProgress | null
  result?: TResult
  error?: string
}
 
/**
 * Polls a job-status endpoint on a fixed interval until the job reaches a
 * terminal state ('completed' or 'failed'), exposing status/progress/result
 * reactively as they update on each tick.
 *
 * There is no persisted job tracking here by design: a poll only needs to
 * survive for as long as whatever UI started it stays open. Calling `stop()`
 * (or unmounting the owning component) simply abandons the poll — any
 * pending `start()` promise resolves so the caller's `await` doesn't hang,
 * but `status` is left in whatever non-terminal state it was last in, which
 * callers should treat as "no outcome to report", not as an error.
 */
export function usePollUntilComplete<TResult>(intervalMs = 2000) {
  const status = ref<JobPollStatus>('idle')
  const progress = ref<JobProgress | null>(null)
  const result = ref<TResult | null>(null)
  const error = ref<string | null>(null)
 
  let timer: ReturnType<typeof setInterval> | null = null
  let resolveCurrent: (() => void) | null = null
 
  function stop() {
    if (timer !== null) {
      clearInterval(timer)
      timer = null
    }
    if (resolveCurrent) {
      const resolve = resolveCurrent
      resolveCurrent = null
      resolve()
    }
  }
 
  function start(fetchStatus: () => Promise<JobStatusResponse<TResult>>): Promise<void> {
    stop()
    status.value = 'pending'
    progress.value = null
    result.value = null
    error.value = null
 
    async function tick() {
      try {
        const data = await fetchStatus()
        status.value = data.status
        progress.value = data.progress ?? null
        if (data.status === 'completed') {
          result.value = data.result ?? null
          stop()
        } else if (data.status === 'failed') {
          error.value = data.error ?? null
          stop()
        }
      } catch (err: any) {
        error.value = err.response?.data?.error || err.message || 'Failed to check job status'
        status.value = 'failed'
        stop()
      }
    }
 
    return new Promise((resolve) => {
      resolveCurrent = resolve
      void tick()
      timer = setInterval(() => void tick(), intervalMs)
    })
  }
 
  onUnmounted(stop)
 
  return { status, progress, result, error, start, stop }
}