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