index.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. let 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) => {
  21. return new Promise((resolve, reject) => {
  22. let fullPath = buildURL(buildFullPath(config.baseURL, config.url), config.params, config.paramsSerializer)
  23. const _config = {
  24. url: fullPath,
  25. header: config.header,
  26. complete: (response) => {
  27. config.fullPath = fullPath
  28. response.config = config
  29. response.rawData = response.data
  30. try {
  31. // 对可能字符串不是json 的情况容错
  32. if (typeof response.data === 'string') {
  33. response.data = JSON.parse(response.data)
  34. }
  35. // eslint-disable-next-line no-empty
  36. } catch (e) {
  37. }
  38. settle(resolve, reject, response)
  39. }
  40. }
  41. let requestTask
  42. if (config.method === 'UPLOAD') {
  43. delete _config.header['content-type']
  44. delete _config.header['Content-Type']
  45. let otherConfig = {
  46. // #ifdef MP-ALIPAY
  47. fileType: config.fileType,
  48. // #endif
  49. filePath: config.filePath,
  50. name: config.name
  51. }
  52. const optionalKeys = [
  53. // #ifdef APP-PLUS || H5
  54. 'files',
  55. // #endif
  56. // #ifdef H5
  57. 'file',
  58. // #endif
  59. // #ifdef H5 || APP-PLUS
  60. 'timeout',
  61. // #endif
  62. 'formData'
  63. ]
  64. requestTask = uni.uploadFile({..._config, ...otherConfig, ...mergeKeys(optionalKeys, config)})
  65. } else if (config.method === 'DOWNLOAD') {
  66. // #ifdef H5 || APP-PLUS
  67. if (!isUndefined(config['timeout'])) {
  68. _config['timeout'] = config['timeout']
  69. }
  70. // #endif
  71. requestTask = uni.downloadFile(_config)
  72. } else {
  73. const optionalKeys = [
  74. 'data',
  75. 'method',
  76. // #ifdef H5 || APP-PLUS || MP-ALIPAY || MP-WEIXIN
  77. 'timeout',
  78. // #endif
  79. 'dataType',
  80. // #ifndef MP-ALIPAY
  81. 'responseType',
  82. // #endif
  83. // #ifdef APP-PLUS
  84. 'sslVerify',
  85. // #endif
  86. // #ifdef H5
  87. 'withCredentials',
  88. // #endif
  89. // #ifdef APP-PLUS
  90. 'firstIpv4',
  91. // #endif
  92. ]
  93. requestTask = uni.request({..._config, ...mergeKeys(optionalKeys, config)})
  94. }
  95. if (config.getTask) {
  96. config.getTask(requestTask, config)
  97. }
  98. })
  99. }