UI protocol: cleanup version handling code
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / ui-services / UIServiceUtils.ts
index 06db5a47109f2c11b77eb938021748d86968eaf5..b6137886d76c105fda10f5cd667f7c37e7e94dc5 100644 (file)
@@ -1,4 +1,4 @@
-import { IncomingMessage } from 'http';
+import type { IncomingMessage } from 'http';
 
 import { Protocol, ProtocolVersion } from '../../../types/UIProtocol';
 import logger from '../../../utils/Logger';
@@ -11,19 +11,16 @@ export class UIServiceUtils {
 
   public static handleProtocols = (
     protocols: Set<string>,
+    // eslint-disable-next-line @typescript-eslint/no-unused-vars
     request: IncomingMessage
   ): string | false => {
-    let protocolIndex: number;
     let protocol: Protocol;
     let version: ProtocolVersion;
+    if (protocols.size === 0) {
+      return false;
+    }
     for (const fullProtocol of protocols) {
-      protocolIndex = fullProtocol.indexOf(Protocol.UI);
-      protocol = fullProtocol.substring(
-        protocolIndex,
-        protocolIndex + Protocol.UI.length
-      ) as Protocol;
-      version = fullProtocol.substring(protocolIndex + Protocol.UI.length) as ProtocolVersion;
-      if (UIServiceUtils.isProtocolSupported(protocol, version) === true) {
+      if (UIServiceUtils.isProtocolAndVersionSupported(fullProtocol) === true) {
         return fullProtocol;
       }
     }
@@ -35,8 +32,23 @@ export class UIServiceUtils {
     return false;
   };
 
-  public static isProtocolSupported = (protocol: Protocol, version: ProtocolVersion): boolean =>
-    Object.values(Protocol).includes(protocol) && Object.values(ProtocolVersion).includes(version);
+  public static isProtocolAndVersionSupported = (protocolStr: string): boolean => {
+    const [protocol, version] = UIServiceUtils.getProtocolAndVersion(protocolStr);
+    return (
+      Object.values(Protocol).includes(protocol) === true &&
+      Object.values(ProtocolVersion).includes(version) === true
+    );
+  };
+
+  public static getProtocolAndVersion = (protocolStr: string): [Protocol, ProtocolVersion] => {
+    const protocolIndex = protocolStr.indexOf(Protocol.UI);
+    const protocol = protocolStr.substring(
+      protocolIndex,
+      protocolIndex + Protocol.UI.length
+    ) as Protocol;
+    const version = protocolStr.substring(protocolIndex + Protocol.UI.length) as ProtocolVersion;
+    return [protocol, version];
+  };
 
   public static isLoopback(address: string): boolean {
     const isLoopbackRegExp = new RegExp(