fix: fix worker options argument passing to worker pool/set
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / UIHttpServer.ts
index 37c579dc56a552dc26dbd57ae515378820e9e2d9..159559df1f4cacb6eebaa1f67b8e6cca66ac030a 100644 (file)
@@ -1,35 +1,39 @@
-import type { IncomingMessage, RequestListener, ServerResponse } from 'http';
+import type { IncomingMessage, RequestListener, ServerResponse } from 'node:http';
 
 import { StatusCodes } from 'http-status-codes';
 
-import BaseError from '../../exception/BaseError';
-import type { UIServerConfiguration } from '../../types/ConfigurationData';
+import { AbstractUIServer } from './AbstractUIServer';
+import { UIServerUtils } from './UIServerUtils';
+import { BaseError } from '../../exception';
 import {
-  ProcedureName,
-  Protocol,
-  ProtocolRequest,
-  ProtocolResponse,
-  ProtocolVersion,
-  RequestPayload,
+  type ProcedureName,
+  type Protocol,
+  type ProtocolRequest,
+  type ProtocolResponse,
+  type ProtocolVersion,
+  type RequestPayload,
   ResponseStatus,
-} from '../../types/UIProtocol';
-import logger from '../../utils/Logger';
-import Utils from '../../utils/Utils';
-import { AbstractUIServer } from './AbstractUIServer';
-import { UIServiceUtils } from './ui-services/UIServiceUtils';
+  type UIServerConfiguration,
+} from '../../types';
+import { Constants, Utils, logger } from '../../utils';
 
 const moduleName = 'UIHttpServer';
 
-export default class UIHttpServer extends AbstractUIServer {
+enum HttpMethods {
+  GET = 'GET',
+  PUT = 'PUT',
+  POST = 'POST',
+  PATCH = 'PATCH',
+}
+
+export class UIHttpServer extends AbstractUIServer {
   public constructor(protected readonly uiServerConfiguration: UIServerConfiguration) {
     super(uiServerConfiguration);
   }
 
   public start(): void {
     this.httpServer.on('request', this.requestListener.bind(this) as RequestListener);
-    if (this.httpServer.listening === false) {
-      this.httpServer.listen(this.uiServerConfiguration.options);
-    }
+    this.startHttpServer();
   }
 
   // eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -40,7 +44,7 @@ export default class UIHttpServer extends AbstractUIServer {
   public sendResponse(response: ProtocolResponse): void {
     const [uuid, payload] = response;
     try {
-      if (this.responseHandlers.has(uuid) === true) {
+      if (this.hasResponseHandler(uuid) === true) {
         const res = this.responseHandlers.get(uuid) as ServerResponse;
         res
           .writeHead(this.responseStatusToStatusCode(payload.status), {
@@ -62,12 +66,14 @@ export default class UIHttpServer extends AbstractUIServer {
     }
   }
 
-  public logPrefix(modName?: string, methodName?: string, prefixSuffix?: string): string {
+  public logPrefix = (modName?: string, methodName?: string, prefixSuffix?: string): string => {
     const logMsgPrefix = prefixSuffix ? `UI HTTP Server ${prefixSuffix}` : 'UI HTTP Server';
     const logMsg =
-      modName && methodName ? ` ${logMsgPrefix} | ${modName}.${methodName}:` : ` ${logMsgPrefix} |`;
+      Utils.isNotEmptyString(modName) && Utils.isNotEmptyString(methodName)
+        ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
+        : ` ${logMsgPrefix} |`;
     return Utils.logPrefix(logMsg);
-  }
+  };
 
   private requestListener(req: IncomingMessage, res: ServerResponse): void {
     this.authenticate(req, (err) => {
@@ -91,8 +97,9 @@ export default class UIHttpServer extends AbstractUIServer {
     const uuid = Utils.generateUUID();
     this.responseHandlers.set(uuid, res);
     try {
-      if (UIServiceUtils.isProtocolAndVersionSupported(protocol, version) === false) {
-        throw new BaseError(`Unsupported UI protocol version: '/${protocol}/${version}'`);
+      const fullProtocol = `${protocol}${version}`;
+      if (UIServerUtils.isProtocolAndVersionSupported(fullProtocol) === false) {
+        throw new BaseError(`Unsupported UI protocol version: '${fullProtocol}'`);
       }
       this.registerProtocolVersionUIService(version);
       req.on('error', (error) => {
@@ -101,7 +108,7 @@ export default class UIHttpServer extends AbstractUIServer {
           error
         );
       });
-      if (req.method === 'POST') {
+      if (req.method === HttpMethods.POST) {
         const bodyBuffer = [];
         req
           .on('data', (chunk) => {
@@ -111,10 +118,19 @@ export default class UIHttpServer extends AbstractUIServer {
             const body = JSON.parse(Buffer.concat(bodyBuffer).toString()) as RequestPayload;
             this.uiServices
               .get(version)
-              .requestHandler(this.buildProtocolRequest(uuid, procedureName, body ?? {}))
-              .catch(() => {
-                /* Error caught by AbstractUIService */
-              });
+              ?.requestHandler(
+                this.buildProtocolRequest(
+                  uuid,
+                  procedureName,
+                  body ?? Constants.EMPTY_FREEZED_OBJECT
+                )
+              )
+              .then((protocolResponse: ProtocolResponse) => {
+                if (!Utils.isNullOrUndefined(protocolResponse)) {
+                  this.sendResponse(protocolResponse);
+                }
+              })
+              .catch(Constants.EMPTY_FUNCTION);
           });
       } else {
         throw new BaseError(`Unsupported HTTP method: '${req.method}'`);