|
| 1 | +import { useEffect, useRef, useState } from 'react'; |
| 2 | +import type { EventSourceMessage, FetchEventSourceInit } from '@microsoft/fetch-event-source'; |
| 3 | +import { fetchEventSource } from '@microsoft/fetch-event-source'; |
| 4 | +import useRefFunction from './useRefFunction'; |
| 5 | +import useRefValue from './useRefValue'; |
| 6 | + |
| 7 | +// eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 8 | +export interface UseSSEProps<T = any> { |
| 9 | + /** The URL to connect to */ |
| 10 | + url: RequestInfo; |
| 11 | + /** Options for the connection. */ |
| 12 | + connectOptions?: Omit<FetchEventSourceInit, 'onmessage' | 'onerror' | 'onclose'>; |
| 13 | + /** Automatically connect to the SSE channel. Default is `false`. */ |
| 14 | + autoConnect?: boolean; |
| 15 | + /** Automatically close the connection when the component unmounts. Default is `true`. */ |
| 16 | + autoClose?: boolean; |
| 17 | + /** Function to parse the incoming message. If not provided, the default JSON parser will be used. */ |
| 18 | + parseMessage?: (original: EventSourceMessage) => T; |
| 19 | + /** Callback function to handle incoming messages. */ |
| 20 | + onMessage?: (messageData: T) => void; |
| 21 | + /** Callback function to handle errors. */ |
| 22 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 23 | + onError?: (error: any) => void; |
| 24 | + /** Callback function to handle connection closure. */ |
| 25 | + onClose?: () => void; |
| 26 | +} |
| 27 | + |
| 28 | +// eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 29 | +const useSSE = <T = any>(props: UseSSEProps<T>) => { |
| 30 | + const { url, autoConnect, connectOptions, onMessage, parseMessage, onError, onClose } = props; |
| 31 | + const autoConnectRef = useRefValue(autoConnect); |
| 32 | + const [isRequesting, setIsRequesting] = useState(false); |
| 33 | + const isRequestingRef = useRefValue(isRequesting); |
| 34 | + const [isConnected, setIsConnected] = useState<boolean>(false); |
| 35 | + const abortCtrlRef = useRef<AbortController | undefined>(undefined); |
| 36 | + |
| 37 | + const connect = useRefFunction(async (options?: FetchEventSourceInit & Partial<Pick<UseSSEProps, 'url'>>) => { |
| 38 | + const { |
| 39 | + url: connectUrl = url, |
| 40 | + headers = {}, |
| 41 | + onopen, |
| 42 | + // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 43 | + onmessage, |
| 44 | + // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 45 | + onclose, |
| 46 | + // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 47 | + onerror, |
| 48 | + ...restOptions |
| 49 | + } = { ...connectOptions, ...options }; |
| 50 | + abortCtrlRef.current = new AbortController(); |
| 51 | + try { |
| 52 | + setIsRequesting(true); |
| 53 | + setIsConnected(false); |
| 54 | + await fetchEventSource(connectUrl, { |
| 55 | + method: 'post', |
| 56 | + signal: abortCtrlRef.current.signal, |
| 57 | + openWhenHidden: true, |
| 58 | + onopen: async (response: Response) => { |
| 59 | + setIsConnected(true); |
| 60 | + onopen?.(response); |
| 61 | + }, |
| 62 | + onmessage(event) { |
| 63 | + if (!isRequestingRef.current) { |
| 64 | + setIsRequesting(false); |
| 65 | + } |
| 66 | + try { |
| 67 | + let parsed: T; |
| 68 | + if (parseMessage) { |
| 69 | + parsed = parseMessage(event); |
| 70 | + } else { |
| 71 | + parsed = event.data ? JSON.parse(event.data) : undefined; |
| 72 | + } |
| 73 | + if (parsed != null) { |
| 74 | + onMessage?.(parsed); |
| 75 | + } |
| 76 | + } catch (error) { |
| 77 | + console.error('Error parsing message data:', error); |
| 78 | + console.log('The underlying event:', event); |
| 79 | + } |
| 80 | + }, |
| 81 | + onerror(error) { |
| 82 | + setIsRequesting(false); |
| 83 | + onError?.(error); |
| 84 | + }, |
| 85 | + onclose() { |
| 86 | + setIsRequesting(false); |
| 87 | + onClose?.(); |
| 88 | + }, |
| 89 | + headers: { |
| 90 | + 'Content-Type': 'application/json', |
| 91 | + ...headers, |
| 92 | + }, |
| 93 | + ...restOptions, |
| 94 | + }); |
| 95 | + } finally { |
| 96 | + setIsRequesting(false); |
| 97 | + } |
| 98 | + }); |
| 99 | + |
| 100 | + const close = useRefFunction(() => { |
| 101 | + setIsConnected(false); |
| 102 | + if (isConnected && abortCtrlRef.current) { |
| 103 | + abortCtrlRef.current.abort(); |
| 104 | + } |
| 105 | + }); |
| 106 | + |
| 107 | + useEffect(() => { |
| 108 | + if (autoConnectRef.current) { |
| 109 | + connect(); |
| 110 | + } |
| 111 | + return close; |
| 112 | + }, []); |
| 113 | + |
| 114 | + // 清理函数 |
| 115 | + return { |
| 116 | + connect, |
| 117 | + close, |
| 118 | + isRequesting, |
| 119 | + isConnected, |
| 120 | + }; |
| 121 | +}; |
| 122 | + |
| 123 | +export default useSSE; |
0 commit comments