request.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import store from '@/store/index.js'
  2. import config from '@/admin.config.js'
  3. const debugOptions = config.navBar.debug
  4. const db = uniCloud.database()
  5. export function request (action, params, options) {
  6. const {objectName, functionName, showModal, ...objectOptions} = Object.assign({
  7. objectName: 'uni-id-co',
  8. functionName: '',
  9. showModal: false,
  10. customUI: true,
  11. loadingOptions: {
  12. title: 'xxx'
  13. },
  14. }, options)
  15. // 兼容 云函数 与 云对象 请求,默认为云对象
  16. let call
  17. if (functionName) {
  18. call = uniCloud.callFunction({
  19. name: functionName,
  20. data: {
  21. action,
  22. params
  23. }
  24. })
  25. } else {
  26. const uniCloudObject = uniCloud.importObject(objectName, objectOptions)
  27. call = uniCloudObject[action](params)
  28. }
  29. return call.then(result => {
  30. result = functionName ? result.result: result
  31. if (!result) {
  32. return Promise.resolve(result)
  33. }
  34. if (result.errCode) {
  35. return Promise.reject(result)
  36. }
  37. return Promise.resolve(result)
  38. }).catch(err => {
  39. showModal && uni.showModal({
  40. content: err.errMsg || '请求服务失败',
  41. showCancel: false
  42. })
  43. // #ifdef H5
  44. const noDebugPages = ['/uni_modules/uni-id-pages/pages/login/login-withpwd', '/uni_modules/uni-id-pages/pages/register/register']
  45. const path = location.hash.split('#')[1]
  46. if (debugOptions && debugOptions.enable === true && noDebugPages.indexOf(path) === -1) {
  47. store.dispatch('error/add', {
  48. err: err.toString(),
  49. info: '$request("' + action + '")',
  50. route: '',
  51. time: new Date().toLocaleTimeString()
  52. })
  53. }
  54. // #endif
  55. return Promise.reject(err)
  56. })
  57. }
  58. // #ifndef VUE3
  59. export function initRequest(Vue) {
  60. Vue.prototype.$request = request
  61. }
  62. // #endif
  63. // #ifdef VUE3
  64. export function initRequest(app) {
  65. app.config.globalProperties.$request = request
  66. }
  67. // #endif