Refine connector id validation error message
[e-mobility-charging-stations-simulator.git] / src / utils / Utils.ts
CommitLineData
c37528f1 1import crypto from 'crypto';
8114d10e 2
5e3cb728
JB
3import { WebSocketCloseEventStatusString } from '../types/WebSocket';
4
3f40bc9c 5export default class Utils {
d5bd1c00
JB
6 private constructor() {
7 // This is intentional
8 }
9
0f16a662 10 public static logPrefix(prefixString = ''): string {
147d0e0f
JB
11 return new Date().toLocaleString() + prefixString;
12 }
13
0f16a662 14 public static generateUUID(): string {
03eacbe5
JB
15 return crypto.randomUUID();
16 }
17
18 public static validateUUID(uuid: string): boolean {
8bd02502
JB
19 return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(
20 uuid
21 );
7dde0b73
JB
22 }
23
0f16a662 24 public static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> {
5f8a4fd6 25 return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds));
7dde0b73
JB
26 }
27
d7d1db72
JB
28 public static formatDurationMilliSeconds(duration: number): string {
29 duration = Utils.convertToInt(duration);
30 const hours = Math.floor(duration / (3600 * 1000));
e7aeea18
JB
31 const minutes = Math.floor((duration / 1000 - hours * 3600) / 60);
32 const seconds = duration / 1000 - hours * 3600 - minutes * 60;
a3868ec4
JB
33 let hoursStr = hours.toString();
34 let minutesStr = minutes.toString();
35 let secondsStr = seconds.toString();
d7d1db72
JB
36
37 if (hours < 10) {
38 hoursStr = '0' + hours.toString();
39 }
40 if (minutes < 10) {
41 minutesStr = '0' + minutes.toString();
42 }
43 if (seconds < 10) {
b322b8b4 44 secondsStr = '0' + seconds.toString();
d7d1db72 45 }
b322b8b4 46 return hoursStr + ':' + minutesStr + ':' + secondsStr.substring(0, 6);
9ac86a7e
JB
47 }
48
d7d1db72
JB
49 public static formatDurationSeconds(duration: number): string {
50 return Utils.formatDurationMilliSeconds(duration * 1000);
7dde0b73
JB
51 }
52
0f16a662 53 public static convertToDate(value: unknown): Date {
560bcf5b 54 // Check
6af9012e 55 if (!value) {
73d09045 56 return value as Date;
560bcf5b
JB
57 }
58 // Check Type
6af9012e 59 if (!(value instanceof Date)) {
73d09045 60 return new Date(value as string);
7dde0b73 61 }
6af9012e 62 return value;
7dde0b73
JB
63 }
64
0f16a662 65 public static convertToInt(value: unknown): number {
73d09045 66 let changedValue: number = value as number;
72766a82 67 if (!value) {
7dde0b73
JB
68 return 0;
69 }
72766a82 70 if (Number.isSafeInteger(value)) {
95926c9b 71 return value as number;
72766a82 72 }
7dde0b73 73 // Check
087a502d 74 if (Utils.isString(value)) {
7dde0b73 75 // Create Object
73d09045 76 changedValue = parseInt(value as string);
7dde0b73 77 }
df645d8f
JB
78 if (typeof value === 'number') {
79 changedValue = Math.trunc(value);
80 }
72766a82 81 return changedValue;
7dde0b73
JB
82 }
83
0f16a662 84 public static convertToFloat(value: unknown): number {
73d09045 85 let changedValue: number = value as number;
72766a82 86 if (!value) {
7dde0b73
JB
87 return 0;
88 }
89 // Check
087a502d 90 if (Utils.isString(value)) {
7dde0b73 91 // Create Object
73d09045 92 changedValue = parseFloat(value as string);
7dde0b73 93 }
72766a82 94 return changedValue;
7dde0b73
JB
95 }
96
0f16a662 97 public static convertToBoolean(value: unknown): boolean {
a6e68f34 98 let result = false;
a6e68f34
JB
99 if (value) {
100 // Check the type
101 if (typeof value === 'boolean') {
a6e68f34 102 result = value;
df645d8f
JB
103 } else if (
104 Utils.isString(value) &&
105 ((value as string).toLowerCase() === 'true' || value === '1')
106 ) {
107 result = true;
108 } else if (typeof value === 'number' && value === 1) {
109 result = true;
a6e68f34
JB
110 }
111 }
112 return result;
113 }
114
b5e5892d 115 public static getRandomFloat(max = Number.MAX_VALUE, min = 0, negative = false): number {
b3aa9f53 116 if (max < min || max < 0 || min < 0) {
b322b8b4
JB
117 throw new RangeError('Invalid interval');
118 }
fd00fa2e 119 const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff;
e7aeea18 120 const sign = negative && randomPositiveFloat < 0.5 ? -1 : 1;
fd00fa2e 121 return sign * (randomPositiveFloat * (max - min) + min);
560bcf5b
JB
122 }
123
b5e5892d 124 public static getRandomInteger(max = Number.MAX_SAFE_INTEGER, min = 0): number {
b3aa9f53 125 if (max < min || max < 0 || min < 0) {
a3868ec4
JB
126 throw new RangeError('Invalid interval');
127 }
fd00fa2e 128 max = Math.floor(max);
1f86b121 129 if (!Utils.isNullOrUndefined(min) && min !== 0) {
fd00fa2e 130 min = Math.ceil(min);
c37528f1 131 return Math.floor(Utils.secureRandom() * (max - min + 1)) + min;
7dde0b73 132 }
c37528f1 133 return Math.floor(Utils.secureRandom() * (max + 1));
560bcf5b
JB
134 }
135
0f16a662 136 public static roundTo(numberValue: number, scale: number): number {
ad3de6c4 137 const roundPower = Math.pow(10, scale);
035742f7 138 return Math.round(numberValue * roundPower) / roundPower;
560bcf5b
JB
139 }
140
0f16a662 141 public static truncTo(numberValue: number, scale: number): number {
6d3a11a0 142 const truncPower = Math.pow(10, scale);
035742f7 143 return Math.trunc(numberValue * truncPower) / truncPower;
6d3a11a0
JB
144 }
145
b5e5892d 146 public static getRandomFloatRounded(max = Number.MAX_VALUE, min = 0, scale = 2): number {
560bcf5b
JB
147 if (min) {
148 return Utils.roundTo(Utils.getRandomFloat(max, min), scale);
149 }
150 return Utils.roundTo(Utils.getRandomFloat(max), scale);
7dde0b73
JB
151 }
152
e7aeea18
JB
153 public static getRandomFloatFluctuatedRounded(
154 staticValue: number,
155 fluctuationPercent: number,
156 scale = 2
157 ): number {
9ccca265
JB
158 if (fluctuationPercent === 0) {
159 return Utils.roundTo(staticValue, scale);
160 }
97ef739c 161 const fluctuationRatio = fluctuationPercent / 100;
e7aeea18
JB
162 return Utils.getRandomFloatRounded(
163 staticValue * (1 + fluctuationRatio),
164 staticValue * (1 - fluctuationRatio),
165 scale
166 );
9ccca265
JB
167 }
168
0f16a662 169 public static cloneObject<T>(object: T): T {
e56aa9a4 170 return JSON.parse(JSON.stringify(object)) as T;
2e6f5966 171 }
facd8ebd 172
0f16a662 173 public static isIterable<T>(obj: T): boolean {
7558b3a6 174 return obj ? typeof obj[Symbol.iterator] === 'function' : false;
67e9cccf
JB
175 }
176
0f16a662 177 public static isString(value: unknown): boolean {
560bcf5b
JB
178 return typeof value === 'string';
179 }
180
e8191622 181 public static isEmptyString(value: unknown): boolean {
87f82a94 182 return Utils.isString(value) && (value as string).trim().length === 0;
e8191622
JB
183 }
184
0f16a662 185 public static isUndefined(value: unknown): boolean {
ead548f2
JB
186 return typeof value === 'undefined';
187 }
188
0f16a662 189 public static isNullOrUndefined(value: unknown): boolean {
7558b3a6
JB
190 // eslint-disable-next-line eqeqeq, no-eq-null
191 return value == null ? true : false;
facd8ebd 192 }
4a56deef 193
45999aab 194 public static isEmptyArray(object: unknown | unknown[]): boolean {
a2111e8d 195 if (!Array.isArray(object)) {
30e27491 196 return true;
fd1ee77c 197 }
45999aab 198 if (object.length > 0) {
4a56deef
JB
199 return false;
200 }
201 return true;
202 }
7abfea5f 203
94ec7e96 204 public static isEmptyObject(obj: object): boolean {
5e5ba121 205 if (obj?.constructor !== Object) {
d20581ee
JB
206 return false;
207 }
87f82a94
JB
208 // Iterates over the keys of an object, if
209 // any exist, return false.
210 for (const _ in obj) {
211 return false;
212 }
213 return true;
7abfea5f 214 }
7ec46a9a 215
e7aeea18
JB
216 public static insertAt = (str: string, subStr: string, pos: number): string =>
217 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
032d6efc
JB
218
219 /**
81797102
JB
220 * @param [retryNumber=0]
221 * @returns delay in milliseconds
032d6efc 222 */
0f16a662 223 public static exponentialDelay(retryNumber = 0): number {
032d6efc 224 const delay = Math.pow(2, retryNumber) * 100;
c37528f1 225 const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay
032d6efc
JB
226 return delay + randomSum;
227 }
32a1eb7a 228
6d9abcc2 229 public static async promiseWithTimeout<T>(
e7aeea18
JB
230 promise: Promise<T>,
231 timeoutMs: number,
232 timeoutError: Error,
233 timeoutCallback: () => void = () => {
234 /* This is intentional */
235 }
6d9abcc2
JB
236 ): Promise<T> {
237 // Create a timeout promise that rejects in timeout milliseconds
238 const timeoutPromise = new Promise<never>((_, reject) => {
239 setTimeout(() => {
ed0f8380 240 timeoutCallback();
6d9abcc2
JB
241 reject(timeoutError);
242 }, timeoutMs);
243 });
244
245 // Returns a race between timeout promise and the passed promise
246 return Promise.race<T>([promise, timeoutPromise]);
247 }
248
c37528f1 249 /**
0f16a662 250 * Generate a cryptographically secure random number in the [0,1[ range
c37528f1
JB
251 *
252 * @returns
253 */
0f16a662 254 public static secureRandom(): number {
c37528f1
JB
255 return crypto.randomBytes(4).readUInt32LE() / 0x100000000;
256 }
fe791818
JB
257
258 public static JSONStringifyWithMapSupport(
259 obj: Record<string, unknown> | Record<string, unknown>[],
260 space?: number
261 ): string {
262 return JSON.stringify(
263 obj,
264 (key, value: Record<string, unknown>) => {
265 if (value instanceof Map) {
266 return {
267 dataType: 'Map',
268 value: [...value],
269 };
270 }
271 return value;
272 },
273 space
274 );
275 }
5e3cb728
JB
276
277 /**
278 * Convert websocket error code to human readable string message
279 *
280 * @param code websocket error code
281 * @returns human readable string message
282 */
283 public static getWebSocketCloseEventStatusString(code: number): string {
284 if (code >= 0 && code <= 999) {
285 return '(Unused)';
286 } else if (code >= 1016) {
287 if (code <= 1999) {
288 return '(For WebSocket standard)';
289 } else if (code <= 2999) {
290 return '(For WebSocket extensions)';
291 } else if (code <= 3999) {
292 return '(For libraries and frameworks)';
293 } else if (code <= 4999) {
294 return '(For applications)';
295 }
296 }
297 if (!Utils.isUndefined(WebSocketCloseEventStatusString[code])) {
298 return WebSocketCloseEventStatusString[code] as string;
299 }
300 return '(Unknown)';
301 }
7dde0b73 302}