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