rpc-websocketserver
Version:
Simple rpc websocket server, wrapping the very popular 'ws' library. Register your RPCs with convenient decorators.
74 lines (73 loc) • 2.77 kB
TypeScript
import WebSocket from 'ws';
import { MessageHandler, Method } from './interfaces';
/**
* Abstract WebSocketServer class. Describes a namespace once inherited.
* Wraps the ws lib WebSocket.Server. Includes convenience methods to interact with clients.
*
* @abstract
* @example
* class NamespaceA extends WebSocketServer {
* constructor(messageHandler: MessageHandler, options: WebSocket.ServerOptions) {
* super(messageHandler, options);
* }
*
* `@register()`
* sum(@param('a') a: number, @param('b') b: number) {
* return a + b;
* }
* }
*/
export declare abstract class WebSocketServer {
wss: WebSocket.Server;
protected static methods: Set<Method>;
protected readonly _namespaceMethods: Map<string, Method>;
protected _messageHandler: MessageHandler;
/**
* @param messageHandler {MessageHandler} - MessageHandler instance
* @param options {WebSocket.ServerOptions} - ws server options
* @protected
*/
protected constructor(messageHandler: MessageHandler, options: WebSocket.ServerOptions);
/**
* Returns all registered methods of namespace
*
* @returns {Map<string, Method>} - Map of all registered methods in namespace with method name as key
*/
getMethods(): Map<string, Method>;
/**
* Sends passed data to all connected clients
*
* @param {WebSocket.Data} data - data to be sent to clients
*/
broadcastMessage(data: WebSocket.Data): void;
/**
* Sends passed data to passed websocket
*
* @param ws {WebSocket} - client to receive data
* @param data {WebSocket.Data} - data to be sent to client
* @protected
*/
protected _sendMessage(ws: WebSocket, data: WebSocket.Data): void;
/**
* Convenience method to set listeners on websocket connection
*
* @param ws {WebSocket} - websocket/client that established a connection
* @protected
*/
protected _onConnection(ws: WebSocket): void;
/**
* On message listener to handle and process incoming messages
*
* @param ws {WebSocket} - websocket/client that sent the message
* @param message {WebSocket.Data} - data received from the client
* @protected
* @returns {Promise<void>}
*/
protected _onMessage(ws: WebSocket, message: WebSocket.Data): Promise<void>;
/**
* Convenience method to initialize namespace specific methods instance variable from all registered methods
*
* @returns {Map<string, Method>} - Map of all registered methods in namespace with method name as key
*/
private _initNamespaceMethods;
}