refactor: factor out performance records JSON file path building
[e-mobility-charging-stations-simulator.git] / src / charging-station / WorkerBroadcastChannel.ts
index 2099d695ab683e75d315151e02c9c5914eb6cedd..f3c168bdc8f1057611d1b8768d6d1dde0364c627 100644 (file)
@@ -1,9 +1,17 @@
-import { BroadcastChannel } from 'worker_threads';
+import { BroadcastChannel } from 'node:worker_threads';
 
-import { BroadcastChannelRequest, BroadcastChannelResponse } from '../types/WorkerBroadcastChannel';
+import type {
+  BroadcastChannelRequest,
+  BroadcastChannelResponse,
+  JsonType,
+  MessageEvent,
+} from '../types';
+import { Utils, logger } from '../utils';
 
-export default class WorkerBroadcastChannel extends BroadcastChannel {
-  constructor() {
+const moduleName = 'WorkerBroadcastChannel';
+
+export abstract class WorkerBroadcastChannel extends BroadcastChannel {
+  protected constructor() {
     super('worker');
   }
 
@@ -11,7 +19,41 @@ export default class WorkerBroadcastChannel extends BroadcastChannel {
     this.postMessage(request);
   }
 
-  public sendResponse(response: BroadcastChannelResponse): void {
+  protected sendResponse(response: BroadcastChannelResponse): void {
     this.postMessage(response);
   }
+
+  protected isRequest(message: JsonType[]): boolean {
+    return Array.isArray(message) === true && message.length === 3;
+  }
+
+  protected isResponse(message: JsonType[]): boolean {
+    return Array.isArray(message) === true && message.length === 2;
+  }
+
+  protected validateMessageEvent(messageEvent: MessageEvent): MessageEvent | false {
+    if (Array.isArray(messageEvent.data) === false) {
+      logger.error(
+        `${this.logPrefix(
+          moduleName,
+          'validateMessageEvent'
+        )} Worker broadcast channel protocol message event data is not an array`
+      );
+      return false;
+    }
+    if (Utils.validateUUID(messageEvent.data[0]) === false) {
+      logger.error(
+        `${this.logPrefix(
+          moduleName,
+          'validateMessageEvent'
+        )} Worker broadcast channel protocol message event data UUID field is invalid`
+      );
+      return false;
+    }
+    return messageEvent;
+  }
+
+  private logPrefix = (modName: string, methodName: string): string => {
+    return Utils.logPrefix(` Worker Broadcast Channel | ${modName}.${methodName}:`);
+  };
 }