From 7fa62ae073629d8766fa19afb6aa64b9efe3d1e8 Mon Sep 17 00:00:00 2001 From: pyr0ball Date: Wed, 4 Mar 2026 12:17:46 -0800 Subject: [PATCH] feat: add useApiSSE helper for Server-Sent Events connections --- web/src/composables/useApi.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/web/src/composables/useApi.ts b/web/src/composables/useApi.ts index d677091..2965d8e 100644 --- a/web/src/composables/useApi.ts +++ b/web/src/composables/useApi.ts @@ -18,3 +18,33 @@ export async function useApiFetch( return { data: null, error: { kind: 'network', message: String(e) } } } } + +/** + * Open an SSE connection. Returns a cleanup function. + * onEvent receives each parsed JSON payload. + * onComplete is called when the server sends a {"type":"complete"} event. + * onError is called on connection error. + */ +export function useApiSSE( + url: string, + onEvent: (data: Record) => void, + onComplete?: () => void, + onError?: (e: Event) => void, +): () => void { + const es = new EventSource(url) + es.onmessage = (e) => { + try { + const data = JSON.parse(e.data) as Record + onEvent(data) + if (data.type === 'complete') { + es.close() + onComplete?.() + } + } catch { /* ignore malformed events */ } + } + es.onerror = (e) => { + onError?.(e) + es.close() + } + return () => es.close() +}