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