UI protocol: cleanup version handling code
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / ui-services / UIServiceUtils.ts
index dabb5d474e88a78aebe5ea965b5b591e9f20246e..b6137886d76c105fda10f5cd667f7c37e7e94dc5 100644 (file)
@@ -1,36 +1,61 @@
-import { Protocol, ProtocolVersion } from '../../../types/UIProtocol';
+import type { IncomingMessage } from 'http';
 
-import { IncomingMessage } from 'http';
-import Utils from '../../../utils/Utils';
+import { Protocol, ProtocolVersion } from '../../../types/UIProtocol';
 import logger from '../../../utils/Logger';
+import Utils from '../../../utils/Utils';
 
 export class UIServiceUtils {
+  private constructor() {
+    // This is intentional
+  }
+
   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 (
-        Object.values(Protocol).includes(protocol) &&
-        Object.values(ProtocolVersion).includes(version)
-      ) {
+      if (UIServiceUtils.isProtocolAndVersionSupported(fullProtocol) === true) {
         return fullProtocol;
       }
     }
     logger.error(
       `${Utils.logPrefix(
-        ' UI WebSocket Server:'
+        ' UI WebSocket Server |'
       )} Unsupported protocol: ${protocol} or protocol version: ${version}`
     );
     return false;
   };
+
+  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(
+      // eslint-disable-next-line no-useless-escape
+      /^localhost$|^127(?:\.\d+){0,2}\.\d+$|^(?:0*\:)*?:?0*1$/,
+      'i'
+    );
+    return isLoopbackRegExp.test(address);
+  }
 }