feat: add useApiSSE helper for Server-Sent Events connections
This commit is contained in:
parent
7bd37ef982
commit
7fa62ae073
1 changed files with 30 additions and 0 deletions
|
|
@ -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()
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue