mergeConfig.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import {deepMerge, isObject} 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. }
  33. const mergeDeepPropertiesKeys = ['header', 'params', 'custom']
  34. const defaultToConfig2Keys = ['getTask', 'validateStatus']
  35. mergeDeepPropertiesKeys.forEach(prop => {
  36. if (isObject(config2[prop])) {
  37. config[prop] = deepMerge(globalsConfig[prop], config2[prop])
  38. } else if (typeof config2[prop] !== 'undefined') {
  39. config[prop] = config2[prop]
  40. } else if (isObject(globalsConfig[prop])) {
  41. config[prop] = deepMerge(globalsConfig[prop])
  42. } else if (typeof globalsConfig[prop] !== 'undefined') {
  43. config[prop] = globalsConfig[prop]
  44. }
  45. })
  46. config = {...config, ...mergeKeys(defaultToConfig2Keys, globalsConfig, config2)}
  47. // eslint-disable-next-line no-empty
  48. if (method === 'DOWNLOAD') {
  49. } else if (method === 'UPLOAD') {
  50. if (isObject(config.header)) {
  51. delete config.header['content-type']
  52. delete config.header['Content-Type']
  53. }
  54. const uploadKeys = [
  55. // #ifdef APP-PLUS || H5
  56. 'files',
  57. // #endif
  58. // #ifdef MP-ALIPAY
  59. 'fileType',
  60. // #endif
  61. // #ifdef H5
  62. 'file',
  63. // #endif
  64. 'filePath',
  65. 'name',
  66. 'formData',
  67. ]
  68. uploadKeys.forEach(prop => {
  69. if (typeof config2[prop] !== 'undefined') {
  70. config[prop] = config2[prop]
  71. }
  72. })
  73. } else {
  74. const defaultsKeys = [
  75. 'data',
  76. // #ifdef MP-ALIPAY || MP-WEIXIN
  77. 'timeout',
  78. // #endif
  79. 'dataType',
  80. // #ifndef MP-ALIPAY || APP-PLUS
  81. 'responseType',
  82. // #endif
  83. // #ifdef APP-PLUS
  84. 'sslVerify',
  85. // #endif
  86. // #ifdef H5
  87. 'withCredentials'
  88. // #endif
  89. ]
  90. config = {...config, ...mergeKeys(defaultsKeys, globalsConfig, config2)}
  91. }
  92. return config
  93. }