request.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. if (!result) {
  31. return Promise.resolve(result)
  32. }
  33. if (result.errCode) {
  34. return Promise.reject(result)
  35. }
  36. return Promise.resolve(result)
  37. }).catch(err => {
  38. showModal && uni.showModal({
  39. content: err.errMsg || '请求服务失败',
  40. showCancel: false
  41. })
  42. // #ifdef H5
  43. const noDebugPages = ['/uni_modules/uni-id-pages/pages/login/login-withpwd', '/uni_modules/uni-id-pages/pages/register/register']
  44. const path = location.hash.split('#')[1]
  45. if (debugOptions && debugOptions.enable === true && noDebugPages.indexOf(path) === -1) {
  46. store.dispatch('error/add', {
  47. err: err.toString(),
  48. info: '$request("' + action + '")',
  49. route: '',
  50. time: new Date().toLocaleTimeString()
  51. })
  52. }
  53. // #endif
  54. return Promise.reject(err)
  55. })
  56. }
  57. // #ifndef VUE3
  58. export function initRequest(Vue) {
  59. Vue.prototype.$request = request
  60. }
  61. // #endif
  62. // #ifdef VUE3
  63. export function initRequest(app) {
  64. app.config.globalProperties.$request = request
  65. }
  66. // #endif