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