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