feat(frontend): useSessionStream (EventSource -> store)
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
import { renderHook } from "@testing-library/react";
|
||||
import { act } from "react";
|
||||
import { FakeEventSource } from "../test/fakeEventSource";
|
||||
import { useSessionStream } from "./useSessionStream";
|
||||
import { useSessionStore } from "../store/sessionStore";
|
||||
|
||||
beforeEach(() => {
|
||||
FakeEventSource.instances = [];
|
||||
(globalThis as any).EventSource = FakeEventSource;
|
||||
useSessionStore.getState().resetSession();
|
||||
});
|
||||
|
||||
test("opens an EventSource for the session and feeds events to the store", () => {
|
||||
renderHook(() => useSessionStream("s1"));
|
||||
const es = FakeEventSource.instances[0];
|
||||
expect(es.url).toContain("/sessions/s1/events");
|
||||
act(() =>
|
||||
es.emit({ type: "ui_request", ui_request: { id: "u1", widget: "select" } })
|
||||
);
|
||||
expect(useSessionStore.getState().pendingWidget?.id).toBe("u1");
|
||||
});
|
||||
|
||||
test("closes the stream on unmount", () => {
|
||||
const { unmount } = renderHook(() => useSessionStream("s1"));
|
||||
const es = FakeEventSource.instances[0];
|
||||
unmount();
|
||||
expect(es.closed).toBe(true);
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { BASE } from "../api/client";
|
||||
import { useSessionStore } from "../store/sessionStore";
|
||||
import type { StreamEvent } from "../api/types";
|
||||
|
||||
export function useSessionStream(sessionId: string | null) {
|
||||
const [connected, setConnected] = useState(false);
|
||||
const applyEvent = useSessionStore((s) => s.applyEvent);
|
||||
|
||||
useEffect(() => {
|
||||
if (!sessionId) return;
|
||||
|
||||
const es = new EventSource(`${BASE}/sessions/${sessionId}/events`);
|
||||
es.onopen = () => setConnected(true);
|
||||
es.onerror = () => setConnected(false);
|
||||
es.onmessage = (ev) => {
|
||||
try {
|
||||
applyEvent(JSON.parse(ev.data) as StreamEvent);
|
||||
} catch {
|
||||
/* ignore malformed */
|
||||
}
|
||||
};
|
||||
|
||||
return () => {
|
||||
es.close();
|
||||
setConnected(false);
|
||||
};
|
||||
}, [sessionId, applyEvent]);
|
||||
|
||||
return { connected };
|
||||
}
|
||||
Reference in New Issue
Block a user