WebSocketRoute

The WebSocketRoute class defines a WebSocket endpoint with automatic registration to the global router. It accepts a path and a definition object containing lifecycle handlers for connection open, close, and message events. This class doesn't really do much. It's just a thin wrapper on top of Bun's websocket implementation to register it to the router. Read more here: Bun Docs.

Contents
  1. Usage
  2. Constructor Parameters
  3. Properties

Usage

Routes can be instantiated directly with new. The constructor automatically registers the route to the global router store.

Simple WebSocket echo

import { C } from "@ozanarslan/corpus";

// GET /ws upgrades to WebSocket
new C.WebSocketRoute("/ws", {
	onMessage: (ws, message) => {
		ws.send(`Echo: ${message}`);
	},
});

Extending the abstract class

It makes sense to extend the abstract class since the definition involves 3 callbacks and can become pretty ugly.

class MyRoute extends C.WebSocketRouteAbstract {
	constructor() {
		super();
		// this method needs to be called to register it to the router
		// here or where you instantiate
		this.register();
	}

	path: string = "/ws";
	onClose?: C.WebSocketOnClose | undefined = undefined;
	onOpen?: C.WebSocketOnOpen | undefined = undefined;
	onMessage: C.WebSocketOnMessage = (ws, message) => {
		ws.send(`ECHO: ${message}`);
	};
}

Full lifecycle handlers

import { C } from "@ozanarslan/corpus";

new C.WebSocketRoute("/chat", {
	onOpen: (ws) => {
		console.log("Client connected");
		ws.send("Welcome!");
	},
	onMessage: (ws, message) => {
		broadcast(message);
	},
	onClose: (ws, code, reason) => {
		console.log(`Client disconnected: ${code} ${reason}`);
	},
});

Binary message handling

import { C } from "@ozanarslan/corpus";

new C.WebSocketRoute("/binary", {
	onMessage: (ws, message) => {
		if (message instanceof Buffer) {
			ws.send(message); // echo binary
		}
	},
});

Constructor Parameters

path

E extends string

The URL endpoint path. Always uses GET method (WebSocket upgrade handshake).

definition

WebSocketRouteDefinition

The WebSocket lifecycle definition object.

type WebSocketRouteDefinition = {
	onOpen?: Func<[ws: CWebSocketInterface], MaybePromise<void>>;
	onClose?: Func<[ws: CWebSocketInterface, code?: number, reason?: string], MaybePromise<void>>;
	onMessage: Func<[ws: CWebSocketInterface, message: string | Buffer], MaybePromise<void>>;
};
HandlerRequiredDescription
onMessageYesCalled when a message is received from the client. message is string for text frames or Buffer for binary frames.
onOpenNoCalled when the WebSocket connection is established.
onCloseNoCalled when the connection closes. Receives close code and reason string.

Properties

All constructor options are stored as readonly properties:

PropertyTypeDescription
idstringUnique route identifier ({method}:{endpoint})
methodMethodFixed to Method.GET (WebSocket upgrade)
endpointEResolved path
handlerFuncReturns this for internal routing
modelundefinedNot applicable for WebSocket routes
variantRouteVariant.websocketFixed to websocket for this class
onOpenFunc | undefinedConnection open handler
onCloseFunc | undefinedConnection close handler
onMessageFuncMessage receive handler (required)