interface IWebSocketService
Since 0.2.0

Service contract for the WebSocket hub — registered by the WebSocketPlugin under CAPABILITIES.WEBSOCKET.

Examples

Example 1

import { CAPABILITIES } from '@setu-ts/common';

const ws = ctx.services.get<IWebSocketService>(CAPABILITIES.WEBSOCKET);

ws.route('/ws/chat', {
  onOpen: (conn, { query }) => {
    conn.data.set('room', query.room ?? 'lobby');
    ws.room(query.room ?? 'lobby').add(conn);
  },
  onMessage: (conn, data) => {
    const room = conn.data.get('room');
    if (typeof room === 'string') {
      ws.room(room).broadcast(data, { except: conn });
    }
  },
});

Properties

readonly
available: boolean

Whether the underlying HTTP adapter can perform WebSocket upgrades.

readonly
connectionCount: number

Current number of open connections across all routes.

readonly
roomCount: number

Current number of live rooms.

Methods

route(
path: string,
): void

Registers a WebSocket route. Paths match exactly; the query string is ignored for matching and exposed to onOpen instead.

room(name: string): WebSocketRoom

Returns the named room, creating it on first use.

Creating is the point: the first call for a name registers a room. Use IWebSocketService.peek to read a caller-supplied name without registering anything.

Since 0.4.0
peek(name: string): WebSocketRoom | undefined

Returns the named room if one already exists, without creating it.

The non-allocating counterpart to IWebSocketService.room. A presence or dashboard endpoint that reports size for a name taken from a request must use this: room(name) registers one room per distinct name polled, and a room nobody has joined is reclaimed only when some other connection disconnects — so an idle application never reclaims them.

Since 0.3.0
optional
routeUpgrade(
request: Request,
principal?: IPrincipal
): Promise<WebSocketUpgradeDecision | null>

Consults the internal upgrade router for an inbound request. Used by the kernel terminal handler to decide whether to upgrade after the middleware pipeline runs.

Usage

import { type IWebSocketService } from "common/src/index.ts";