import msgHandler from './../../utils/iframe/messageHandler'; import { MiniAppError, MiniAppErrorType } from '../miniAppError'; abstract class BridgeFunction { abstract name: string; protected functionContext: any; public cbHandler?: BridgeCallbackHandler; protected multiCallback = false; protected mockable = true; async execute(functionContext: any, ...args: any[]) { this.functionContext = functionContext; if (!this.cbHandler && this.functionContext?.originId) { this.cbHandler = new BridgeCallbackHandlerIframe(this.functionContext); } try { await this.executeFunction(args); } catch (error) { this.cbHandler?.fail(error); } finally { if (!this.multiCallback) { this.cbHandler?.complete(); } } } protected abstract executeFunction(args: any[]): void; } export interface BridgeCallbackHandler { success(params: any): any; fail(error: Error): any; complete(): any; } class BridgeCallbackHandlerIframe implements BridgeCallbackHandler { protected functionContext: any; constructor(functionContext: any) { this.functionContext = functionContext; } success(params: any) { msgHandler( this.functionContext?.originId, this.functionContext?.successCB, params ); } fail(error: Error) { if (error instanceof MiniAppError) { msgHandler(this.functionContext?.originId, this.functionContext?.failCB, { errorCode: error.message, }); } else { msgHandler(this.functionContext?.originId, this.functionContext?.failCB, { errorCode: MiniAppErrorType.serverError, }); } } complete() { msgHandler( this.functionContext?.originId, this.functionContext?.completeCB ); } } export default BridgeFunction;