1 import { ProtocolCommand
, ProtocolRequestHandler
} from
'../../types/UIProtocol';
3 import BaseError from
'../../exception/BaseError';
4 import UIWebSocketServer from
'../UIWebSocketServer';
5 import logger from
'../../utils/Logger';
7 export default abstract class AbstractUIService
{
8 protected readonly uiWebSocketServer
: UIWebSocketServer
;
9 protected readonly messageHandlers
: Map
<ProtocolCommand
, ProtocolRequestHandler
>;
11 constructor(uiWebSocketServer
: UIWebSocketServer
) {
12 this.uiWebSocketServer
= uiWebSocketServer
;
13 this.messageHandlers
= new Map
<ProtocolCommand
, ProtocolRequestHandler
>([
14 [ProtocolCommand
.LIST_CHARGING_STATIONS
, this.handleListChargingStations
.bind(this)],
18 public async handleMessage(command
: ProtocolCommand
, payload
: Record
<string, unknown
>): Promise
<void> {
19 let messageResponse
: Record
<string, unknown
>;
20 if (this.messageHandlers
.has(command
)) {
22 // Call the method to build the message response
23 messageResponse
= await this.messageHandlers
.get(command
)(payload
) as Record
<string, unknown
>;
26 logger
.error(this.uiWebSocketServer
.logPrefix() + ' Handle message error: %j', error
);
31 throw new BaseError(`${command} is not implemented to handle message payload ${JSON.stringify(payload, null, 2)}`);
33 // Send the built message response
34 this.uiWebSocketServer
.broadcastToClients(this.buildProtocolMessage(command
, messageResponse
));
37 protected buildProtocolMessage(
38 command
: ProtocolCommand
,
39 payload
: Record
<string, unknown
>,
41 return JSON
.stringify([command
, payload
]);
44 private handleListChargingStations(): Set
<string> {
45 return this.uiWebSocketServer
.chargingStations
;