3-pro.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. let $interceptors = {}
  2. // 以下是没有 success、fail、complete 属性的api
  3. // 1、...Sync【√】
  4. // 2、on...【√】
  5. // 3、create... 除了 createBLEConnection【√】
  6. // 4、...Manager【√】
  7. // 5、pause...【√】
  8. // 6、stopRecord、stopVoice、stopBackgroundAudio、stopPullDownRefresh【√】
  9. // 7、hideKeyboard、hideToast、hideLoading、showNavigationBarLoading、hideNavigationBarLoading【√】
  10. // 8、canIUse、navigateBack、closeSocket、pageScrollTo、drawCanvas【√】
  11. uni.pro = {}
  12. for (let key in uni) {
  13. if (/^on|^create|Sync$|Manager$|^pause/.test(key) && key !== 'createBLEConnection' || key === 'stopRecord' || key === 'stopVoice' || key === 'stopBackgroundAudio' || key === 'stopPullDownRefresh' || key === 'hideKeyboard' || key === 'hideToast' || key === 'hideLoading' || key === 'showNavigationBarLoading' || key === 'hideNavigationBarLoading' || key === 'canIUse' || key === 'navigateBack' || key === 'closeSocket' || key === 'closeSocket' || key === 'pageScrollTo' || key === 'drawCanvas') {
  14. uni.pro[key] = uni[key]
  15. continue
  16. }
  17. uni.pro[key] = (options) => {
  18. options = options || {}
  19. if ($interceptors[key] && $interceptors[key].config) {
  20. let ret = $interceptors[key].config.call(this, options)
  21. if (ret === false) {
  22. options.fail && options.fail('aborted by interceptor')
  23. return
  24. }
  25. options = ret
  26. }
  27. return new Promise((resolve, reject) => {
  28. try {
  29. ['fail', 'success', 'complete'].forEach((k) => {
  30. options[k] = (res) => {
  31. if ($interceptors[key] && $interceptors[key][k]) {
  32. res = $interceptors[key][k].call(this, res)
  33. }
  34. if (k === 'success') {
  35. resolve(res)
  36. }
  37. else if (k === 'fail') {
  38. reject(res)
  39. }
  40. }
  41. })
  42. } catch (err) {
  43. console.error(err)
  44. }
  45. uni[key](options)
  46. })
  47. }
  48. }
  49. uni.pro.interceptor = (api, provider) => {
  50. $interceptors[api] = provider
  51. }