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