Commit | Line | Data |
---|---|---|
4198ad5c JB |
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 | 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; | |
4198ad5c JB |
15 | this.messageHandlers = new Map<ProtocolCommand, ProtocolRequestHandler>([ |
16 | [ProtocolCommand.LIST_CHARGING_STATIONS, this.handleListChargingStations.bind(this)], | |
17 | ]); | |
18 | } | |
19 | ||
20 | public async handleMessage(command: ProtocolCommand, payload: Record<string, unknown>): Promise<void> { | |
21 | let messageResponse: Record<string, unknown>; | |
22 | if (this.messageHandlers.has(command)) { | |
23 | try { | |
24 | // Call the method to build the message response | |
25 | messageResponse = await this.messageHandlers.get(command)(payload) as Record<string, unknown>; | |
26 | } catch (error) { | |
27 | // Log | |
28 | logger.error(this.uiWebSocketServer.logPrefix() + ' Handle message error: %j', error); | |
29 | throw error; | |
30 | } | |
31 | } else { | |
32 | // Throw exception | |
33 | throw new BaseError(`${command} is not implemented to handle message payload ${JSON.stringify(payload, null, 2)}`); | |
34 | } | |
35 | // Send the built message response | |
36 | this.uiWebSocketServer.broadcastToClients(this.buildProtocolMessage(command, messageResponse)); | |
37 | } | |
38 | ||
39 | protected buildProtocolMessage( | |
40 | command: ProtocolCommand, | |
41 | payload: Record<string, unknown>, | |
42 | ): string { | |
43 | return JSON.stringify([command, payload]); | |
44 | } | |
45 | ||
46 | protected handleListChargingStations(): Set<string> { | |
47 | return this.chargingStations; | |
48 | } | |
49 | } |