Commit | Line | Data |
---|---|---|
8114d10e JB |
1 | import { RawData } from 'ws'; |
2 | ||
3 | import BaseError from '../../../exception/BaseError'; | |
4 | import { JsonType } from '../../../types/JsonType'; | |
675fa8e3 JB |
5 | import { |
6 | ProtocolCommand, | |
7 | ProtocolRequest, | |
8 | ProtocolRequestHandler, | |
9 | } from '../../../types/UIProtocol'; | |
675fa8e3 | 10 | import logger from '../../../utils/Logger'; |
8114d10e JB |
11 | import Utils from '../../../utils/Utils'; |
12 | import { AbstractUIServer } from '../AbstractUIServer'; | |
4198ad5c JB |
13 | |
14 | export default abstract class AbstractUIService { | |
fe94fce0 | 15 | protected readonly uiServer: AbstractUIServer; |
4198ad5c JB |
16 | protected readonly messageHandlers: Map<ProtocolCommand, ProtocolRequestHandler>; |
17 | ||
fe94fce0 | 18 | constructor(uiServer: AbstractUIServer) { |
675fa8e3 | 19 | this.uiServer = uiServer; |
4198ad5c JB |
20 | this.messageHandlers = new Map<ProtocolCommand, ProtocolRequestHandler>([ |
21 | [ProtocolCommand.LIST_CHARGING_STATIONS, this.handleListChargingStations.bind(this)], | |
22 | ]); | |
23 | } | |
24 | ||
178ac666 JB |
25 | public async messageHandler(request: RawData): Promise<void> { |
26 | let command: ProtocolCommand; | |
27 | let payload: JsonType; | |
28 | const protocolRequest = JSON.parse(request.toString()) as ProtocolRequest; | |
29 | if (Utils.isIterable(protocolRequest)) { | |
30 | [command, payload] = protocolRequest; | |
31 | } else { | |
32 | throw new BaseError('UI protocol request is not iterable'); | |
33 | } | |
5cc4b63b | 34 | let messageResponse: JsonType; |
4198ad5c JB |
35 | if (this.messageHandlers.has(command)) { |
36 | try { | |
178ac666 | 37 | // Call the message handler to build the message response |
5cc4b63b | 38 | messageResponse = (await this.messageHandlers.get(command)(payload)) as JsonType; |
4198ad5c JB |
39 | } catch (error) { |
40 | // Log | |
675fa8e3 | 41 | logger.error(this.uiServer.logPrefix() + ' Handle message error: %j', error); |
4198ad5c JB |
42 | throw error; |
43 | } | |
44 | } else { | |
45 | // Throw exception | |
e7aeea18 JB |
46 | throw new BaseError( |
47 | `${command} is not implemented to handle message payload ${JSON.stringify( | |
48 | payload, | |
49 | null, | |
50 | 2 | |
51 | )}` | |
52 | ); | |
4198ad5c | 53 | } |
178ac666 | 54 | // Send the message response |
675fa8e3 | 55 | this.uiServer.sendResponse(this.buildProtocolMessage(command, messageResponse)); |
4198ad5c JB |
56 | } |
57 | ||
5cc4b63b | 58 | protected buildProtocolMessage(command: ProtocolCommand, payload: JsonType): string { |
4198ad5c JB |
59 | return JSON.stringify([command, payload]); |
60 | } | |
61 | ||
178ac666 | 62 | private handleListChargingStations(): JsonType { |
675fa8e3 | 63 | return Array.from(this.uiServer.chargingStations); |
4198ad5c JB |
64 | } |
65 | } |