import Debug from 'debug' const debug = Debug('tiger-bridge') const RESPONSE_TIMEOUT: number = 100 /** * 默认关闭调试模式 */ window.__cef_debug__ = false /** * 用于调试的模拟接口 */ window.__cef_echo__ = (args) => { if (args && typeof args.callback === 'function') { // istanbul ignore next args.callback({ data: args, taskId: -1, // tslint:disable-next-line unwatch () {} }) } return args } /** * 根据环境选择执行的接口 */ window.__cef_invoker__ = (args) => { const invoker = window.__cef_debug__ ? window.__cef_echo__ : window.__cef_register__ if (!invoker || typeof invoker !== 'function') { throw { message: 'No Invoker!' } } return invoker(args) } /** * 调用Native接口,实现获取数据或订阅数据更新 * 接口调用失败时会throw error * * @param name 接口名称 * @param params 接口传参 * @param callback 接口数据回调 * @param watch 是否订阅数据更新,数据每次改变时调用callback * * @return unwatch 执行此方法取消订阅数据 */ export const register: TigerBridge.CefRegisterFunction = function ( name, params?, callback?, watch? ) { let taskId: any const unwatch: TigerBridge.UnWatchCallback = function () { if (taskId) { unregister(taskId) } // mark as called before callback run taskId = -1 } debug(' register > ', arguments) return new Promise((resolve, reject) => { window.__cef_invoker__({ name, params, watch: !!watch, callback (response) { debug(' response > ', response) if (response.error) { throw response.error } if (typeof callback === 'function') { callback({ ...response, unwatch }) } if (taskId === -1) { // unwatch() called taskId = response.taskId unwatch() } taskId = response.taskId resolve({ ...response, unwatch }) } }) // incase native not responseding window.setTimeout(() => { resolve({ taskId: -1, unwatch }) }, RESPONSE_TIMEOUT) }) } /** * 取消订阅数据接口, 一般不需要手动调用,由订阅时返回的 UnWatchCallback 函数调用 * * @param taskId 添加订阅时native返回的taskId */ export const unregister = function (taskId: any): void { if (!taskId) return debug('unregister > #%s', taskId) window.__cef_invoker__({ name: 'unwatch', params: { taskId }, watch: false }) } /** * 设置debug模式,在该模式下,调用接口会直接返回调用参数, * 用于调试查看调用方式是否正确 * * @param debug 是否为调试模式 */ export const setDebug = function (debug: boolean): void { window.__cef_debug__ = debug }