Skip to content

The typeix/resty-socket-io package: Socket.IO controllers, middleware and namespaces on the resty injector.

typeix/resty-socket-io

2 min read Source

Socket.IO support for the resty framework. Each connection gets a dedicated controller instance created from a child injector, and that instance is destroyed when the connection closes.

Requirements

  • Node.js ^26.0.0
  • @typeix/resty ^9.2.0
  • socket.io as a peer dependency

Installing

npm i @typeix/resty-socket-io socket.io

Usage

pipeWebSocket follows the same convention as the other resty extensions: it must run after pipeServer, because it reads the module injector that pipeServer stored on the root module class.

import {createServer} from "http";
import {pipeServer, Inject, Logger, RootModule} from "@typeix/resty";
import {pipeWebSocket, SocketIOController, Subscribe, Args, Arg, Socket} from "@typeix/resty-socket-io";

@SocketIOController({
  socketOptions: {
    path: "/socket.io"
  }
})
class ChatController {
  @Inject() logger: Logger;
  @Inject() socket: Socket;

  @Subscribe("message")
  onMessage(@Args() payload: unknown[]) {
    this.socket.emit("message", payload);
  }

  @Subscribe("disconnect")
  onDisconnect(@Arg() reason: unknown) {
    this.logger.info(`client left: ${reason}`);
  }
}

@RootModule({shared_providers: [], controllers: [ChatController]})
class Application {}

async function bootstrap() {
  const server = createServer();
  await pipeServer(server, Application);
  await pipeWebSocket(server, Application);
  server.listen(3000);
}

bootstrap();

Decorators

Decorator Level Purpose
@SocketIOController({socketOptions, providers?, middlewares?}) class declare a Socket.IO controller
@Subscribe(event, namespace?) method handle an incoming event, namespace defaults to "/"
@Args() parameter inject every event argument
@Arg() parameter inject the event body

@Inject() works as usual, so socket, logger and any provider in the module graph are injectable.

Socket.IO middleware is implemented by a class matching the Middleware interface and registered through middlewares; the package exports Middleware and MiddlewareClass as types.

import {Middleware, Socket} from "@typeix/resty-socket-io";

class AuthMiddleware implements Middleware {
  use(socket: Socket, next: (err?: Error) => void) {
    if (socket.handshake.auth?.token) {
      next();
    } else {
      next(new Error("unauthorized"));
    }
  }
}

@SocketIOController({
  socketOptions: {path: "/socket.io"},
  middlewares: [AuthMiddleware]
})
class ChatController {}

Lifecycle

  • One controller instance per connection, created from a child injector and destroyed on disconnect, so per-connection state on the controller is safe.
  • pipeWebSocket stores nothing on the sealed root module class. Its own state is keyed by that class, which is what allows it to run after pipeServer.
  • Per-controller registration is logged at debug level, not info.

Exported types

The Socket.IO types you normally need are re-exported, so a single import works:

Socket, DisconnectReason, ServerOptions, Namespace, BroadcastOperator, RemoteSocket.