|
- import { parseJsonText } from '@/utils';
- import { useCallback, useRef } from 'react';
-
- export const useSSE = (onMessage: (data: any) => void) => {
- const evtSourceRef = useRef<EventSource | null>(null);
-
- const setupSSE = useCallback(
- (name: string, namespace: string) => {
- const { origin } = location;
- const params = encodeURIComponent(`metadata.namespace=${namespace},metadata.name=${name}`);
- const evtSource = new EventSource(
- `${origin}/api/v1/realtimeStatus?listOptions.fieldSelector=${params}`,
- { withCredentials: false },
- );
- evtSource.onmessage = (event) => {
- const data = event?.data;
- if (!data) {
- return;
- }
- const dataJson = parseJsonText(data);
- if (dataJson) {
- const nodes = dataJson?.result?.object?.status?.nodes;
- if (nodes) {
- onMessage(nodes);
- }
- }
- };
-
- evtSource.onerror = (error) => {
- console.error('SSE error: ', error);
- };
-
- evtSourceRef.current = evtSource;
- },
- [onMessage],
- );
-
- const closeSSE = useCallback(() => {
- if (evtSourceRef.current) {
- evtSourceRef.current.close();
- evtSourceRef.current = null;
- }
- }, []);
-
- return [setupSSE, closeSSE];
- };
|