(
templateVersion: TemplateVersion | undefined,
options?: { onDone: () => Promise<unknown> },
)
| 2 | import { watchBuildLogsByTemplateVersionId } from "#/api/api"; |
| 3 | import type { ProvisionerJobLog, TemplateVersion } from "#/api/typesGenerated"; |
| 4 | export const useWatchVersionLogs = ( |
| 5 | templateVersion: TemplateVersion | undefined, |
| 6 | options?: { onDone: () => Promise<unknown> }, |
| 7 | ) => { |
| 8 | const [logs, setLogs] = useState<ProvisionerJobLog[]>(); |
| 9 | const templateVersionId = templateVersion?.id; |
| 10 | const [cachedVersionId, setCachedVersionId] = useState(templateVersionId); |
| 11 | if (cachedVersionId !== templateVersionId) { |
| 12 | setCachedVersionId(templateVersionId); |
| 13 | setLogs([]); |
| 14 | } |
| 15 | |
| 16 | const onDoneEvent = useEffectEvent(() => options?.onDone()); |
| 17 | const status = templateVersion?.job.status; |
| 18 | const canWatch = status === "running" || status === "pending"; |
| 19 | useEffect(() => { |
| 20 | if (!templateVersionId || !canWatch) { |
| 21 | return; |
| 22 | } |
| 23 | |
| 24 | const socket = watchBuildLogsByTemplateVersionId(templateVersionId, { |
| 25 | onError: (error) => console.error(error), |
| 26 | onDone: onDoneEvent, |
| 27 | onMessage: (newLog) => { |
| 28 | setLogs((current) => [...(current ?? []), newLog]); |
| 29 | }, |
| 30 | }); |
| 31 | |
| 32 | return () => socket.close(); |
| 33 | }, [canWatch, templateVersionId]); |
| 34 | |
| 35 | return logs; |
| 36 | }; |
no test coverage detected