X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2FWorkerBroadcastChannel.ts;h=96fe7c17df01c76471c384f03af3605175372013;hb=f962bb40411fa6ed83632c2aa23c4de5f2586716;hp=2099d695ab683e75d315151e02c9c5914eb6cedd;hpb=02a6943a30a9a6c93e5dcbdb79aa8d9746ae368e;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/WorkerBroadcastChannel.ts b/src/charging-station/WorkerBroadcastChannel.ts index 2099d695..96fe7c17 100644 --- a/src/charging-station/WorkerBroadcastChannel.ts +++ b/src/charging-station/WorkerBroadcastChannel.ts @@ -1,9 +1,20 @@ import { BroadcastChannel } from 'worker_threads'; -import { BroadcastChannelRequest, BroadcastChannelResponse } from '../types/WorkerBroadcastChannel'; +import * as uuid from 'uuid'; -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'); } @@ -11,7 +22,37 @@ export default class WorkerBroadcastChannel extends BroadcastChannel { this.postMessage(request); } - public sendResponse(response: BroadcastChannelResponse): void { + protected sendResponse(response: BroadcastChannelResponse): void { this.postMessage(response); } + + protected isRequest(message: JsonType[]): boolean { + return Array.isArray(message) && message.length === 3; + } + + protected isResponse(message: JsonType[]): boolean { + return Array.isArray(message) && 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 (uuid.validate(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}:`); + } }