1.0.0 • Published 7 months ago

@andreasnicolaou/reactive-event-source v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

reactive-event-source

GitHub package.json version GitHub Actions Workflow Status GitHub License

NPM Downloads

A lightweight reactive wrapper around EventSource using RxJS, providing automatic reconnection and buffering.

Features

  • Automatic reconnection with exponential backoff
  • Type-safe event handling
  • Buffered events (never miss the last message)
  • Clean RxJS API with no callback hell
  • Configurable retry strategies

Installation

You can install the package via npm:

npm install @andreasnicolaou/reactive-event-source

Usage

import { ReactiveEventSource } from '@andreasnicolaou/reactive-event-source';

const eventSource = new ReactiveEventSource('https://api.example.com/stream');

// Subscribe to standard events
eventSource.on('open').subscribe(() => console.log('Connected'));
eventSource.on('error').subscribe((err) => console.error('Error:', err));

eventSource.on('update').subscribe((event) => {
  console.log('New update:', event.data);
});

// Close when done
eventSource.close();

API

Constructor

SignatureDescription
new ReactiveEventSource(url: string \| URL, options?: Partial<EventSourceOptions>)Creates a new SSE connection manager

Options

PropertyTypeDefaultDescription
maxRetriesnumber3Maximum retry attempts on failure
initialDelaynumber1000Initial retry delay in ms
maxDelaynumber10000Maximum retry delay in ms
withCredentialsbooleanfalseSend cookies with requests

Methods

MethodReturnsDescription
.on(eventType: string = 'message')Observable<MessageEvent>Returns hot observable that:• Buffers last event• Auto-reconnects• Completes on close
.close()voidCloses connection and cleans up resources

Properties

PropertyTypeValuesDescription
.readyStatenumber0: CONNECTING1: OPEN2: CLOSEDCurrent connection state. Automatically updates during reconnections.
.withCredentialsbooleantrue/falseIndicates if credentials are sent with requests (set at construction)
.URLstring-Readonly resolved endpoint URL. Returns string even if constructed with URL object.

Observable Behavior

• Buffers last event (ReplaySubject)
• Automatic reconnection
• Completes when connection closes
• Shared between subscribers

Connection States

StateValueDescription
CONNECTING0Establishing connection
OPEN1Connection active
CLOSED2Connection terminated

Polyfill for Node.js / Legacy Environments

This library depends on the EventSource API, which is available in most modern browsers. If you're running in an environment where EventSource is not defined (such as Node.js), you can globally provide a compatible implementation:

// Only do this once, at the top level of your application
globalThis.EventSource = /* your EventSource-compatible implementation */;

Contributing

Contributions are welcome! If you encounter issues or have ideas to enhance the library, feel free to submit an issue or pull request.