2d729bfc3be22b57ca4a0e71e26702245e5fedd2
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 const statusCode
= this.responseStatusToStatusCode(payload
.status);
52 if (this.responseHandlers
.has(uuid
)) {
53 const { res
} = this.responseHandlers
.get(uuid
);
54 res
.writeHead(statusCode
, { 'Content-Type': 'application/json' });
55 res
.write(JSON
.stringify(payload
));
57 this.responseHandlers
.delete(uuid
);
60 `${this.logPrefix()} ${moduleName}.sendResponse: Response received for unknown request: ${response}`
65 public logPrefix(modName
?: string, methodName
?: string): string {
67 modName
&& methodName
? ` UI HTTP Server | ${modName}.${methodName}:` : ' UI HTTP Server |';
68 return Utils
.logPrefix(logMsg
);
71 private requestListener(req
: IncomingMessage
, res
: ServerResponse
): void {
72 // Expected request URL pathname: /ui/:version/:procedureName
73 const [protocol
, version
, procedureName
] = req
.url
?.split('/').slice(1) as [
78 const uuid
= Utils
.generateUUID();
79 this.responseHandlers
.set(uuid
, { procedureName
, res
});
81 if (UIServiceUtils
.isProtocolSupported(protocol
, version
) === false) {
82 throw new BaseError(`Unsupported UI protocol version: '/${protocol}/${version}'`);
84 req
.on('error', (error
) => {
88 'requestListener.req.onerror'
89 )} Error at incoming request handling:`,
93 if (!this.uiServices
.has(version
)) {
94 this.uiServices
.set(version
, UIServiceFactory
.getUIServiceImplementation(version
, this));
96 if (req
.method
=== 'POST') {
97 const bodyBuffer
= [];
98 let body
: RequestPayload
;
100 .on('data', (chunk
) => {
101 bodyBuffer
.push(chunk
);
104 body
= JSON
.parse(Buffer
.concat(bodyBuffer
).toString()) as RequestPayload
;
107 .requestHandler(this.buildRequest(uuid
, procedureName
, body
?? {}))
109 this.sendResponse(this.buildResponse(uuid
, { status: ResponseStatus
.FAILURE
}));
113 throw new BaseError(`Unsupported HTTP method: '${req.method}'`);
116 this.sendResponse(this.buildResponse(uuid
, { status: ResponseStatus
.FAILURE
}));
120 private buildRequest(
122 procedureName
: ProcedureName
,
123 requestPayload
: RequestPayload
125 return JSON
.stringify([id
, procedureName
, requestPayload
]);
128 private buildResponse(id
: string, responsePayload
: ResponsePayload
): string {
129 return JSON
.stringify([id
, responsePayload
]);
132 private responseStatusToStatusCode(status: ResponseStatus
): StatusCodes
{
134 case ResponseStatus
.SUCCESS
:
135 return StatusCodes
.OK
;
136 case ResponseStatus
.FAILURE
:
137 return StatusCodes
.BAD_REQUEST
;
139 return StatusCodes
.INTERNAL_SERVER_ERROR
;