refactor: strong type data sent to worker
authorJérôme Benoit <jerome.benoit@sap.com>
Mon, 20 Nov 2023 10:19:58 +0000 (11:19 +0100)
committerJérôme Benoit <jerome.benoit@sap.com>
Mon, 20 Nov 2023 10:19:58 +0000 (11:19 +0100)
Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
src/charging-station/ChargingStationWorker.ts

index 6201bf07e2b52fe7e6d1931412da74e89043717c..a0adf80595a46d1ef2b4ba7772d735a6640c7248 100644 (file)
@@ -9,29 +9,29 @@ import { ChargingStation } from './ChargingStation';
 import { BaseError } from '../exception';
 import type { ChargingStationWorkerData } from '../types';
 import { Configuration } from '../utils';
-import { type WorkerMessage, WorkerMessageEvents } from '../worker';
+import { type WorkerData, type WorkerMessage, WorkerMessageEvents } from '../worker';
 
 const moduleName = 'ChargingStationWorker';
 
 /**
  * Creates and starts a charging station instance
  *
- * @param data - workerData
+ * @param data - data sent to worker
  */
 const startChargingStation = (data?: ChargingStationWorkerData): void => {
   new ChargingStation(data!.index, data!.templateFile).start();
 };
 
-class ChargingStationWorker extends AsyncResource {
+class ChargingStationWorker<Data extends WorkerData> extends AsyncResource {
   constructor() {
     super(moduleName);
     // Add message listener to create and start charging station from the main thread
-    parentPort?.on('message', (message: WorkerMessage<ChargingStationWorkerData>) => {
+    parentPort?.on('message', (message: WorkerMessage<Data>) => {
       switch (message.event) {
         case WorkerMessageEvents.startWorkerElement:
           try {
             this.runInAsyncScope(
-              startChargingStation.bind(this) as (data?: ChargingStationWorkerData) => void,
+              startChargingStation.bind(this) as (data?: Data) => void,
               this,
               message.data,
             );
@@ -61,9 +61,11 @@ class ChargingStationWorker extends AsyncResource {
   }
 }
 
-export let chargingStationWorker: ChargingStationWorker | ThreadWorker<ChargingStationWorkerData>;
+export let chargingStationWorker:
+  | ChargingStationWorker<ChargingStationWorkerData>
+  | ThreadWorker<ChargingStationWorkerData>;
 if (Configuration.workerPoolInUse()) {
   chargingStationWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation);
 } else {
-  chargingStationWorker = new ChargingStationWorker();
+  chargingStationWorker = new ChargingStationWorker<ChargingStationWorkerData>();
 }