1 import { IncomingMessage
, RequestListener
, Server
, ServerResponse
} from
'http';
3 import { StatusCodes
} from
'http-status-codes';
5 import BaseError from
'../../exception/BaseError';
6 import { ServerOptions
} from
'../../types/ConfigurationData';
16 } from
'../../types/UIProtocol';
17 import Configuration from
'../../utils/Configuration';
18 import logger from
'../../utils/Logger';
19 import Utils from
'../../utils/Utils';
20 import { AbstractUIServer
} from
'./AbstractUIServer';
21 import UIServiceFactory from
'./ui-services/UIServiceFactory';
22 import { UIServiceUtils
} from
'./ui-services/UIServiceUtils';
24 const moduleName
= 'UIHttpServer';
26 type responseHandler
= { procedureName
: ProcedureName
; res
: ServerResponse
};
28 export default class UIHttpServer
extends AbstractUIServer
{
29 private readonly responseHandlers
: Map
<string, responseHandler
>;
31 public constructor(private options
?: ServerOptions
) {
33 this.server
= new Server(this.requestListener
.bind(this) as RequestListener
);
34 this.responseHandlers
= new Map
<string, responseHandler
>();
37 public start(): void {
38 (this.server
as Server
).listen(this.options
?? Configuration
.getUIServer().options
);
42 this.chargingStations
.clear();
45 // eslint-disable-next-line @typescript-eslint/no-unused-vars
46 public sendRequest(request
: string): void {
47 // This is intentionally left blank
50 public sendResponse(response
: string): void {
51 const [uuid
, payload
] = JSON
.parse(response
) as ProtocolResponse
;
52 const statusCode
= this.responseStatusToStatusCode(payload
.status);
53 if (this.responseHandlers
.has(uuid
)) {
54 const { res
} = this.responseHandlers
.get(uuid
);
55 res
.writeHead(statusCode
, { 'Content-Type': 'application/json' });
56 res
.write(JSON
.stringify(payload
));
58 this.responseHandlers
.delete(uuid
);
61 `${this.logPrefix()} ${moduleName}.sendResponse: Response for unknown request: ${response}`
66 public logPrefix(modName
?: string, methodName
?: string): string {
68 modName
&& methodName
? ` UI HTTP Server | ${modName}.${methodName}:` : ' UI HTTP Server |';
69 return Utils
.logPrefix(logMsg
);
72 private requestListener(req
: IncomingMessage
, res
: ServerResponse
): void {
73 // Expected request URL pathname: /ui/:version/:procedureName
74 const [protocol
, version
, procedureName
] = req
.url
?.split('/').slice(1) as [
79 const uuid
= Utils
.generateUUID();
80 this.responseHandlers
.set(uuid
, { procedureName
, res
});
82 if (UIServiceUtils
.isProtocolSupported(protocol
, version
) === false) {
83 throw new BaseError(`Unsupported UI protocol version: '/${protocol}/${version}'`);
85 req
.on('error', (error
) => {
87 `${this.logPrefix(moduleName, 'requestListener.req.onerror')} Error on HTTP request:`,
91 if (!this.uiServices
.has(version
)) {
92 this.uiServices
.set(version
, UIServiceFactory
.getUIServiceImplementation(version
, this));
94 if (req
.method
=== 'POST') {
95 const bodyBuffer
= [];
97 .on('data', (chunk
) => {
98 bodyBuffer
.push(chunk
);
101 const body
= JSON
.parse(Buffer
.concat(bodyBuffer
).toString()) as RequestPayload
;
104 .requestHandler(this.buildRequest(uuid
, procedureName
, body
?? {}))
106 this.sendResponse(this.buildResponse(uuid
, { status: ResponseStatus
.FAILURE
}));
110 throw new BaseError(`Unsupported HTTP method: '${req.method}'`);
114 `${this.logPrefix(moduleName, 'requestListener')} Handle HTTP request error:`,
117 this.sendResponse(this.buildResponse(uuid
, { status: ResponseStatus
.FAILURE
}));
121 private buildRequest(
123 procedureName
: ProcedureName
,
124 requestPayload
: RequestPayload
126 return JSON
.stringify([id
, procedureName
, requestPayload
] as ProtocolRequest
);
129 private buildResponse(id
: string, responsePayload
: ResponsePayload
): string {
130 return JSON
.stringify([id
, responsePayload
] as ProtocolResponse
);
133 private responseStatusToStatusCode(status: ResponseStatus
): StatusCodes
{
135 case ResponseStatus
.SUCCESS
:
136 return StatusCodes
.OK
;
137 case ResponseStatus
.FAILURE
:
138 return StatusCodes
.BAD_REQUEST
;
140 return StatusCodes
.INTERNAL_SERVER_ERROR
;