Kind: Function
Source: src/helper/websocket/index.ts
Part of: Helper
Create a WebSocket adapter/helper
defineWebSocketHelper creates the WebSocket adapter used by the helper layer. It centralizes socket connection, message handling, and lifecycle operations behind a shared interface.
Signature
tsfunction defineWebSocketHelper(handler: WebSocketHelperDefineHandler<T, U>): UpgradeWebSocket<T, U>
Parameters
| Name | Type |
|---|---|
handler | WebSocketHelperDefineHandler<T, U> |
Returns: UpgradeWebSocket<T, U>
Diagram
mermaidgraph LR App[Application code] --> Helper[defineWebSocketHelper] Helper --> Socket[WebSocket] Socket --> Server[WebSocket server] Server --> Socket Socket --> Helper Helper --> App
Usage
tsimport { defineWebSocketHelper } from './helper/websocket'
const websocket = defineWebSocketHelper({
url: 'wss://example.com/events',
})
websocket.connect()
websocket.onMessage((message) => {
console.log('Received message:', message)
})
websocket.send({
type: 'subscribe',
channel: 'events',
})
window.addEventListener('beforeunload', () => {
websocket.close()
})
AI Coding Instructions
- Keep WebSocket-specific behavior inside the helper rather than spreading socket handling across callers.
- Close the socket during application teardown to avoid leaving active connections.
- Handle connection failures and unexpected close events through the helper’s lifecycle callbacks.
- Keep message payload formats aligned with the server protocol before calling
send.
Used by
3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.
Imported by (3)
BunServerWebSocket—src/adapter/bun/websocket.ts:8upgradeWebSocket—src/adapter/cloudflare-workers/websocket.ts:5upgradeWebSocket—src/adapter/deno/websocket.ts:4
Was this page helpful?