refactor(simulator): switch utils to internal module export/import
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / UIServerUtils.ts
CommitLineData
6c1761d4 1import type { IncomingMessage } from 'http';
8114d10e 2
268a74bb 3import { Protocol, ProtocolVersion } from '../../types';
60a74391 4import { Utils, logger } from '../../utils';
4198ad5c 5
ed3d2808 6export class UIServerUtils {
d5bd1c00
JB
7 private constructor() {
8 // This is intentional
9 }
10
e7aeea18
JB
11 public static handleProtocols = (
12 protocols: Set<string>,
7cb5b17f 13 // eslint-disable-next-line @typescript-eslint/no-unused-vars
e7aeea18
JB
14 request: IncomingMessage
15 ): string | false => {
4198ad5c
JB
16 let protocol: Protocol;
17 let version: ProtocolVersion;
a92929f1
JB
18 if (protocols.size === 0) {
19 return false;
20 }
4198ad5c 21 for (const fullProtocol of protocols) {
ed3d2808 22 if (UIServerUtils.isProtocolAndVersionSupported(fullProtocol) === true) {
4198ad5c
JB
23 return fullProtocol;
24 }
25 }
e7aeea18
JB
26 logger.error(
27 `${Utils.logPrefix(
32de5a57 28 ' UI WebSocket Server |'
e7aeea18
JB
29 )} Unsupported protocol: ${protocol} or protocol version: ${version}`
30 );
4198ad5c
JB
31 return false;
32 };
d5bd1c00 33
7cb5b17f 34 public static isProtocolAndVersionSupported = (protocolStr: string): boolean => {
ed3d2808 35 const [protocol, version] = UIServerUtils.getProtocolAndVersion(protocolStr);
7cb5b17f
JB
36 return (
37 Object.values(Protocol).includes(protocol) === true &&
38 Object.values(ProtocolVersion).includes(version) === true
39 );
40 };
1f7fa4de 41
a92929f1
JB
42 public static getProtocolAndVersion = (protocolStr: string): [Protocol, ProtocolVersion] => {
43 const protocolIndex = protocolStr.indexOf(Protocol.UI);
44 const protocol = protocolStr.substring(
45 protocolIndex,
46 protocolIndex + Protocol.UI.length
47 ) as Protocol;
48 const version = protocolStr.substring(protocolIndex + Protocol.UI.length) as ProtocolVersion;
49 return [protocol, version];
50 };
51
d5bd1c00
JB
52 public static isLoopback(address: string): boolean {
53 const isLoopbackRegExp = new RegExp(
54 // eslint-disable-next-line no-useless-escape
55 /^localhost$|^127(?:\.\d+){0,2}\.\d+$|^(?:0*\:)*?:?0*1$/,
56 'i'
57 );
58 return isLoopbackRegExp.test(address);
59 }
4198ad5c 60}