The typeix/resty-ws package: WebSocket controllers on the resty injector, with socket options and per-connection instances.¶
typeix/resty-ws¶
Typeix WebSocket package for the resty framework. Each connection has a dedicated controller instance, and it is destroyed once the connection is closed or stale. The implementation is a wrapper over the ws package.
Requirements¶
- Node.js
^26.0.0 @typeix/resty^9.2.0wsas a peer dependency
Installing¶
npm i @typeix/resty-ws ws
Usage¶
import {createServer, IncomingMessage} from "http";
import {pipeServer, Inject, Logger, RootModule, IAfterConstruct} from "@typeix/resty";
import {pipeWebSocket, WebSocketController, Subscribe, Arg, Args, WebSocket} from "@typeix/resty-ws";
@WebSocketController({
socketOptions: {
path: "/ws"
}
})
class ChatController implements IAfterConstruct {
@Inject() logger: Logger;
@Inject() socket: WebSocket;
@Inject() request: IncomingMessage;
@Subscribe("message")
onMessage(@Arg() buffer: Buffer, @Arg() isBinary: boolean, @Args() args: [Buffer, boolean]) {
this.logger.info(buffer.toString(), isBinary);
this.socket.send(buffer.toString());
}
afterConstruct(): void {
this.logger.info({
headers: this.request.headers
});
}
}
@RootModule({
shared_providers: [],
controllers: [ChatController]
})
class Application {
}
async function bootstrap() {
const server = createServer();
await pipeServer(server, Application);
await pipeWebSocket(server, Application);
server.on("error", e => console.error(e));
server.listen(8080);
}
export default bootstrap();
Decorators¶
| Decorator | Level | Purpose |
|---|---|---|
@WebSocketController({socketOptions, providers?}) | class | declare a websocket controller, socketOptions.path is the endpoint |
@Subscribe(event) | method | handle an incoming event |
@Args() | parameter | inject every event argument |
@Arg() | parameter | inject the event body |
@Inject() works as usual, so socket, request, logger and any provider in the module graph are injectable. A controller may also implement IAfterConstruct to run code once the instance exists.
Socket options¶
socketOptions accepts the ws server options:
| Option | Meaning |
|---|---|
path | accept only connections matching this path |
maxPayload | maximum allowed message size in bytes, defaults to 100 MiB |
clientTracking | track connected clients |
perMessageDeflate | enable/disable permessage-deflate |
backlog | maximum length of the pending connection queue |
skipUTF8Validation | skip UTF-8 validation, only for trusted clients |
Events¶
@Subscribe() accepts the ws event names:
| Event | Arguments |
|---|---|
message | (@Arg() data: Buffer, @Arg() isBinary: boolean) |
close | (@Arg() code: number, @Arg() reason: Buffer) |
error | (@Arg() error: Error) |
open | – |
ping / pong | (@Arg() data: Buffer) |
upgrade | (@Arg() request: IncomingMessage) |
unexpected-response | (@Arg() request: ClientRequest, @Arg() response: IncomingMessage) |
redirect | (@Arg() url: string, @Arg() request: ClientRequest) |
Lifecycle¶
- One controller instance per connection, created from a child injector and destroyed when the connection closes, so per-connection state on the controller is safe.
pipeWebSocketmust run afterpipeServer, because it reads the module injector stored on the root module class. It keeps its own state keyed by that class, so it never writes to the sealed module.- Per-controller registration is logged at
debuglevel, notinfo.
The package re-exports the ws WebSocket type, so a single import is enough.
Testing¶
A real server on an ephemeral port is the most direct integration test:
import {createServer} from "http";
import {AddressInfo} from "net";
import {pipeServer, RootModule} from "@typeix/resty";
import {pipeWebSocket, WebSocket} from "@typeix/resty-ws";
@RootModule({shared_providers: [], controllers: [ChatController]})
class WebSocketApplication {}
const server = createServer();
await pipeServer(server, WebSocketApplication);
await pipeWebSocket(server, WebSocketApplication);
await new Promise<void>(resolve => server.listen(0, resolve));
const {port} = server.address() as AddressInfo;
const socket = new WebSocket(`ws://localhost:${port}/ws`);