Skip to content

Commit

Permalink
Convert taskMonitor to Typescript + refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
davelopez committed Sep 20, 2023
1 parent bea9a81 commit 3aa4fab
Showing 1 changed file with 25 additions and 21 deletions.
Original file line number Diff line number Diff line change
@@ -1,57 +1,61 @@
import axios from "axios";
import { computed, readonly, ref } from "vue";

import { fetcher } from "@/schema";
import { errorMessageAsString } from "@/utils/simple-error";

const SUCCESS_STATE = "SUCCESS";
const FAILURE_STATE = "FAILURE";
const TASK_READY_STATES = [SUCCESS_STATE, FAILURE_STATE];
const DEFAULT_POLL_DELAY = 10000;

const getTaskStatus = fetcher.path("/api/tasks/{task_id}/state").method("get").create();

/**
* Composable for waiting on Galaxy background tasks.
*/
export function useTaskMonitor() {
let timeout = null;
let timeout: NodeJS.Timeout | null = null;
let pollDelay = DEFAULT_POLL_DELAY;

const isRunning = ref(false);
const status = ref(null);
const currentTaskId = ref(null);
const status = ref<string>();
const currentTaskId = ref<string>();
const requestHasFailed = ref(false);

const isCompleted = computed(() => status.value === SUCCESS_STATE);
const hasFailed = computed(() => status.value === FAILURE_STATE);
const queryStateUrl = computed(() => `/api/tasks/${currentTaskId.value}/state`);

function waitForTask(taskId, pollDelayInMs = DEFAULT_POLL_DELAY) {
async function waitForTask(taskId: string, pollDelayInMs = DEFAULT_POLL_DELAY) {
pollDelay = pollDelayInMs;
resetState();
currentTaskId.value = taskId;
isRunning.value = true;
fetchTaskStatus();
}

function fetchTaskStatus() {
axios.get(queryStateUrl.value).then(handleStatusResponse).catch(handleError);
return fetchTaskStatus(taskId);
}

function handleStatusResponse(response) {
status.value = response.data;
const isReady = TASK_READY_STATES.includes(status.value);
if (isReady) {
isRunning.value = false;
} else {
pollAfterDelay();
async function fetchTaskStatus(taskId: string) {
try {
const { data } = await getTaskStatus({ task_id: taskId });
status.value = data;
const isReady = TASK_READY_STATES.includes(status.value);
if (isReady) {
isRunning.value = false;
} else {
pollAfterDelay(taskId);
}
} catch (err) {
handleError(errorMessageAsString(err));
}
}

function pollAfterDelay(taskId) {
function pollAfterDelay(taskId: string) {
resetTimeout();
timeout = setTimeout(() => {
fetchTaskStatus(taskId);
}, pollDelay);
}

function handleError(err) {
function handleError(err: string) {
status.value = err;
requestHasFailed.value = true;
isRunning.value = false;
Expand All @@ -66,7 +70,7 @@ export function useTaskMonitor() {

function resetState() {
resetTimeout();
status.value = null;
status.value = undefined;
}

return {
Expand Down

0 comments on commit 3aa4fab

Please sign in to comment.