feat: strict message event checking in worker set mode
authorJérôme Benoit <jerome.benoit@sap.com>
Thu, 20 Jul 2023 19:30:02 +0000 (21:30 +0200)
committerJérôme Benoit <jerome.benoit@sap.com>
Thu, 20 Jul 2023 19:30:02 +0000 (21:30 +0200)
Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
src/charging-station/Bootstrap.ts
src/charging-station/ChargingStationWorker.ts

index 4bfea3213d822244acc028d75049f8a711cfe647..79d9a00865c4a0d3ae9368f7c21a141e39ac4fd3 100644 (file)
@@ -292,7 +292,9 @@ export class Bootstrap extends EventEmitter {
           break;
         default:
           throw new BaseError(
-            `Unknown event type: '${msg.event}' for data: ${JSON.stringify(msg.data, null, 2)}`,
+            `Unknown charging station worker event: '${
+              msg.event
+            }' received with data: ${JSON.stringify(msg.data, null, 2)}`,
           );
       }
     } catch (error) {
index b20bf3e8ba2851e8bd5be467b03cb044ef73a132..db7ae2cb4462ff79f50359dc989b50536a73edd6 100644 (file)
@@ -26,25 +26,35 @@ class ChargingStationWorker extends AsyncResource {
     super(moduleName);
     // Add message listener to create and start charging station from the main thread
     parentPort?.on('message', (message: WorkerMessage<ChargingStationWorkerData>) => {
-      if (message.event === WorkerMessageEvents.startWorkerElement) {
-        try {
-          this.runInAsyncScope(
-            startChargingStation.bind(this) as (data?: ChargingStationWorkerData) => void,
-            this,
-            message.data,
+      switch (message.event) {
+        case WorkerMessageEvents.startWorkerElement:
+          try {
+            this.runInAsyncScope(
+              startChargingStation.bind(this) as (data?: ChargingStationWorkerData) => void,
+              this,
+              message.data,
+            );
+            parentPort?.postMessage({
+              event: WorkerMessageEvents.startedWorkerElement,
+            });
+          } catch (error) {
+            parentPort?.postMessage({
+              event: WorkerMessageEvents.startWorkerElementError,
+              data: {
+                message: (error as Error).message,
+                stack: (error as Error).stack,
+              },
+            });
+          }
+          break;
+        default:
+          throw new Error(
+            `Unknown worker event: '${message.event}' received with data: '${JSON.stringify(
+              message.data,
+              null,
+              2,
+            )}'`,
           );
-          parentPort?.postMessage({
-            event: WorkerMessageEvents.startedWorkerElement,
-          });
-        } catch (error) {
-          parentPort?.postMessage({
-            event: WorkerMessageEvents.startWorkerElementError,
-            data: {
-              message: (error as Error).message,
-              stack: (error as Error).stack,
-            },
-          });
-        }
       }
     });
   }