ea89dc3dbf65f093f0a0bbfacdfdb32aab3c5f62
[e-mobility-charging-stations-simulator.git] / src / charging-station / WorkerBroadcastChannel.ts
1 import { BroadcastChannel } from 'worker_threads';
2
3 import BaseError from '../exception/BaseError';
4 import {
5 BroadcastChannelRequest,
6 BroadcastChannelResponse,
7 MessageEvent,
8 } from '../types/WorkerBroadcastChannel';
9
10 export default abstract class WorkerBroadcastChannel extends BroadcastChannel {
11 protected constructor() {
12 super('worker');
13 }
14
15 public sendRequest(request: BroadcastChannelRequest): void {
16 this.postMessage(request);
17 }
18
19 protected sendResponse(response: BroadcastChannelResponse): void {
20 this.postMessage(response);
21 }
22
23 protected isRequest(message: any): boolean {
24 return Array.isArray(message) && message.length === 3;
25 }
26
27 protected isResponse(message: any): boolean {
28 return Array.isArray(message) && message.length === 2;
29 }
30
31 protected validateMessageEvent(messageEvent: MessageEvent): void {
32 if (Array.isArray(messageEvent.data) === false) {
33 throw new BaseError('Worker broadcast channel protocol message event data is not an array');
34 }
35 }
36 }