Skip to main content

Adapters

The @axisparkjs/websocket package defines the WebSocket plugin and the WebSocketAdapter contract. A transport integration implements that contract to initialize a server, register event definitions, start listening, and stop cleanly.

The Socket.IO implementation is provided separately by @axisparkjs/websocket-socketio. Its WebSocketPluginOptionsFactory configures WebSocketPlugin with SocketIOWebSocketAdapter:

import { WebSocketPlugin } from '@axisparkjs/websocket';
import { WebSocketPluginOptionsFactory } from '@axisparkjs/websocket-socketio';

app.use(WebSocketPlugin, WebSocketPluginOptionsFactory.create({
path: '/realtime',
port: 4000
}));

To provide a different transport, implement the WebSocketAdapter interface and pass its class as the adapter option. The adapter receives the generated WebSocketEventDefinition[] through registerEvents. Each definition includes its namespace, event name, and handler. It can call the handler with a context containing the current connection and, for message events, the message.

import { WebSocketPlugin } from '@axisparkjs/websocket';
import type { WebSocketAdapter } from '@axisparkjs/websocket';

class CustomWebSocketAdapter implements WebSocketAdapter {
registerEvents(events) { ... }
getRegisteredEvents() { ... }
initialize(server?) { ... }
start() { ... }
stop() { ... }
}

app.use(WebSocketPlugin, {
plugin: WebSocketPlugin,
adapter: CustomWebSocketAdapter,
useHttpPluginServer: false
});

initialize(server) receives the HTTP server when useHttpPluginServer is enabled and the HTTP Plugin is registered. Otherwise, the adapter is responsible for creating its own server. initialize is optional; the other adapter methods are required. The adapter option is required by WebSocketPluginOptions.