1 import { ProtocolCommand
, ProtocolRequest
, ProtocolVersion
} from
'../types/UIProtocol';
3 import AbstractUIService from
'./WebSocketServices/ui/AbstractUIService';
4 import { IncomingMessage
} from
'http';
5 import UIService from
'./WebSocketServices/ui/0.0.1/UIService';
6 import Utils from
'../utils/Utils';
7 import WebSocket from
'ws';
8 import logger from
'../utils/Logger';
10 export default class WebSocketServer
extends WebSocket
.Server
{
11 private webSocketServerService
: AbstractUIService
;
13 public constructor(options
?: WebSocket
.ServerOptions
, callback
?: () => void) {
14 // Create the WebSocket Server
15 super(options
, callback
);
16 // FIXME: version the instantiation
17 this.webSocketServerService
= new UIService(this);
20 public broadcastToClients(message
: Record
<string, unknown
>): void {
21 for (const client
of this.clients
) {
22 if (client
?.readyState
=== WebSocket
.OPEN
) {
28 public start(): void {
29 this.on('connection', (socket
: WebSocket
, request
: IncomingMessage
): void => {
30 // FIXME: Check connection validity
31 socket
.on('message', (messageData
) => {
32 let [version
, command
, payload
]: ProtocolRequest
= [ProtocolVersion
['0.0.1'], ProtocolCommand
.UNKNOWN
, {}];
33 // FIXME: check for iterable object
34 [version
, command
, payload
] = JSON
.parse(messageData
.toString()) as ProtocolRequest
;
36 case ProtocolVersion
['0.0.1']:
37 this.webSocketServerService
.handleMessage(command
, payload
).catch(() => {
38 logger
.error(`${this.logPrefix()} Error while handling command %s message: %j`, command
, payload
);
42 logger
.error(`${this.logPrefix()} Unknown protocol version: ${version}`);
45 socket
.on('error', (error
) => {
46 logger
.error(`${this.logPrefix()} Error on WebSocket: %j`, error
);
55 public logPrefix(): string {
56 return Utils
.logPrefix('WebSocket Server:');