X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2FWorkerBroadcastChannel.ts;h=652a27e1831e7fb7f9815745511de6c68a7fe54f;hb=262c47b2dbe7ad59fa523e77668dd0b994214cb2;hp=563da4588b564210ab65992ee084e3a7430231fe;hpb=32de5a575189d226213641f5ee36004f8454cb50;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/WorkerBroadcastChannel.ts b/src/charging-station/WorkerBroadcastChannel.ts index 563da458..652a27e1 100644 --- a/src/charging-station/WorkerBroadcastChannel.ts +++ b/src/charging-station/WorkerBroadcastChannel.ts @@ -1,7 +1,56 @@ import { BroadcastChannel } from 'worker_threads'; -export default class WorkerBroadcastChannel extends BroadcastChannel { - constructor() { +import type { JsonType } from '../types/JsonType'; +import type { + BroadcastChannelRequest, + BroadcastChannelResponse, + MessageEvent, +} from '../types/WorkerBroadcastChannel'; +import logger from '../utils/Logger'; +import Utils from '../utils/Utils'; + +const moduleName = 'WorkerBroadcastChannel'; + +export default abstract class WorkerBroadcastChannel extends BroadcastChannel { + protected constructor() { super('worker'); } + + public sendRequest(request: BroadcastChannelRequest): void { + this.postMessage(request); + } + + protected sendResponse(response: BroadcastChannelResponse): void { + this.postMessage(response); + } + + protected isRequest(message: JsonType[]): boolean { + return Array.isArray(message) === true && message.length === 3; + } + + protected isResponse(message: JsonType[]): boolean { + return Array.isArray(message) === true && message.length === 2; + } + + protected validateMessageEvent(messageEvent: MessageEvent): MessageEvent | false { + if (Array.isArray(messageEvent.data) === false) { + logger.error( + this.logPrefix(moduleName, 'validateMessageEvent') + + ' Worker broadcast channel protocol message event data is not an array' + ); + return false; + } + if (Utils.validateUUID(messageEvent.data[0]) === false) { + logger.error( + this.logPrefix(moduleName, 'validateMessageEvent') + + ' Worker broadcast channel protocol message event data UUID field is invalid' + ); + return false; + } + return messageEvent; + } + + private logPrefix(modName: string, methodName: string): string { + return Utils.logPrefix(` Worker Broadcast Channel | ${modName}.${methodName}:`); + } }