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