-
Notifications
You must be signed in to change notification settings - Fork 14
/
useRunWorkflow.ts
64 lines (52 loc) · 1.7 KB
/
useRunWorkflow.ts
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
import { useApi } from '@backstage/core-plugin-api';
import {
scaffolderApiRef,
useTemplateSecrets,
} from '@backstage/plugin-scaffolder-react';
import { JsonValue } from '@backstage/types';
import { useAsync } from '@react-hookz/web';
import { useEffect, useState } from 'react';
import { useTaskEventStream } from './useTaskEventStream';
type Props = {
templateRef: string;
onComplete?: () => void;
onError?: (e: Error) => void;
};
export type TaskStatus = 'idle' | 'pending' | 'error' | 'success';
export type RunWorkflow = ReturnType<typeof useRunWorkflow>;
export function useRunWorkflow({ templateRef, onComplete, onError }: Props) {
const scaffolderApi = useApi(scaffolderApiRef);
const [taskId, setTaskId] = useState<string>();
const { secrets } = useTemplateSecrets();
const taskStream = useTaskEventStream(taskId);
const [taskStatus, setTaskStatus] = useState<TaskStatus>('idle');
const [state, { execute }] = useAsync(async function runScaffolderWorkflow(
values: Record<string, JsonValue>,
) {
setTaskStatus('pending');
const { taskId: id } = await scaffolderApi.scaffold({
templateRef,
values,
secrets,
});
setTaskId(id);
});
useEffect(() => {
if (taskStream.error) {
// eslint-disable-next-line no-console
console.error(taskStream.error);
setTaskStatus('error');
onError?.(taskStream.error);
return;
}
if (taskStream.completed) {
setTaskStatus('success');
onComplete?.();
}
}, [onComplete, onError, taskStream.completed, taskStream.error]);
const reset = () => {
setTaskStatus('idle');
setTaskId(undefined);
};
return { state, execute, taskId, taskStream, taskStatus, reset };
}