Use arrow function for log messages prefixing
[e-mobility-charging-stations-simulator.git] / src / charging-station / WorkerBroadcastChannel.ts
index d1d430c3a0c39230aef0c00dd5de5660b25e42a0..37987437eee496f7684bc1e2049d55fc90a71084 100644 (file)
@@ -1,13 +1,60 @@
 import { BroadcastChannel } from 'worker_threads';
 
-import { BroadcastChannelRequest } from '../types/WorkerBroadcastChannel';
+import type { JsonType } from '../types/JsonType';
+import type {
+  BroadcastChannelRequest,
+  BroadcastChannelResponse,
+  MessageEvent,
+} from '../types/WorkerBroadcastChannel';
+import logger from '../utils/Logger';
+import Utils from '../utils/Utils';
 
-export default class WorkerBroadcastChannel extends BroadcastChannel {
-  constructor() {
+const moduleName = 'WorkerBroadcastChannel';
+
+export default abstract class WorkerBroadcastChannel extends BroadcastChannel {
+  protected constructor() {
     super('worker');
   }
 
   public sendRequest(request: BroadcastChannelRequest): void {
     this.postMessage(request);
   }
+
+  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}:`);
+  };
 }