function connectToSSE(url, eventHandlers = {}) { if (typeof EventSource === 'undefined') { console.error('EventSource is not supported by this browser.'); return null; } const eventSource = new EventSource(url); eventSource.onopen = (event) => { console.log('SSE connection opened.'); if (eventHandlers.onOpen) eventHandlers.onOpen(event); }; eventSource.onerror = (error) => { console.error('SSE Error:', error); if (eventHandlers.onError) eventHandlers.onError(error); // Reconnect logic can be implemented here if needed // For example, if error.readyState === EventSource.CLOSED, try to reconnect after a delay. }; // Default message handler for 'message' event eventSource.onmessage = (event) => { console.log('Received generic message:', event.data); try { const data = JSON.parse(event.data); if (eventHandlers.onMessage) eventHandlers.onMessage(data, event); } catch (e) { if (eventHandlers.onMessage) eventHandlers.onMessage(event.data, event); // Pass raw if not JSON } }; // Handle custom named events for (const eventName in eventHandlers) { if (eventName !== 'onOpen' && eventName !== 'onError' && eventName !== 'onMessage') { eventSource.addEventListener(eventName, (event) => { console.log(`Received custom event '${eventName}':`, event.data); try { const data = JSON.parse(event.data); eventHandlers[eventName](data, event); } catch (e) { eventHandlers[eventName](event.data, event); // Pass raw if not JSON } }); } } return eventSource; // Return the EventSource instance for closing the connection } // Usage example: // const sseConnection = connectToSSE('https://api.example.com/realtime-updates', { // onOpen: () => console.log('Connected to real-time feed!'), // onError: (error) => console.error('SSE Error:', error), // onMessage: (data) => { // console.log('New generic data event:', data); // // Update UI with data // }, // 'new-notification': (notification) => { // console.log('Received new notification:', notification); // // Display notification to user // }, // 'user-status-update': (status) => { // console.log('User status changed:', status); // // Update user online status in UI // } // }); // To close the connection when no longer needed (e.g., component unmounts): // if (sseConnection) { // // sseConnection.close(); // // console.log('SSE connection closed.'); // }