WsContext
This file defines the WsContext
class, which extends HttpContext
to provide contextual information and utility methods for WebSocket connections in the @sodacore/core
WebSocket module. It wraps a Bun ServerWebSocket
and exposes methods for sending messages, managing connection data, and accessing connection metadata.
Features
- Extends HttpContext: Inherits all HTTP context features, allowing access to request, server, cookies, headers, etc.
- WebSocket Integration: Wraps a Bun
ServerWebSocket
and provides methods for sending structured or raw messages. - Connection Metadata: Provides methods to get the connection ID and remote address.
- Custom Data Storage: Allows storing and retrieving arbitrary data associated with the WebSocket connection.
- Graceful Close: Supports closing the connection with an optional reason and code, and logs the closure.
Usage
An instance of WsContext
is automatically provided to WebSocket controller methods:
async function onMessage(context: WsContext) {
const id = context.getId();
const remote = context.getRemoteAddress();
context.send('update', { message: 'Hello, client!' });
}
API
Constructor
constructor(socket: ServerWebSocket<IServerWsContext>)
- socket: The Bun
ServerWebSocket
instance for this connection.
Methods
setData(data: Record<string, any>): void
Sets custom data for the connection.getData<T = Record<string, any>>(): T
Retrieves the stored custom data.getId(): string
Returns the WebSocket connection ID (from thesec-websocket-key
header).getRemoteAddress(): string
Returns the remote address of the connected client.send(command: string, context: Record<string, any> = {}): void
Sends a structured JSON message with a command and context.sendRaw(data: string): void
Sends a raw string message to the client.close(reason?: string, code?: number): void
Closes the WebSocket connection, optionally logging the reason and code.
How It Works
- On construction, extracts the HTTP request and server from the underlying
HttpContext
attached to the socket. - Provides utility methods for sending messages and managing connection state.
- Uses dependency injection to access the logger for connection events.
Notes
- Designed for internal use by the Sodacore WebSocket controller system.
- Allows seamless integration of HTTP and WebSocket context for unified controller logic.