README.md: update to reflect response payload format change on
[e-mobility-charging-stations-simulator.git] / src / charging-station / WorkerBroadcastChannel.ts
index 563da4588b564210ab65992ee084e3a7430231fe..2fa082dddfd844fb872068f91a03e7c957f60ccb 100644 (file)
@@ -1,7 +1,38 @@
 import { BroadcastChannel } from 'worker_threads';
 
-export default class WorkerBroadcastChannel extends BroadcastChannel {
-  constructor() {
+import BaseError from '../exception/BaseError';
+import type { JsonType } from '../types/JsonType';
+import type {
+  BroadcastChannelRequest,
+  BroadcastChannelResponse,
+  MessageEvent,
+} from '../types/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) && message.length === 3;
+  }
+
+  protected isResponse(message: JsonType[]): boolean {
+    return Array.isArray(message) && message.length === 2;
+  }
+
+  protected validateMessageEvent(messageEvent: MessageEvent): MessageEvent {
+    if (Array.isArray(messageEvent.data) === false) {
+      throw new BaseError('Worker broadcast channel protocol message event data is not an array');
+    }
+    return messageEvent;
+  }
 }