feat: add useApiSSE helper for Server-Sent Events connections

This commit is contained in:
pyr0ball 2026-03-04 12:17:46 -08:00
parent 7bd37ef982
commit 7fa62ae073

View file

@ -18,3 +18,33 @@ export async function useApiFetch<T>(
return { data: null, error: { kind: 'network', message: String(e) } } 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<string, unknown>) => 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<string, unknown>
onEvent(data)
if (data.type === 'complete') {
es.close()
onComplete?.()
}
} catch { /* ignore malformed events */ }
}
es.onerror = (e) => {
onError?.(e)
es.close()
}
return () => es.close()
}