index.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. let otherConfig = {
  40. // #ifdef MP-ALIPAY
  41. fileType: config.fileType,
  42. // #endif
  43. filePath: config.filePath,
  44. name: config.name
  45. }
  46. const optionalKeys = [
  47. // #ifdef APP-PLUS || H5
  48. 'files',
  49. // #endif
  50. // #ifdef H5
  51. 'file',
  52. // #endif
  53. 'formData'
  54. ]
  55. requestTask = uni.uploadFile({..._config, ...otherConfig, ...mergeKeys(optionalKeys, config)})
  56. } else if (config.method === 'DOWNLOAD') {
  57. requestTask = uni.downloadFile(_config)
  58. } else {
  59. const optionalKeys = [
  60. 'data',
  61. 'method',
  62. // #ifdef MP-ALIPAY || MP-WEIXIN
  63. 'timeout',
  64. // #endif
  65. 'dataType',
  66. // #ifndef MP-ALIPAY || APP-PLUS
  67. 'responseType',
  68. // #endif
  69. // #ifdef APP-PLUS
  70. 'sslVerify',
  71. // #endif
  72. // #ifdef H5
  73. 'withCredentials'
  74. // #endif
  75. ]
  76. requestTask = uni.request({..._config,...mergeKeys(optionalKeys, config)})
  77. }
  78. if (config.getTask) {
  79. config.getTask(requestTask, config)
  80. }
  81. })
  82. }