dd14d781ce61b207d2faf9a0cd42bff9d47933b3
[e-mobility-charging-stations-simulator.git] / src / charging-station / WorkerBroadcastChannel.ts
1 import { BroadcastChannel } from 'worker_threads';
2
3 import type {
4 BroadcastChannelRequest,
5 BroadcastChannelResponse,
6 JsonType,
7 MessageEvent,
8 } from '../types';
9 import { logger } from '../utils/Logger';
10 import { Utils } from '../utils/Utils';
11
12 const moduleName = 'WorkerBroadcastChannel';
13
14 export abstract class WorkerBroadcastChannel extends BroadcastChannel {
15 protected constructor() {
16 super('worker');
17 }
18
19 public sendRequest(request: BroadcastChannelRequest): void {
20 this.postMessage(request);
21 }
22
23 protected sendResponse(response: BroadcastChannelResponse): void {
24 this.postMessage(response);
25 }
26
27 protected isRequest(message: JsonType[]): boolean {
28 return Array.isArray(message) === true && message.length === 3;
29 }
30
31 protected isResponse(message: JsonType[]): boolean {
32 return Array.isArray(message) === true && message.length === 2;
33 }
34
35 protected validateMessageEvent(messageEvent: MessageEvent): MessageEvent | false {
36 if (Array.isArray(messageEvent.data) === false) {
37 logger.error(
38 `${this.logPrefix(
39 moduleName,
40 'validateMessageEvent'
41 )} Worker broadcast channel protocol message event data is not an array`
42 );
43 return false;
44 }
45 if (Utils.validateUUID(messageEvent.data[0]) === false) {
46 logger.error(
47 `${this.logPrefix(
48 moduleName,
49 'validateMessageEvent'
50 )} Worker broadcast channel protocol message event data UUID field is invalid`
51 );
52 return false;
53 }
54 return messageEvent;
55 }
56
57 private logPrefix = (modName: string, methodName: string): string => {
58 return Utils.logPrefix(` Worker Broadcast Channel | ${modName}.${methodName}:`);
59 };
60 }