MCPcopy Create free account
hub / github.com/astercloud/aster / useEventStream

Function useEventStream

studio/src/hooks/useEventStream.ts:31–205  ·  view source on GitHub ↗
(options: UseEventStreamOptions = {})

Source from the content-addressed store, hash-verified

29};
30
31export function useEventStream(options: UseEventStreamOptions = {}): UseEventStreamResult {
32 const opts = { ...DEFAULT_OPTIONS, ...options };
33
34 const [events, setEvents] = useState<StreamEvent[]>([]);
35 const [status, setStatus] = useState<ConnectionStatus>('disconnected');
36 const [stats, setStats] = useState<EventStreamStats | null>(null);
37 const [error, setError] = useState<string | null>(null);
38
39 const wsRef = useRef<WebSocket | null>(null);
40 const reconnectAttempts = useRef(0);
41 const reconnectTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
42 const filtersRef = useRef<StreamEventFilters>({});
43
44 // Build WebSocket URL
45 const getWsUrl = useCallback(() => {
46 const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
47 const host = window.location.host;
48 return `${protocol}//${host}/v1/dashboard/events/stream`;
49 }, []);
50
51 // Connect to WebSocket
52 const connect = useCallback(() => {
53 if (wsRef.current?.readyState === WebSocket.OPEN) {
54 return;
55 }
56
57 // Clean up existing connection
58 if (wsRef.current) {
59 wsRef.current.close();
60 wsRef.current = null;
61 }
62
63 setStatus('connecting');
64 setError(null);
65
66 try {
67 const ws = new WebSocket(getWsUrl());
68 wsRef.current = ws;
69
70 ws.onopen = () => {
71 setStatus('connected');
72 setError(null);
73 reconnectAttempts.current = 0;
74
75 // Always send subscription on connect (even with empty filters to subscribe to all)
76 ws.send(JSON.stringify({
77 action: 'subscribe',
78 filters: filtersRef.current,
79 }));
80 };
81
82 ws.onmessage = (event) => {
83 try {
84 const data = JSON.parse(event.data);
85
86 switch (data.type) {
87 case 'event':
88 // Extract payload as the actual event data

Callers 1

EventsFunction · 0.90

Calls 5

setStatusFunction · 0.85
connectFunction · 0.85
closeMethod · 0.45
sendMethod · 0.45
parseMethod · 0.45

Tested by

no test coverage detected