Skip to content

@forinda/kickjs-ws

WebSocket support for KickJS applications via Socket.IO, using the same decorator-driven approach as HTTP controllers.

Installation

bash
pnpm add @forinda/kickjs-ws socket.io

Exports

Decorators

DecoratorDescription
@WsController(namespace)Mark a class as a WebSocket controller bound to a namespace
@OnConnect()Handle new socket connections
@OnDisconnect()Handle socket disconnections
@OnMessage(event)Handle a named message event
@OnError()Handle socket errors

Adapter

ExportDescription
WsAdapterAppAdapter that mounts Socket.IO on the HTTP server

Context

ExportDescription
WsContextContext object passed to all WebSocket handler methods

Types

ExportDescription
WsControllerMetaMetadata stored by @WsController
WsHandlerMetaMetadata stored by @OnMessage and other handler decorators
WsAdapterOptionsConfiguration options for WsAdapter

WsAdapter Options

ts
interface WsAdapterOptions {
  /** Socket.IO server options (cors, transports, etc.) */
  serverOptions?: Partial<ServerOptions>
  /** Heartbeat interval in ms (default: 30000) */
  heartbeatInterval?: number
  /** Heartbeat timeout in ms (default: 5000) */
  heartbeatTimeout?: number
}

WsContext

Every handler method receives a WsContext with:

PropertyTypeDescription
socketSocketThe raw Socket.IO socket
dataanyThe message payload
serverServerThe Socket.IO server instance
nspNamespaceThe namespace this socket belongs to
roomsSet<string>Rooms the socket has joined

Methods

MethodDescription
ctx.emit(event, data)Emit to the current socket
ctx.broadcast(event, data)Emit to all others in the namespace
ctx.toRoom(room, event, data)Emit to all sockets in a room
ctx.join(room)Join a room
ctx.leave(room)Leave a room

Usage

See the WebSocket guide for full examples.

ts
import { WsController, OnConnect, OnMessage, OnDisconnect } from '@forinda/kickjs-ws'
import type { WsContext } from '@forinda/kickjs-ws'

@WsController('/chat')
export class ChatController {
  @OnConnect()
  onConnect(ctx: WsContext) {
    console.log(`Connected: ${ctx.socket.id}`)
  }

  @OnMessage('send')
  onSend(ctx: WsContext) {
    ctx.broadcast('message', ctx.data)
  }

  @OnDisconnect()
  onDisconnect(ctx: WsContext) {
    console.log(`Disconnected: ${ctx.socket.id}`)
  }
}

Released under the MIT License.