All files / src/utils EngineEventTrigger.ts

93.33% Statements 14/15
100% Branches 8/8
80% Functions 4/5
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  7x 7x 2620x         73x 70x 70x   67x 47x   20x   3x     73x       3x 2x   1x        
/* eslint-disable @typescript-eslint/no-explicit-any */
import { CallbackErrorBehavior, LogCategory, LoggerFunction, LogLevel } from '../types/CommonTypes';
export abstract class EngineEventTrigger<T extends (...args: any[]) => any> {
    constructor(protected logger?: LoggerFunction) {}
 
    abstract trigger(...args: Parameters<T>): ReturnType<T>;
 
    protected createEventHandlerFn(callbackFn: T, errorBehavior: CallbackErrorBehavior): T {
        const wrapper: any = (...args: Parameters<T>) => {
            try {
                const result = callbackFn(...args);
                // If the callback returns a promise, we need to await it
                if (result instanceof Promise) {
                    return result.catch((error) => this.handleError(error, errorBehavior, callbackFn.name));
                }
                return result;
            } catch (error) {
                this.handleError(error, errorBehavior, callbackFn.name);
            }
        };
        return wrapper;
    }
 
    private handleError(error: unknown, errorBehavior: CallbackErrorBehavior, fnName: string) {
        if (errorBehavior === CallbackErrorBehavior.log) {
            this.logger?.(LogLevel.error, LogCategory.event, `Error in callback ${fnName}: ${error}`);
        } else {
            throw error;
        }
    }
}