index.js 2.3 KB

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