All files / src/composables useForkJob.ts

100% Statements 15/15
90% Branches 9/10
100% Functions 4/4
100% Lines 13/13

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                                                72x 72x 72x     16x 16x   14x 11x 11x 11x   3x 2x   1x     72x    
import { computed } from 'vue'
import { useEntitiesStore, type Entity } from '@/stores/entities'
import { usePollUntilComplete } from '@/composables/usePollUntilComplete'
import type { RenamedField } from '@/utils/renamedFields'
 
type ForkOptions = {
  name?: string | Record<string, string>
  visibility?: 'flow-members' | 'public'
  copyItems?: boolean
}
 
/**
 * Forks an entity through the async fork job: enqueues it, then polls until
 * the worker is done. `status`/`progress` update as it runs so the caller can
 * show a progress bar.
 *
 * `run` resolves with the forked entity, rejects when the job (or the request
 * that starts it) fails, and resolves with `null` when polling was abandoned
 * before the job settled (`stop()` or the owning component unmounting) — the
 * job keeps running server-side, there is just nothing left to report.
 * `renamedFields` lists the fields the fork renamed, their name being taken
 * by an earlier field of the source (UC-ENTITY-029.1).
 */
export function useForkJob() {
  const entitiesStore = useEntitiesStore()
  const poll = usePollUntilComplete<{ entity: Entity; renamedFields?: RenamedField[] }>()
  const renamedFields = computed(() => poll.result.value?.renamedFields ?? [])
 
  async function run(entityId: string, options: ForkOptions): Promise<Entity | null> {
    const { jobId } = await entitiesStore.forkEntity(entityId, options)
    await poll.start(() => entitiesStore.getForkJobStatus(jobId))
 
    if (poll.status.value === 'completed' && poll.result.value) {
      const { entity } = poll.result.value
      entitiesStore.entities.unshift(entity)
      return entity
    }
    if (poll.status.value === 'failed') {
      throw new Error(poll.error.value || 'Failed to fork entity')
    }
    return null
  }
 
  return { status: poll.status, progress: poll.progress, renamedFields, run, stop: poll.stop }
}