import { isFunction } from '@tarojs/shared' type TCallback> = (res: T) => Promise | void interface IMethodParam> { name: string success?: TCallback fail?: TCallback complete?: TCallback } interface IMockPromise { resolve?: typeof Promise.resolve | TFunc reject?: typeof Promise.reject | TFunc } export class MethodHandler> { methodName: string protected __success?: TCallback protected __fail?: TCallback protected __complete?: TCallback protected isHandlerError = false constructor ({ name, success, fail, complete }: IMethodParam) { this.methodName = name this.__success = success this.__fail = fail this.__complete = complete this.isHandlerError = isFunction(this.__complete) || isFunction(this.__fail) } success> (res: Partial & Partial = {}, promise: IMockPromise = {}): Promise { if (!res.errMsg) { res.errMsg = `${this.methodName}:ok` } isFunction(this.__success) && this.__success(res as T) isFunction(this.__complete) && this.__complete(res) const { resolve = Promise.resolve.bind(Promise) } = promise return resolve(res as Required) } fail> (res: Partial & Partial = {}, promise: IMockPromise = {}): Promise { if (!res.errMsg) { res.errMsg = `${this.methodName}:fail` } else { res.errMsg = `${this.methodName}:fail ${res.errMsg}` } isFunction(this.__fail) && this.__fail(res) isFunction(this.__complete) && this.__complete(res) const { resolve = Promise.resolve.bind(Promise), reject = Promise.reject.bind(Promise) } = promise return this.isHandlerError ? resolve(res as Required) : reject(res) } } type TFunc = (...args: any[]) => any