| 1 | import type { BroadcastChannelResponse, MessageEvent } from '../types/WorkerBroadcastChannel'; |
| 2 | import logger from '../utils/Logger'; |
| 3 | import type AbstractUIService from './ui-server/ui-services/AbstractUIService'; |
| 4 | import WorkerBroadcastChannel from './WorkerBroadcastChannel'; |
| 5 | |
| 6 | const moduleName = 'UIServiceWorkerBroadcastChannel'; |
| 7 | |
| 8 | export default class UIServiceWorkerBroadcastChannel extends WorkerBroadcastChannel { |
| 9 | private uiService: AbstractUIService; |
| 10 | |
| 11 | constructor(uiService: AbstractUIService) { |
| 12 | super(); |
| 13 | this.uiService = uiService; |
| 14 | this.onmessage = this.responseHandler.bind(this) as (message: MessageEvent) => void; |
| 15 | this.onmessageerror = this.messageErrorHandler.bind(this) as (message: MessageEvent) => void; |
| 16 | } |
| 17 | |
| 18 | private responseHandler(messageEvent: MessageEvent): void { |
| 19 | if (this.isRequest(messageEvent.data)) { |
| 20 | return; |
| 21 | } |
| 22 | this.validateMessageEvent(messageEvent); |
| 23 | const [uuid, responsePayload] = messageEvent.data as BroadcastChannelResponse; |
| 24 | |
| 25 | this.uiService.sendResponse(uuid, responsePayload); |
| 26 | } |
| 27 | |
| 28 | private messageErrorHandler(messageEvent: MessageEvent): void { |
| 29 | logger.error( |
| 30 | `${this.uiService.logPrefix(moduleName, 'messageErrorHandler')} Error at handling message:`, |
| 31 | { messageEvent, messageEventData: messageEvent.data } |
| 32 | ); |
| 33 | } |
| 34 | } |