6fb8a6add2550be30898b0f43fab18eb39153d8a
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';
14 } from
'../../types/UIProtocol';
15 import Configuration from
'../../utils/Configuration';
16 import logger from
'../../utils/Logger';
17 import Utils from
'../../utils/Utils';
18 import { AbstractUIServer
} from
'./AbstractUIServer';
19 import UIServiceFactory from
'./ui-services/UIServiceFactory';
20 import { UIServiceUtils
} from
'./ui-services/UIServiceUtils';
22 const moduleName
= 'UIHttpServer';
24 type responseHandler
= { procedureName
: ProcedureName
; res
: ServerResponse
};
26 export default class UIHttpServer
extends AbstractUIServer
{
27 private readonly responseHandlers
: Map
<string, responseHandler
>;
29 public constructor(private options
?: ServerOptions
) {
31 this.server
= new Server(this.requestListener
.bind(this) as RequestListener
);
32 this.responseHandlers
= new Map
<string, responseHandler
>();
35 public start(): void {
36 (this.server
as Server
).listen(this.options
?? Configuration
.getUIServer().options
);
40 this.chargingStations
.clear();
43 // eslint-disable-next-line @typescript-eslint/no-unused-vars
44 public sendRequest(request
: string): void {
45 // This is intentionally left blank
48 public sendResponse(response
: string): void {
49 const [uuid
, payload
] = JSON
.parse(response
) as ProtocolResponse
;
50 const statusCode
= this.responseStatusToStatusCode(payload
.status);
51 if (this.responseHandlers
.has(uuid
)) {
52 const { res
} = this.responseHandlers
.get(uuid
);
53 res
.writeHead(statusCode
, { 'Content-Type': 'application/json' });
54 res
.write(JSON
.stringify(payload
));
56 this.responseHandlers
.delete(uuid
);
59 `${this.logPrefix()} ${moduleName}.sendResponse: Response for unknown request: ${response}`
64 public logPrefix(modName
?: string, methodName
?: string): string {
66 modName
&& methodName
? ` UI HTTP Server | ${modName}.${methodName}:` : ' UI HTTP Server |';
67 return Utils
.logPrefix(logMsg
);
70 private requestListener(req
: IncomingMessage
, res
: ServerResponse
): void {
71 // Expected request URL pathname: /ui/:version/:procedureName
72 const [protocol
, version
, procedureName
] = req
.url
?.split('/').slice(1) as [
77 const uuid
= Utils
.generateUUID();
78 this.responseHandlers
.set(uuid
, { procedureName
, res
});
80 if (UIServiceUtils
.isProtocolSupported(protocol
, version
) === false) {
81 throw new BaseError(`Unsupported UI protocol version: '/${protocol}/${version}'`);
83 req
.on('error', (error
) => {
85 `${this.logPrefix(moduleName, 'requestListener.req.onerror')} Error on HTTP request:`,
89 if (!this.uiServices
.has(version
)) {
90 this.uiServices
.set(version
, UIServiceFactory
.getUIServiceImplementation(version
, this));
92 if (req
.method
=== 'POST') {
93 const bodyBuffer
= [];
95 .on('data', (chunk
) => {
96 bodyBuffer
.push(chunk
);
99 const body
= JSON
.parse(Buffer
.concat(bodyBuffer
).toString()) as RequestPayload
;
102 .requestHandler(this.buildProtocolRequest(uuid
, procedureName
, body
?? {}))
105 this.buildProtocolResponse(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.buildProtocolResponse(uuid
, { status: ResponseStatus
.FAILURE
}));
121 private responseStatusToStatusCode(status: ResponseStatus
): StatusCodes
{
123 case ResponseStatus
.SUCCESS
:
124 return StatusCodes
.OK
;
125 case ResponseStatus
.FAILURE
:
126 return StatusCodes
.BAD_REQUEST
;
128 return StatusCodes
.INTERNAL_SERVER_ERROR
;