module.ts 2.9 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6
declare const uni: {
  requireNativePlugin(name: string): { invoke: Function }
}

const moduleName = '__MODULE_NAME__'

fxy060608's avatar
fxy060608 已提交
7 8 9 10
const moduleDefine = '__MODULE_DEFINE__' as unknown as Record<
  string,
  ModuleMethodDefine
>
fxy060608's avatar
fxy060608 已提交
11

fxy060608's avatar
fxy060608 已提交
12 13 14 15 16
interface ModuleMethodDefine {
  async?: boolean
}

export default initModule(moduleDefine)
fxy060608's avatar
fxy060608 已提交
17 18 19 20 21 22 23 24 25

let callbackId = 1

const objectToString = Object.prototype.toString
const toTypeString = (value: unknown): string => objectToString.call(value)

const isPlainObject = (val: unknown): val is object =>
  toTypeString(val) === '[object Object]'

fxy060608's avatar
fxy060608 已提交
26
const callbacks: Record<string, Function> = {}
fxy060608's avatar
fxy060608 已提交
27 28
export function normalizeArg(arg: unknown) {
  if (typeof arg === 'function') {
fxy060608's avatar
fxy060608 已提交
29 30
    const id = callbackId++
    callbacks[id] = arg
fxy060608's avatar
fxy060608 已提交
31 32
    return {
      $$type: 'function',
fxy060608's avatar
fxy060608 已提交
33
      value: id,
fxy060608's avatar
fxy060608 已提交
34 35 36 37 38 39 40 41
    }
  } else if (isPlainObject(arg)) {
    Object.keys(arg).forEach((name) => {
      ;(arg as any)[name] = normalizeArg((arg as any)[name])
    })
  }
  return arg
}
fxy060608's avatar
fxy060608 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54
interface ProxyInvokeAsyncResponse {
  errMsg: string
  params: unknown
}
interface ProxyInvokeCallbackResponse {
  id: number
  name: string
  params: unknown[]
  keepAlive: boolean
}
type ProxyInvokeResponse =
  | ProxyInvokeAsyncResponse
  | ProxyInvokeCallbackResponse
fxy060608's avatar
fxy060608 已提交
55

fxy060608's avatar
fxy060608 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
function isProxyInvokeCallbackResponse(
  res: ProxyInvokeResponse
): res is ProxyInvokeCallbackResponse {
  return !!(res as ProxyInvokeCallbackResponse).name
}
function moduleGetter(
  proxy: any,
  module: string,
  method: string,
  defines: ModuleMethodDefine
) {
  const invokeCallback = ({
    id,
    name,
    params,
    keepAlive,
  }: ProxyInvokeCallbackResponse) => {
    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 已提交
83 84
  return (...args: unknown[]) => {
    const params = args.map((arg) => normalizeArg(arg))
fxy060608's avatar
fxy060608 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    const invokeArgs = { module, method, params, async: !!defines.async }
    if (defines.async) {
      return new Promise((resolve, reject) => {
        proxy.invoke(invokeArgs, (res: ProxyInvokeResponse) => {
          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 已提交
102 103 104
  }
}

fxy060608's avatar
fxy060608 已提交
105 106
function initModule(moduleDefine: Record<string, ModuleMethodDefine>) {
  let proxy: any
fxy060608's avatar
fxy060608 已提交
107 108 109 110 111
  const moduleProxy = {}
  for (const methodName in moduleDefine) {
    Object.defineProperty(moduleProxy, methodName, {
      enumerable: true,
      configurable: true,
fxy060608's avatar
fxy060608 已提交
112 113 114 115 116 117 118 119 120 121 122
      get: () => {
        if (!proxy) {
          proxy = uni.requireNativePlugin('proxy-module')
        }
        return moduleGetter(
          proxy,
          moduleName,
          methodName,
          moduleDefine[methodName]
        )
      },
fxy060608's avatar
fxy060608 已提交
123 124 125
    })
  }
}