66c4c0de6aa266580a9be0b77250dd62e2acabe9
[e-mobility-charging-stations-simulator.git] / src / charging-station / broadcast-channel / WorkerBroadcastChannel.ts
1 import { BroadcastChannel } from 'node:worker_threads'
2
3 import type {
4 BroadcastChannelRequest,
5 BroadcastChannelResponse,
6 JsonType,
7 MessageEvent,
8 } from '../../types/index.js'
9
10 import { logger, logPrefix, validateUUID } from '../../utils/index.js'
11
12 const moduleName = 'WorkerBroadcastChannel'
13
14 export abstract class WorkerBroadcastChannel extends BroadcastChannel {
15 private readonly logPrefix = (modName: string, methodName: string): string => {
16 return logPrefix(` Worker Broadcast Channel | ${modName}.${methodName}:`)
17 }
18
19 protected constructor () {
20 super('worker')
21 }
22
23 protected isRequest (message: JsonType[]): boolean {
24 return Array.isArray(message) && message.length === 3
25 }
26
27 protected isResponse (message: JsonType[]): boolean {
28 return Array.isArray(message) && message.length === 2
29 }
30
31 protected sendResponse (response: BroadcastChannelResponse): void {
32 this.postMessage(response)
33 }
34
35 protected validateMessageEvent (messageEvent: MessageEvent): false | MessageEvent {
36 if (!Array.isArray(messageEvent.data)) {
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 (!validateUUID(messageEvent.data[0])) {
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 public sendRequest (request: BroadcastChannelRequest): void {
58 this.postMessage(request)
59 }
60 }