From 377d038dc268434b838efd6701f5efbaa5840843 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 3 Nov 2024 08:50:38 +0100 Subject: [PATCH] feat: add backgroundJob composable --- src/composables/backgroundJob.ts | 56 ++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/composables/backgroundJob.ts diff --git a/src/composables/backgroundJob.ts b/src/composables/backgroundJob.ts new file mode 100644 index 00000000..b15e2a96 --- /dev/null +++ b/src/composables/backgroundJob.ts @@ -0,0 +1,56 @@ +import { BackgroundTaskStatus } from '@/types'; +import { AxiosInstance } from 'axios'; + +const jobs = ref>({}); + +export function useBackgroundJob() { + function start(api: AxiosInstance, showAlert: any, jobId: string, jobType: string) { + async function getBackgroundJobStatus(jobId: string) { + try { + const { data } = await api.get(`/background/${jobId}`); + return Promise.resolve(data); + } catch (error) { + console.error(error); + return Promise.reject(error); + } + } + + const evaluating = ref(false); + const result = ref(null); + jobs.value[jobId] = { jobType, status: 'starting' }; + + const interval = window.setInterval(async () => { + try { + result.value = await getBackgroundJobStatus(jobId); + if (!result.value.running) { + clearJobFromList(); + } + jobs.value[jobId] = { ...jobs.value[jobId], status: result.value.status }; + console.log('got result', result.value); + } catch (error) { + console.error(error); + showAlert('Failed to get background job status', 'error'); + clearJobFromList(); + } + }, 500); + + function clearJobFromList() { + if (interval) { + clearInterval(interval); + } + evaluating.value = false; + } + + return { + evaluating, + result, + }; + } + + const runningJobs = computed(() => jobs.value); + + return { + runningJobs, + start, + }; +}