api.js 8.3 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10
import {
  isFn,
  isPlainObject
} from 'uni-shared'

import {
  tryCatch,
  tryCatchFramework
} from './catch'

fxy060608's avatar
fxy060608 已提交
11 12 13 14 15 16
import {
  isTaskApi,
  isSyncApi,
  isCallbackApi
} from './promise'

fxy060608's avatar
fxy060608 已提交
17
import protocol from 'uni-api-protocol'
fxy060608's avatar
fxy060608 已提交
18 19 20 21 22

import validateParam from './params'

function invokeCallbackHandlerFail (err, apiName, callbackId) {
  const errMsg = `${apiName}:fail ${err}`
fxy060608's avatar
fxy060608 已提交
23 24 25
  if (process.env.NODE_ENV !== 'production') {
    console.error(errMsg)
  }
fxy060608's avatar
fxy060608 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
  if (callbackId === -1) {
    throw new Error(errMsg)
  }
  if (typeof callbackId === 'number') {
    invokeCallbackHandler(callbackId, {
      errMsg
    })
  }
  return false
}

const callbackApiParamTypes = [{
  name: 'callback',
  type: Function,
  required: true
}]

fxy060608's avatar
fxy060608 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
// 目前已用到的仅这三个
// 完整的可能包含:
// beforeValidate,
// beforeSuccess,
// afterSuccess,
// beforeFail,
// afterFail,
// beforeCancel,
// afterCancel,
// beforeAll,
// afterAll
const IGNORE_KEYS = [
  'beforeValidate',
  'beforeAll',
  'beforeSuccess'
]

fxy060608's avatar
fxy060608 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
function validateParams (apiName, paramsData, callbackId) {
  let paramTypes = protocol[apiName]
  if (!paramTypes && isCallbackApi(apiName)) {
    paramTypes = callbackApiParamTypes
  }
  if (paramTypes) {
    if (Array.isArray(paramTypes) && Array.isArray(paramsData)) {
      const paramTypeObj = Object.create(null)
      const paramsDataObj = Object.create(null)
      const paramsDataLength = paramsData.length
      paramTypes.forEach((paramType, index) => {
        paramTypeObj[paramType.name] = paramType
        if (paramsDataLength > index) {
          paramsDataObj[paramType.name] = paramsData[index]
        }
      })
      paramTypes = paramTypeObj
      paramsData = paramsDataObj
    }

    if (isFn(paramTypes.beforeValidate)) {
      const err = paramTypes.beforeValidate(paramsData)
      if (err) {
        return invokeCallbackHandlerFail(err, apiName, callbackId)
      }
    }

    const keys = Object.keys(paramTypes)
    for (let i = 0; i < keys.length; i++) {
fxy060608's avatar
fxy060608 已提交
89
      if (IGNORE_KEYS.indexOf(keys[i]) !== -1) {
fxy060608's avatar
fxy060608 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
        continue
      }
      const err = validateParam(keys[i], paramTypes, paramsData)
      if (err) {
        return invokeCallbackHandlerFail(err, apiName, callbackId)
      }
    }
  }
  return true
}

let invokeCallbackId = 1

const invokeCallbacks = {}

function createKeepAliveApiCallback (apiName, callback) {
  const callbackId = invokeCallbackId++
  const invokeCallbackName = 'api.' + apiName + '.' + callbackId

  invokeCallbacks[callbackId] = {
    name: invokeCallbackName,
    keepAlive: true,
Q
qiang 已提交
112
    callback
fxy060608's avatar
fxy060608 已提交
113 114 115 116
  }
  return callbackId
}

Q
qiang 已提交
117 118 119 120 121 122 123 124 125 126 127
function getKeepAliveApiCallback (apiName, callback) {
  for (const key in invokeCallbacks) {
    const item = invokeCallbacks[key]
    if (item.name.startsWith('api.' + apiName.replace(/^off/, 'on')) && item.callback === callback) {
      delete invokeCallbacks[key]
      return Number(key)
    }
  }
  return 'fail'
}

fxy060608's avatar
fxy060608 已提交
128 129 130 131 132 133 134 135 136
function createApiCallback (apiName, params = {}, extras = {}) {
  if (!isPlainObject(params)) {
    return {
      params
    }
  }
  params = Object.assign({}, params)

  const apiCallbacks = {}
fxy060608's avatar
fxy060608 已提交
137
  for (const name in params) {
fxy060608's avatar
fxy060608 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    const param = params[name]
    if (isFn(param)) {
      apiCallbacks[name] = tryCatch(param)
      delete params[name]
    }
  }

  const {
    success,
    fail,
    cancel,
    complete
  } = apiCallbacks

  const hasSuccess = isFn(success)
  const hasFail = isFn(fail)
  const hasCancel = isFn(cancel)
  const hasComplete = isFn(complete)

  if (!hasSuccess && !hasFail && !hasCancel && !hasComplete) { // 无回调
    return {
      params
    }
  }

  const wrapperCallbacks = {}
fxy060608's avatar
fxy060608 已提交
164
  for (const name in extras) {
fxy060608's avatar
fxy060608 已提交
165 166 167 168 169 170 171 172 173 174 175 176 177
    const extra = extras[name]
    if (isFn(extra)) {
      wrapperCallbacks[name] = tryCatchFramework(extra)
    }
  }

  const {
    beforeSuccess,
    afterSuccess,
    beforeFail,
    afterFail,
    beforeCancel,
    afterCancel,
fxy060608's avatar
fxy060608 已提交
178
    beforeAll,
fxy060608's avatar
fxy060608 已提交
179 180 181 182 183 184 185 186 187
    afterAll
  } = wrapperCallbacks

  const callbackId = invokeCallbackId++
  const invokeCallbackName = 'api.' + apiName + '.' + callbackId

  const invokeCallback = function (res) {
    res.errMsg = res.errMsg || apiName + ':ok'

fxy060608's avatar
fxy060608 已提交
188 189 190 191 192
    // 部分 api 可能返回的 errMsg 的 api 名称部分不一致,格式化为正确的
    if (res.errMsg.indexOf(':ok') !== -1) {
      res.errMsg = apiName + ':ok'
    } else if (res.errMsg.indexOf(':cancel') !== -1) {
      res.errMsg = apiName + ':cancel'
fxy060608's avatar
fxy060608 已提交
193 194
    } else if (res.errMsg.indexOf(':fail') !== -1) {
      let errDetail = ''
fxy060608's avatar
fxy060608 已提交
195
      const spaceIndex = res.errMsg.indexOf(' ')
fxy060608's avatar
fxy060608 已提交
196 197
      if (spaceIndex > -1) {
        errDetail = res.errMsg.substr(spaceIndex)
雪洛's avatar
雪洛 已提交
198 199
      }
      res.errMsg = apiName + ':fail' + errDetail
fxy060608's avatar
fxy060608 已提交
200 201
    }

fxy060608's avatar
fxy060608 已提交
202 203
    isFn(beforeAll) && beforeAll(res)

fxy060608's avatar
fxy060608 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    const errMsg = res.errMsg

    if (errMsg.indexOf(apiName + ':ok') === 0) {
      isFn(beforeSuccess) && beforeSuccess(res)

      hasSuccess && success(res)

      isFn(afterSuccess) && afterSuccess(res)
    } else if (errMsg.indexOf(apiName + ':cancel') === 0) {
      res.errMsg = res.errMsg.replace(apiName + ':cancel', apiName + ':fail cancel')

      hasFail && fail(res)

      isFn(beforeCancel) && beforeCancel(res)

      hasCancel && cancel(res)

      isFn(afterCancel) && afterCancel(res)
    } else if (errMsg.indexOf(apiName + ':fail') === 0) {
      isFn(beforeFail) && beforeFail(res)

      hasFail && fail(res)

      isFn(afterFail) && afterFail(res)
    }

    hasComplete && complete(res)

    isFn(afterAll) && afterAll(res)
  }

  invokeCallbacks[callbackId] = {
    name: invokeCallbackName,
    callback: invokeCallback
  }

  return {
    params,
    callbackId
  }
}

function createInvokeCallback (apiName, params = {}, extras = {}) {
  const {
    params: args,
    callbackId
  } = createApiCallback(apiName, params, extras)

  if (isPlainObject(args) && !validateParams(apiName, args, callbackId)) {
    return {
      params: args,
      callbackId: false
    }
  }

  return {
    params: args,
    callbackId
  }
}
fxy060608's avatar
fxy060608 已提交
264 265
// onNativeEventReceive((event,data)=>{}) 需要两个参数,写死最多两个参数,避免改动太大,影响已有逻辑
export function invokeCallbackHandler (invokeCallbackId, res, extras) {
fxy060608's avatar
fxy060608 已提交
266 267 268 269 270 271
  if (typeof invokeCallbackId === 'number') {
    const invokeCallback = invokeCallbacks[invokeCallbackId]
    if (invokeCallback) {
      if (!invokeCallback.keepAlive) {
        delete invokeCallbacks[invokeCallbackId]
      }
fxy060608's avatar
fxy060608 已提交
272
      return invokeCallback.callback(res, extras)
fxy060608's avatar
fxy060608 已提交
273 274 275 276 277
    }
  }
  return res
}

278 279 280 281
export function removeCallbackHandler (invokeCallbackId) {
  delete invokeCallbacks[invokeCallbackId]
}

fxy060608's avatar
fxy060608 已提交
282
export function wrapperUnimplemented (name) {
fxy060608's avatar
fxy060608 已提交
283
  return function todo (args) {
fxy060608's avatar
fxy060608 已提交
284 285 286 287
    console.error('API `' + name + '` is not yet implemented')
  }
}

fxy060608's avatar
fxy060608 已提交
288 289 290
function wrapperExtras (name, extras) {
  const protocolOptions = protocol[name]
  if (protocolOptions) {
fxy060608's avatar
fxy060608 已提交
291
    isFn(protocolOptions.beforeAll) && (extras.beforeAll = protocolOptions.beforeAll)
fxy060608's avatar
fxy060608 已提交
292 293 294 295
    isFn(protocolOptions.beforeSuccess) && (extras.beforeSuccess = protocolOptions.beforeSuccess)
  }
}

296
export function wrapper (name, invokeMethod, extras = {}) {
fxy060608's avatar
fxy060608 已提交
297 298 299
  if (!isFn(invokeMethod)) {
    return invokeMethod
  }
fxy060608's avatar
fxy060608 已提交
300
  wrapperExtras(name, extras)
fxy060608's avatar
fxy060608 已提交
301 302 303 304 305 306 307
  return function (...args) {
    if (isSyncApi(name)) {
      if (validateParams(name, args, -1)) {
        return invokeMethod.apply(null, args)
      }
    } else if (isCallbackApi(name)) {
      if (validateParams(name, args, -1)) {
Q
qiang 已提交
308
        return invokeMethod((name.startsWith('off') ? getKeepAliveApiCallback : createKeepAliveApiCallback)(name, args[0]))
fxy060608's avatar
fxy060608 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
      }
    } else {
      let argsObj = {}
      if (args.length) {
        argsObj = args[0]
      }
      const {
        params,
        callbackId
      } = createInvokeCallback(name, argsObj, extras)
      if (callbackId !== false) {
        let res
        if (isFn(params)) {
          res = invokeMethod(callbackId)
        } else {
          res = invokeMethod(params, callbackId)
        }
        if (res && !isTaskApi(name)) {
          res = invokeCallbackHandler(callbackId, res)
          if (isPlainObject(res)) {
            res.errMsg = res.errMsg || name + ':ok'
          }
        }
        return res
      }
    }
  }
Q
qiang 已提交
336
}