学员端小程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.9 KiB

1 year ago
  1. import buildURL from '../helpers/buildURL'
  2. import buildFullPath from '../core/buildFullPath'
  3. import settle from '../core/settle'
  4. import { isUndefined } from '../utils'
  5. /**
  6. * 返回可选值存在的配置
  7. * @param {Array} keys - 可选值数组
  8. * @param {Object} config2 - 配置
  9. * @return {{}} - 存在的配置项
  10. */
  11. const mergeKeys = (keys, config2) => {
  12. const config = {}
  13. keys.forEach((prop) => {
  14. if (!isUndefined(config2[prop])) {
  15. config[prop] = config2[prop]
  16. }
  17. })
  18. return config
  19. }
  20. export default (config) => new Promise((resolve, reject) => {
  21. const fullPath = buildURL(buildFullPath(config.baseURL, config.url), config.params)
  22. const _config = {
  23. url: fullPath,
  24. header: config.header,
  25. complete: (response) => {
  26. config.fullPath = fullPath
  27. response.config = config
  28. try {
  29. // 对可能字符串不是json 的情况容错
  30. if (typeof response.data === 'string') {
  31. response.data = JSON.parse(response.data)
  32. }
  33. // eslint-disable-next-line no-empty
  34. } catch (e) {
  35. }
  36. settle(resolve, reject, response)
  37. }
  38. }
  39. let requestTask
  40. if (config.method === 'UPLOAD') {
  41. delete _config.header['content-type']
  42. delete _config.header['Content-Type']
  43. const otherConfig = {
  44. // #ifdef MP-ALIPAY
  45. fileType: config.fileType,
  46. // #endif
  47. filePath: config.filePath,
  48. name: config.name
  49. }
  50. const optionalKeys = [
  51. // #ifdef APP-PLUS || H5
  52. 'files',
  53. // #endif
  54. // #ifdef H5
  55. 'file',
  56. // #endif
  57. // #ifdef H5 || APP-PLUS
  58. 'timeout',
  59. // #endif
  60. 'formData'
  61. ]
  62. requestTask = uni.uploadFile({ ..._config, ...otherConfig, ...mergeKeys(optionalKeys, config) })
  63. } else if (config.method === 'DOWNLOAD') {
  64. // #ifdef H5 || APP-PLUS
  65. if (!isUndefined(config.timeout)) {
  66. _config.timeout = config.timeout
  67. }
  68. // #endif
  69. requestTask = uni.downloadFile(_config)
  70. } else {
  71. const optionalKeys = [
  72. 'data',
  73. 'method',
  74. // #ifdef H5 || APP-PLUS || MP-ALIPAY || MP-WEIXIN
  75. 'timeout',
  76. // #endif
  77. 'dataType',
  78. // #ifndef MP-ALIPAY
  79. 'responseType',
  80. // #endif
  81. // #ifdef APP-PLUS
  82. 'sslVerify',
  83. // #endif
  84. // #ifdef H5
  85. 'withCredentials',
  86. // #endif
  87. // #ifdef APP-PLUS
  88. 'firstIpv4'
  89. // #endif
  90. ]
  91. requestTask = uni.request({ ..._config, ...mergeKeys(optionalKeys, config) })
  92. }
  93. if (config.getTask) {
  94. config.getTask(requestTask, config)
  95. }
  96. })