WebSockets¶
A deep dive into the websockets starter: @WebSocketController, subscribing to frames, injecting the socket and the underlying request, and running HTTP and WebSocket on one injector.
Source: websockets
The smallest starter in the set, and the clearest demonstration that a WebSocket handler is just another provider: it injects services, it has a lifecycle hook, and it lives in the same module graph as the HTTP controller next to it.
Project layout¶
src
├─ app.controller.ts # GET / → "Hello World!"
├─ app.controller-socket.ts # @WebSocketController on /ws
├─ app.module.ts # both controllers in one graph
├─ app.service.ts
└─ bootstrap.ts # pipeServer + pipeWebSocket + pipeSwagger
One graph, two protocols¶
@RootModule({
imports: [],
controllers: [AppController, AppControllerSocket],
providers: [AppService],
shared_providers: [/* Logger factory */]
})
export class AppModule {
}
The socket controller is listed in controllers — the same array as the HTTP controller. The module does not distinguish protocols; the difference is which pipe registers the class:
async function bootstrap() {
const server = createServer();
await pipeServer(server, AppModule); // HTTP controllers → router
await pipeWebSocket(server, AppModule); // @WebSocketController → upgrade handling
await pipeSwagger(server, AppModule, {path: "/docs"});
server.listen(8080);
}
pipeWebSocket runs after pipeServer for the same reason pipeGraphQL does: it reads the module injector that pipeServer stored on the root module class. Both protocols therefore share provider instances — the Logger injected into a socket handler is the same logger the HTTP controller sees.
The socket controller¶
@WebSocketController({
socketOptions: {
path: "/ws"
}
})
export class AppControllerSocket implements IAfterConstruct {
@Inject() logger: Logger;
@Inject() socket: WebSocket;
@Inject() request: IncomingMessage;
@Subscribe("message")
onMessage(@Arg() buffer: Buffer, @Arg() isBinary: boolean) {
this.logger.debug({message: buffer.toString(), isBinary}, "MESSAGE SENT");
this.socket.send(JSON.stringify({
message: "RECEIVED: " + buffer.toString()
}));
}
afterConstruct(): void {
this.logger.info({headers: this.request.headers});
}
}
| Piece | Meaning |
|---|---|
@WebSocketController({socketOptions: {path: "/ws"}}) | binds the class to the /ws upgrade path |
@Subscribe("message") | handles the message event of the raw socket |
@Arg() | positional handler arguments — here the buffer and the isBinary flag |
@Inject() socket | the WebSocket instance, used to send a reply |
@Inject() request | the underlying IncomingMessage, so headers are available |
afterConstruct() | runs once per connection, after injection |
The starter echoes framed as JSON: send hello and you get {"message":"RECEIVED: hello"}.
Because the class is instantiated per connection, request-scoped injection works exactly as it does for an HTTP request: request is that connection's handshake request, and socket is that socket. There is no global connection registry to manage.
Verifying the upgrade¶
The HTTP route answers normally, and the WebSocket path answers an upgrade handshake:
curl http://localhost:8080/ # Hello World! (200)
curl -i -H 'Connection: Upgrade' \
-H 'Upgrade: websocket' \
-H 'Sec-WebSocket-Version: 13' \
-H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==' \
http://localhost:8080/ws # 101 Switching Protocols
A 101 proves the route is registered and the handshake is accepted. To exercise @Subscribe you need a real client (ws, wscat, or the browser WebSocket API) — an HTTP request cannot carry frames.
Documentation¶
pipeSwagger documents GET / and nothing else:
expect(Object.keys(document.paths)).toEqual(["/"]);
That is not an omission to fix later: OpenAPI describes HTTP operations, and a WebSocket connection is not one. @WebSocketController classes are not @Controller, so they produce no route definitions, and the socket endpoint is described in the document's info.description instead:
info: {
title: "Websockets starter",
version: "1.0.0",
description: "http health check plus a websocket endpoint on /ws, which accepts text frames and answers with RECEIVED: <payload>"
}
Protocol-level documentation for sockets has to live somewhere else — a plain markdown page, AsyncAPI, or a comment on the event contract. Pretending otherwise produces an OpenAPI document that lies.
Tests¶
| File | Kind | Covers |
|---|---|---|
app.controller.spec.ts | unit | the HTTP handler |
swagger.spec.ts | build-time | the document lists only /, and the socket controller stays out |
Pitfalls¶
pipeWebSocketneeds a realserver.Server.fakeHttpServerpipes an in-process server withisMockServer: true; upgrades need a listening socket, so socket behaviour is verified against a real listener (or a client library) rather than the fake API.- Order matters.
pipeWebSocketbeforepipeServerthrows, because there is no module injector to read yet. socketOptions.pathis the upgrade path, not a route prefix; it is not prefixed by a modulepaththe way controllers are.- Binary frames arrive as
Buffer.@Arg() isBinarytells you which one you got; a handler that always callstoString()silently mangles binary payloads.
Next: Socket.IO — the same shape with a protocol on top.