chenyc
2025-12-09 545c24c6a711d71b65f3d4e8122fee3837fb1edc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { IBrokerEvent, IErrorNotification, IErrorResponse, IReceiver, IRequest, IWorkerDefinition } from '../interfaces';
import { TMessageReceiverWithParams, TMessageReceiverWithoutParams, TWorkerImplementation } from '../types';
import { renderMethodNotFoundError, renderMissingResponseError, renderUnexpectedResultError } from './error-renderers';
 
export const createMessageHandler = <WorkerDefinition extends IWorkerDefinition>(
    receiver: IReceiver,
    workerImplementation: TWorkerImplementation<WorkerDefinition>
) => {
    return async ({ data: { id, method, params } }: IBrokerEvent<WorkerDefinition>) => {
        const messageHandler = workerImplementation[method];
 
        try {
            if (messageHandler === undefined) {
                throw renderMethodNotFoundError(method);
            }
 
            const response =
                params === undefined
                    ? (messageHandler as TMessageReceiverWithoutParams<WorkerDefinition[typeof method]['response']>)()
                    : (
                          messageHandler as TMessageReceiverWithParams<
                              WorkerDefinition[typeof method]['params'],
                              WorkerDefinition[typeof method]['response']
                          >
                      )(params);
 
            if (response === undefined) {
                throw renderMissingResponseError(method);
            }
 
            const synchronousResponse = response instanceof Promise ? await response : response;
 
            if (id === null) {
                if (synchronousResponse.result !== undefined) {
                    throw renderUnexpectedResultError(method);
                }
            } else {
                if (synchronousResponse.result === undefined) {
                    throw renderUnexpectedResultError(method);
                }
 
                const { result, transferables = [] } = <IRequest['response']>synchronousResponse;
 
                receiver.postMessage({ id, result }, transferables);
            }
        } catch (err) {
            const { message, status = -32603 } = err;
 
            receiver.postMessage(<IErrorNotification | IErrorResponse>{ error: { code: status, message }, id });
        }
    };
};