SseConnectionsProvider
This file defines the SseConnectionsProvider
class, which manages all active Server-Sent Events (SSE) connections in the @sodacore/core
HTTP module. It provides methods to add, remove, retrieve, broadcast to, and manage multiple SSE connections, enabling efficient real-time communication with connected clients.
Features
- Connection Management: Add, remove, retrieve, and check for active SSE connections by ID.
- Broadcasting: Send messages or packets to all, some, or all except specified connections.
- Bulk Operations: Clear all connections and close them gracefully.
- Dependency Injection: Uses the
@Provide
decorator for integration with the Sodacore DI system.
Usage
import SseConnectionsProvider from './provider/sse-connections';
// Add a new connection
connectionsProvider.addConnection(id, sseContext);
// Broadcast a packet to all clients
connectionsProvider.broadcast({ data: { message: 'Hello, all!' } });
// Send a raw message to specific clients
connectionsProvider.broadcastRawFor(['id1', 'id2'], 'Ping');
// Remove a connection
connectionsProvider.removeConnection(id);
API
Connection Management
addConnection(id: string, connection: SseContext): void
Adds a new SSE connection by ID.removeConnection(id: string): void
Removes an SSE connection by ID.getConnection(id: string): SseContext | undefined
Retrieves a connection by ID.getConnections(): Map<string, SseContext>
Returns the map of all active connections.hasConnection(id: string): boolean
Checks if a connection exists by ID.getConnectionCount(): number
Returns the number of active connections.clearConnections(): void
Closes and removes all connections.
Broadcasting
broadcast(packet: ISsePacket): void
Sends a packet to all connections.broadcastRaw(data: string): void
Sends a raw string message to all connections.broadcastFor(id: string | string[], packet: ISsePacket): void
Sends a packet to specific connection(s) by ID.broadcastRawFor(id: string | string[], data: string): void
Sends a raw string message to specific connection(s) by ID.broadcastExcept(id: string | string[], packet: ISsePacket): void
Sends a packet to all connections except those specified by ID.broadcastRawExcept(id: string | string[], data: string): void
Sends a raw string message to all connections except those specified by ID.
How It Works
- Maintains a
Map
of connection IDs toSseContext
instances. - Provides methods to add, remove, and retrieve connections.
- Broadcast methods iterate over the map and send messages or packets as needed.
clearConnections
ensures all connections are closed before clearing the map.
Notes
- Designed for internal use by the Sodacore HTTP SSE system.
- Ensures efficient and flexible management of real-time SSE connections.
- All broadcast methods support both single and multiple connection IDs.