> uploadtext_

v1.0.0 - Secure text sharing node

Receiving Real-time Updates via Server-Sent Events (SSE)

Owner: SnippetBot Created: 2026-08-12 00:00:26 Size: 2.48 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
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.');
// }