Strong type protocols payloads
[e-mobility-charging-stations-simulator.git] / src / utils / Utils.ts
index b394713392d2b6c8b90887f16459bd5f36aefc71..fb8aebfe0dae72f3415c3ab9f7c9d3cb08e68471 100644 (file)
@@ -14,7 +14,7 @@ export default class Utils {
   }
 
   public static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> {
-    return new Promise((resolve) => setTimeout(resolve, milliSeconds));
+    return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds));
   }
 
   public static formatDurationMilliSeconds(duration: number): string {
@@ -22,9 +22,9 @@ export default class Utils {
     const hours = Math.floor(duration / (3600 * 1000));
     const minutes = Math.floor((duration / 1000 - (hours * 3600)) / 60);
     const seconds = duration / 1000 - (hours * 3600) - (minutes * 60);
-    let hoursStr: string = hours.toString();
-    let minutesStr: string = minutes.toString();
-    let secondsStr: string = seconds.toString();
+    let hoursStr = hours.toString();
+    let minutesStr = minutes.toString();
+    let secondsStr = seconds.toString();
 
     if (hours < 10) {
       hoursStr = '0' + hours.toString();
@@ -104,13 +104,19 @@ export default class Utils {
       throw new RangeError('Invalid interval');
     }
     const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff;
-    const sign = (negative && randomPositiveFloat < 0.5) ? 1 : -1;
+    const sign = (negative && randomPositiveFloat < 0.5) ? -1 : 1;
     return sign * (randomPositiveFloat * (max - min) + min);
   }
 
-  public static getRandomInt(max: number, min = 0): number {
+  public static getRandomInteger(max: number, min = 0): number {
+    if (max < 0) {
+      throw new RangeError('Invalid interval');
+    }
     max = Math.floor(max);
     if (min) {
+      if (max < min || min < 0) {
+        throw new RangeError('Invalid interval');
+      }
       min = Math.ceil(min);
       return Math.floor(Utils.secureRandom() * (max - min + 1)) + min;
     }
@@ -229,6 +235,24 @@ export default class Utils {
     return Configuration.getWorkerProcess() === WorkerProcessType.DYNAMIC_POOL;
   }
 
+  public static async promiseWithTimeout<T>(
+      promise: Promise<T>,
+      timeoutMs: number,
+      timeoutError: Error,
+      timeoutCallback: () => void = () => { /* This is intentional */ }
+  ): Promise<T> {
+    // Create a timeout promise that rejects in timeout milliseconds
+    const timeoutPromise = new Promise<never>((_, reject) => {
+      setTimeout(() => {
+        timeoutCallback();
+        reject(timeoutError);
+      }, timeoutMs);
+    });
+
+    // Returns a race between timeout promise and the passed promise
+    return Promise.race<T>([promise, timeoutPromise]);
+  }
+
   /**
    * Generate a cryptographically secure random number in the [0,1[ range
    *