index.js 2.7 KB

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