Commit | Line | Data |
---|---|---|
32de5a57 LM |
1 | import { BroadcastChannel } from 'worker_threads'; |
2 | ||
852a4c5f | 3 | import BaseError from '../exception/BaseError'; |
18057587 | 4 | import type { JsonType } from '../types/JsonType'; |
6c1761d4 | 5 | import type { |
852a4c5f JB |
6 | BroadcastChannelRequest, |
7 | BroadcastChannelResponse, | |
8 | MessageEvent, | |
9 | } from '../types/WorkerBroadcastChannel'; | |
4e3ff94d | 10 | |
6c8f5d90 JB |
11 | export default abstract class WorkerBroadcastChannel extends BroadcastChannel { |
12 | protected constructor() { | |
32de5a57 LM |
13 | super('worker'); |
14 | } | |
4e3ff94d JB |
15 | |
16 | public sendRequest(request: BroadcastChannelRequest): void { | |
17 | this.postMessage(request); | |
18 | } | |
02a6943a | 19 | |
6c8f5d90 | 20 | protected sendResponse(response: BroadcastChannelResponse): void { |
02a6943a JB |
21 | this.postMessage(response); |
22 | } | |
6c8f5d90 | 23 | |
18057587 | 24 | protected isRequest(message: JsonType[]): boolean { |
6c8f5d90 JB |
25 | return Array.isArray(message) && message.length === 3; |
26 | } | |
27 | ||
18057587 | 28 | protected isResponse(message: JsonType[]): boolean { |
6c8f5d90 JB |
29 | return Array.isArray(message) && message.length === 2; |
30 | } | |
852a4c5f JB |
31 | |
32 | protected validateMessageEvent(messageEvent: MessageEvent): void { | |
33 | if (Array.isArray(messageEvent.data) === false) { | |
34 | throw new BaseError('Worker broadcast channel protocol message event data is not an array'); | |
35 | } | |
36 | } | |
32de5a57 | 37 | } |