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';
15 } from
'../../types/UIProtocol';
16 import Configuration from
'../../utils/Configuration';
17 import logger from
'../../utils/Logger';
18 import Utils from
'../../utils/Utils';
19 import { AbstractUIServer
} from
'./AbstractUIServer';
20 import UIServiceFactory from
'./ui-services/UIServiceFactory';
21 import { UIServiceUtils
} from
'./ui-services/UIServiceUtils';
23 const moduleName
= 'UIHttpServer';
25 type responseHandler
= { procedureName
: ProcedureName
; res
: ServerResponse
};
27 export default class UIHttpServer
extends AbstractUIServer
{
28 private readonly responseHandlers
: Map
<string, responseHandler
>;
30 public constructor(private options
?: ServerOptions
) {
32 this.server
= new Server(this.requestListener
.bind(this) as RequestListener
);
33 this.responseHandlers
= new Map
<string, responseHandler
>();
36 public start(): void {
37 (this.server
as Server
).listen(this.options
?? Configuration
.getUIServer().options
);
41 this.chargingStations
.clear();
44 // eslint-disable-next-line @typescript-eslint/no-unused-vars
45 public sendRequest(request
: string): void {
46 // This is intentionally left blank
49 public sendResponse(response
: string): void {
50 const [uuid
, payload
] = JSON
.parse(response
) as ProtocolResponse
;
51 let statusCode
: number;
52 switch (payload
.status) {
53 case ResponseStatus
.SUCCESS
:
54 statusCode
= StatusCodes
.OK
;
56 case ResponseStatus
.FAILURE
:
58 statusCode
= StatusCodes
.BAD_REQUEST
;
61 if (this.responseHandlers
.has(uuid
)) {
62 const { procedureName
, res
} = this.responseHandlers
.get(uuid
);
63 res
.writeHead(statusCode
, { 'Content-Type': 'application/json' });
64 res
.write(JSON
.stringify(payload
));
66 this.responseHandlers
.delete(uuid
);
69 `${this.logPrefix()} ${moduleName}.sendResponse: Response received for unknown request: ${response}`
74 public logPrefix(modName
?: string, methodName
?: string): string {
76 modName
&& methodName
? ` UI HTTP Server | ${modName}.${methodName}:` : ' UI HTTP Server |';
77 return Utils
.logPrefix(logMsg
);
80 private requestListener(req
: IncomingMessage
, res
: ServerResponse
): void {
81 // Expected request URL pathname: /ui/:version/:procedureName
82 const [protocol
, version
, procedureName
] = req
.url
?.split('/').slice(1) as [
87 const uuid
= Utils
.generateUUID();
88 this.responseHandlers
.set(uuid
, { procedureName
, res
});
90 if (UIServiceUtils
.isProtocolSupported(protocol
, version
) === false) {
91 throw new BaseError(`Unsupported UI protocol version: '/${protocol}/${version}'`);
93 req
.on('error', (error
) => {
97 'requestListener.req.onerror'
98 )} Error at incoming request handling:`,
102 if (!this.uiServices
.has(version
)) {
103 this.uiServices
.set(version
, UIServiceFactory
.getUIServiceImplementation(version
, this));
105 if (req
.method
=== 'POST') {
106 const bodyBuffer
= [];
107 let body
: RequestPayload
;
109 .on('data', (chunk
) => {
110 bodyBuffer
.push(chunk
);
113 body
= JSON
.parse(Buffer
.concat(bodyBuffer
).toString()) as RequestPayload
;
116 .requestHandler(this.buildRequest(uuid
, procedureName
, body
?? {}))
118 this.sendResponse(this.buildResponse(uuid
, { status: ResponseStatus
.FAILURE
}));
122 throw new BaseError(`Unsupported HTTP method: '${req.method}'`);
125 this.sendResponse(this.buildResponse(uuid
, { status: ResponseStatus
.FAILURE
}));
129 private buildRequest(
131 procedureName
: ProcedureName
,
132 requestPayload
: RequestPayload
134 return JSON
.stringify([id
, procedureName
, requestPayload
]);
137 private buildResponse(id
: string, responsePayload
: ResponsePayload
): string {
138 return JSON
.stringify([id
, responsePayload
]);