Interface.js 1.94 KB
import { JsInterfaces } from '@/api/NativeApis'


class Interface {
    constructor(interfaces) {
        this.listeners = {}
        this.__init(interfaces)
    }

    on(methodName, callback) {
        this.listeners[methodName] = callback
    }

    call(nativeMethod, data, isback) {
        if (isback) {
            return this.__callNativeApiBack(nativeMethod, data)
        }
        return this.__callNativeApiBack(nativeMethod, data)
    }




    __init(interfaces = []) {
        interfaces.forEach(methodName => {
            this[methodName] = (data) => {
                this.listeners[methodName](data ? JSON.parse(data) : data)
            }
        });
    }

    __callNativeApiNotBack(nativeMethod, data) {
        try {
            if (that.__callNativeApi(nativeMethod, { data })) {
                return Promise.reject(`无效调用:[${nativeMethod}]`)
            }
            return Promise.resolve()
        } catch (e) {
            return Promise.reject(`接口调用异常:[${nativeMethod}]`)
        }
    }

    __callNativeApiBack(nativeMethod, data) {
        const that = this
        const jsMethodName = `js${Date.now()}`
        return new Promise((resolve, reject) => {
            try {
                that[jsMethodName] = (data) => {
                    resolve(data ? JSON.parse(data) : data)
                    delete that[jsMethodName]
                }
                if (that.__callNativeApi(nativeMethod, { data, jsMethodName })) {
                    return reject(`无效调用:[${nativeMethod}]`)
                }
            } catch (e) {
                return Promise.reject(`接口调用异常:[${nativeMethod}]`)
            }
        })
    }

    __callNativeApi(nativeMethod, data) {
        if (window.$NativeApi && window.$NativeApi[nativeMethod]) {
            window.$NativeApi[nativeMethod](JSON.stringify(data))
        } else {
            return true
        }
    }
}

window.$api = new Interface(JsInterfaces)