SseContext
This file defines the SseContext
class, which extends HttpContext
to provide Server-Sent Events (SSE) support in the @sodacore/core
HTTP module. It manages the SSE connection lifecycle, message sending, and integration with the SSE connections provider.
Features
- SSE Connection Management: Creates and manages a unique SSE connection for each client, registering with the
SseConnectionsProvider
. - Streaming Responses: Provides a method to generate a properly configured SSE
Response
with a readable stream. - Message Sending: Supports sending structured packets or raw messages to the client over the SSE stream.
- Automatic Keep-Alive: Sends periodic ping messages to keep the SSE connection alive.
- Graceful Cleanup: Handles connection aborts and ensures resources are cleaned up.
Usage
An instance of SseContext
is automatically provided to SSE controller methods:
typescript
async function handleSse(context: SseContext) {
const response = context.getSseResponse();
// ... use response in your HTTP handler
context.send({ data: { message: 'Hello, SSE!' } });
}
API
Constructor
typescript
constructor(request: Request, server: Server)
- request: The incoming HTTP request.
- server: The Bun server instance.
Methods
getSseResponse(headers?: Record<string, string>): Response
Creates and returns a Response
object with a readable stream for SSE.
- Registers the context with the SSE connections provider.
- Sets appropriate SSE headers and a unique cookie.
- Handles connection keep-alive and cleanup on abort.
send(packet: ISsePacket): void
Sends a structured SSE packet to the client.
- packet: An object containing optional
id
anddata
fields.
sendRaw(message: string): void
Sends a raw string message to the client over the SSE stream.
close(): void
Closes the SSE connection and removes it from the connections provider.
How It Works
Initialization:
- Generates a unique connection ID.
- Registers the connection with the
SseConnectionsProvider
.
SSE Response:
- Creates a readable stream and sets up the controller for sending messages.
- Sends initial ping and retry messages.
- Sets up a periodic ping to keep the connection alive.
- Handles cleanup on client disconnect.
Message Sending:
send
formats and sends JSON data as an SSE event.sendRaw
sends any string directly to the client.
Cleanup:
- On abort or manual close, cleans up the interval, closes the stream, and removes the connection.
Notes
- Designed to be used internally by the Sodacore HTTP SSE controller system.
- Integrates with the
SseConnectionsProvider
for managing multiple SSE connections. - Uses Bun's streaming and request APIs.