Move the UI WS protocol version handling is protocol header
[e-mobility-charging-stations-simulator.git] / src / charging-station / UIWebSocketServices / AbstractUIService.ts
CommitLineData
4198ad5c
JB
1import { ProtocolCommand, ProtocolRequestHandler } from '../../types/UIProtocol';
2
3import BaseError from '../../exception/BaseError';
4import UIWebSocketServer from '../UIWebSocketServer';
5import logger from '../../utils/Logger';
6
7export default abstract class AbstractUIService {
8 public readonly chargingStations: Set<string>;
9 protected readonly uiWebSocketServer: UIWebSocketServer;
10 protected readonly messageHandlers: Map<ProtocolCommand, ProtocolRequestHandler>;
11
12 constructor(uiWebSocketServer: UIWebSocketServer) {
13 this.chargingStations = new Set<string>();
14 this.uiWebSocketServer = uiWebSocketServer;
15 // TODO: Move the shared service code to AbstractUIService
16 this.messageHandlers = new Map<ProtocolCommand, ProtocolRequestHandler>([
17 [ProtocolCommand.LIST_CHARGING_STATIONS, this.handleListChargingStations.bind(this)],
18 ]);
19 }
20
21 public async handleMessage(command: ProtocolCommand, payload: Record<string, unknown>): Promise<void> {
22 let messageResponse: Record<string, unknown>;
23 if (this.messageHandlers.has(command)) {
24 try {
25 // Call the method to build the message response
26 messageResponse = await this.messageHandlers.get(command)(payload) as Record<string, unknown>;
27 } catch (error) {
28 // Log
29 logger.error(this.uiWebSocketServer.logPrefix() + ' Handle message error: %j', error);
30 throw error;
31 }
32 } else {
33 // Throw exception
34 throw new BaseError(`${command} is not implemented to handle message payload ${JSON.stringify(payload, null, 2)}`);
35 }
36 // Send the built message response
37 this.uiWebSocketServer.broadcastToClients(this.buildProtocolMessage(command, messageResponse));
38 }
39
40 protected buildProtocolMessage(
41 command: ProtocolCommand,
42 payload: Record<string, unknown>,
43 ): string {
44 return JSON.stringify([command, payload]);
45 }
46
47 protected handleListChargingStations(): Set<string> {
48 return this.chargingStations;
49 }
50}