1 import { type AbstractUIService
, WorkerBroadcastChannel
} from
'./internal';
3 type BroadcastChannelResponse
,
4 type BroadcastChannelResponsePayload
,
9 import { Utils
, logger
} from
'../utils';
11 const moduleName
= 'UIServiceWorkerBroadcastChannel';
14 responsesExpected
: number;
15 responsesReceived
: number;
16 responses
: BroadcastChannelResponsePayload
[];
19 export class UIServiceWorkerBroadcastChannel
extends WorkerBroadcastChannel
{
20 private readonly uiService
: AbstractUIService
;
21 private readonly responses
: Map
<string, Responses
>;
23 constructor(uiService
: AbstractUIService
) {
25 this.uiService
= uiService
;
26 this.onmessage
= this.responseHandler
.bind(this) as (message
: MessageEvent
) => void;
27 this.onmessageerror
= this.messageErrorHandler
.bind(this) as (message
: MessageEvent
) => void;
28 this.responses
= new Map
<string, Responses
>();
31 private responseHandler(messageEvent
: MessageEvent
): void {
32 const validatedMessageEvent
= this.validateMessageEvent(messageEvent
);
33 if (validatedMessageEvent
=== false) {
36 if (this.isRequest(validatedMessageEvent
.data
) === true) {
39 const [uuid
, responsePayload
] = validatedMessageEvent
.data
as BroadcastChannelResponse
;
40 if (this.responses
.has(uuid
) === false) {
41 this.responses
.set(uuid
, {
42 responsesExpected
: this.uiService
.getBroadcastChannelExpectedResponses(uuid
),
44 responses
: [responsePayload
],
47 this.responses
.get(uuid
)?.responsesReceived
<= this.responses
.get(uuid
)?.responsesExpected
49 this.responses
.get(uuid
).responsesReceived
++;
50 this.responses
.get(uuid
)?.responses
.push(responsePayload
);
53 this.responses
.get(uuid
)?.responsesReceived
=== this.responses
.get(uuid
)?.responsesExpected
55 this.uiService
.sendResponse(uuid
, this.buildResponsePayload(uuid
));
56 this.responses
.delete(uuid
);
57 this.uiService
.deleteBroadcastChannelRequest(uuid
);
61 private buildResponsePayload(uuid
: string): ResponsePayload
{
62 const responsesStatus
=
65 ?.responses
.every(({ status }) => status === ResponseStatus
.SUCCESS
) === true
66 ? ResponseStatus
.SUCCESS
67 : ResponseStatus
.FAILURE
;
69 status: responsesStatus
,
70 hashIdsSucceeded
: this.responses
72 ?.responses
.filter(({ hashId
}) => !Utils
.isNullOrUndefined(hashId
))
73 .map(({ status, hashId
}) => {
74 if (status === ResponseStatus
.SUCCESS
) {
78 ...(responsesStatus
=== ResponseStatus
.FAILURE
&& {
79 hashIdsFailed
: this.responses
81 ?.responses
.filter(({ hashId
}) => !Utils
.isNullOrUndefined(hashId
))
82 .map(({ status, hashId
}) => {
83 if (status === ResponseStatus
.FAILURE
) {
88 ...(responsesStatus
=== ResponseStatus
.FAILURE
&& {
89 responsesFailed
: this.responses
91 ?.responses
.filter((response
) => !Utils
.isNullOrUndefined(response
))
93 if (response
.status === ResponseStatus
.FAILURE
) {
101 private messageErrorHandler(messageEvent
: MessageEvent
): void {
103 `${this.uiService.logPrefix(moduleName, 'messageErrorHandler')} Error at handling message:`,