README.md: document added UI protocol features
[e-mobility-charging-stations-simulator.git] / src / charging-station / WorkerBroadcastChannel.ts
index d1d430c3a0c39230aef0c00dd5de5660b25e42a0..b19bf946dc633db77e5c690e75dd4b921de6868a 100644 (file)
@@ -1,13 +1,37 @@
 import { BroadcastChannel } from 'worker_threads';
 
-import { BroadcastChannelRequest } from '../types/WorkerBroadcastChannel';
+import BaseError from '../exception/BaseError';
+import type { JsonType } from '../types/JsonType';
+import type {
+  BroadcastChannelRequest,
+  BroadcastChannelResponse,
+  MessageEvent,
+} from '../types/WorkerBroadcastChannel';
 
-export default class WorkerBroadcastChannel extends BroadcastChannel {
-  constructor() {
+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) && message.length === 3;
+  }
+
+  protected isResponse(message: JsonType[]): boolean {
+    return Array.isArray(message) && message.length === 2;
+  }
+
+  protected validateMessageEvent(messageEvent: MessageEvent): void {
+    if (Array.isArray(messageEvent.data) === false) {
+      throw new BaseError('Worker broadcast channel protocol message event data is not an array');
+    }
+  }
 }