Comment some dubious OCPPError usage
[e-mobility-charging-stations-simulator.git] / src / charging-station / WorkerBroadcastChannel.ts
index 12a877c12add623365c0c8c6c6068c62841000d2..96fe7c17df01c76471c384f03af3605175372013 100644 (file)
@@ -1,6 +1,17 @@
 import { BroadcastChannel } from 'worker_threads';
 
-import { BroadcastChannelRequest, BroadcastChannelResponse } from '../types/WorkerBroadcastChannel';
+import * as uuid from 'uuid';
+
+import type { JsonType } from '../types/JsonType';
+import type {
+  BroadcastChannelRequest,
+  BroadcastChannelResponse,
+  MessageEvent,
+} from '../types/WorkerBroadcastChannel';
+import logger from '../utils/Logger';
+import Utils from '../utils/Utils';
+
+const moduleName = 'WorkerBroadcastChannel';
 
 export default abstract class WorkerBroadcastChannel extends BroadcastChannel {
   protected constructor() {
@@ -15,11 +26,33 @@ export default abstract class WorkerBroadcastChannel extends BroadcastChannel {
     this.postMessage(response);
   }
 
-  protected isRequest(message: any): boolean {
+  protected isRequest(message: JsonType[]): boolean {
     return Array.isArray(message) && message.length === 3;
   }
 
-  protected isResponse(message: any): boolean {
+  protected isResponse(message: JsonType[]): boolean {
     return Array.isArray(message) && 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 (uuid.validate(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}:`);
+  }
 }