mergeConfig.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import {deepMerge} from '../utils'
  2. /**
  3. * 合并局部配置优先的配置,如果局部有该配置项则用局部,如果全局有该配置项则用全局
  4. * @param {Array} keys - 配置项
  5. * @param {Object} globalsConfig - 当前的全局配置
  6. * @param {Object} config2 - 局部配置
  7. * @return {{}}
  8. */
  9. const mergeKeys = (keys, globalsConfig, config2) => {
  10. let config = {}
  11. keys.forEach(prop => {
  12. if (typeof config2[prop] !== 'undefined') {
  13. config[prop] = config2[prop]
  14. } else if (typeof globalsConfig[prop] !== 'undefined') {
  15. config[prop] = globalsConfig[prop]
  16. }
  17. })
  18. return config
  19. }
  20. /**
  21. *
  22. * @param globalsConfig - 当前实例的全局配置
  23. * @param config2 - 当前的局部配置
  24. * @return - 合并后的配置
  25. */
  26. export default (globalsConfig, config2 = {}) => {
  27. const method = config2.method || globalsConfig.method || 'GET'
  28. let config = {
  29. baseURL: globalsConfig.baseURL || '',
  30. method: method,
  31. url: config2.url || '',
  32. params: config2.params || {},
  33. custom: {...(globalsConfig.custom || {}), ...(config2.custom || {})},
  34. header: deepMerge(globalsConfig.header || {}, config2.header || {})
  35. }
  36. const defaultToConfig2Keys = ['getTask', 'validateStatus']
  37. config = {...config, ...mergeKeys(defaultToConfig2Keys, globalsConfig, config2)}
  38. // eslint-disable-next-line no-empty
  39. if (method === 'DOWNLOAD') {
  40. } else if (method === 'UPLOAD') {
  41. delete config.header['content-type']
  42. delete config.header['Content-Type']
  43. const uploadKeys = [
  44. // #ifdef APP-PLUS || H5
  45. 'files',
  46. // #endif
  47. // #ifdef MP-ALIPAY
  48. 'fileType',
  49. // #endif
  50. // #ifdef H5
  51. 'file',
  52. // #endif
  53. 'filePath',
  54. 'name',
  55. 'formData',
  56. ]
  57. uploadKeys.forEach(prop => {
  58. if (typeof config2[prop] !== 'undefined') {
  59. config[prop] = config2[prop]
  60. }
  61. })
  62. } else {
  63. const defaultsKeys = [
  64. 'data',
  65. // #ifdef MP-ALIPAY || MP-WEIXIN
  66. 'timeout',
  67. // #endif
  68. 'dataType',
  69. // #ifndef MP-ALIPAY || APP-PLUS
  70. 'responseType',
  71. // #endif
  72. // #ifdef APP-PLUS
  73. 'sslVerify',
  74. // #endif
  75. // #ifdef H5
  76. 'withCredentials',
  77. // #endif
  78. // #ifdef APP-PLUS
  79. 'firstIpv4',
  80. // #endif
  81. ]
  82. config = {...config, ...mergeKeys(defaultsKeys, globalsConfig, config2)}
  83. }
  84. return config
  85. }