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