module.js 2.1 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2
const moduleName = '__MODULE_NAME__'
const moduleDefine = '__MODULE_DEFINE__'
fxy060608's avatar
fxy060608 已提交
3
var module = initModule(moduleDefine)
fxy060608's avatar
fxy060608 已提交
4
let callbackId = 1
fxy060608's avatar
fxy060608 已提交
5 6 7
const objectToString = Object.prototype.toString
const toTypeString = (value) => objectToString.call(value)
const isPlainObject = (val) => toTypeString(val) === '[object Object]'
fxy060608's avatar
fxy060608 已提交
8
const callbacks = {}
fxy060608's avatar
fxy060608 已提交
9 10
function normalizeArg(arg) {
  if (typeof arg === 'function') {
fxy060608's avatar
fxy060608 已提交
11 12
    const id = callbackId++
    callbacks[id] = arg
fxy060608's avatar
fxy060608 已提交
13
    return id
fxy060608's avatar
fxy060608 已提交
14 15 16 17 18 19 20
  } else if (isPlainObject(arg)) {
    Object.keys(arg).forEach((name) => {
      arg[name] = normalizeArg(arg[name])
    })
  }
  return arg
}
fxy060608's avatar
fxy060608 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
function isProxyInvokeCallbackResponse(res) {
  return !!res.name
}
function moduleGetter(proxy, module, method, defines) {
  const invokeCallback = ({ id, name, params, keepAlive }) => {
    const callback = callbacks[id]
    if (callback) {
      callback(...params)
      if (!keepAlive) {
        delete callbacks[id]
      }
    } else {
      console.error(`${module}.${method} ${name} is not found`)
    }
  }
fxy060608's avatar
fxy060608 已提交
36 37
  return (...args) => {
    const params = args.map((arg) => normalizeArg(arg))
fxy060608's avatar
fxy060608 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
    const invokeArgs = { module, method, params, async: !!defines.async }
    if (defines.async) {
      return new Promise((resolve, reject) => {
        proxy.invoke(invokeArgs, (res) => {
          if (isProxyInvokeCallbackResponse(res)) {
            invokeCallback(res)
          } else {
            if (res.errMsg) {
              reject(res.errMsg)
            } else {
              resolve(res.params)
            }
          }
        })
      })
    }
    return proxy.invoke(invokeArgs, invokeCallback)
fxy060608's avatar
fxy060608 已提交
55 56 57
  }
}
function initModule(moduleDefine) {
fxy060608's avatar
fxy060608 已提交
58
  let proxy
fxy060608's avatar
fxy060608 已提交
59 60 61 62 63
  const moduleProxy = {}
  for (const methodName in moduleDefine) {
    Object.defineProperty(moduleProxy, methodName, {
      enumerable: true,
      configurable: true,
fxy060608's avatar
fxy060608 已提交
64 65 66 67 68 69 70 71 72 73 74
      get: () => {
        if (!proxy) {
          proxy = uni.requireNativePlugin('proxy-module')
        }
        return moduleGetter(
          proxy,
          moduleName,
          methodName,
          moduleDefine[methodName]
        )
      },
fxy060608's avatar
fxy060608 已提交
75 76 77 78 79
    })
  }
}

export { module as default, normalizeArg }