2023-03-28 21:32:54 +08:00
|
|
|
import { isUndefined, isPlainObject } from '../helpers/isTypes';
|
|
|
|
import { deepMerge } from '../helpers/deepMerge';
|
2023-03-23 20:09:00 +08:00
|
|
|
import { AxiosRequestConfig } from './Axios';
|
|
|
|
|
2023-04-03 21:03:33 +08:00
|
|
|
const fromConfig2Map: Record<string, boolean> = {
|
|
|
|
url: true,
|
|
|
|
method: true,
|
|
|
|
data: true,
|
|
|
|
upload: true,
|
|
|
|
download: true,
|
|
|
|
};
|
|
|
|
const deepMergeConfigMap: Record<string, boolean> = {
|
|
|
|
headers: true,
|
|
|
|
params: true,
|
|
|
|
};
|
2023-03-23 20:09:00 +08:00
|
|
|
|
|
|
|
export function mergeConfig(
|
|
|
|
config1: AxiosRequestConfig = {},
|
|
|
|
config2: AxiosRequestConfig = {},
|
|
|
|
): AxiosRequestConfig {
|
|
|
|
const config: AxiosRequestConfig = {};
|
|
|
|
|
2023-04-03 21:03:33 +08:00
|
|
|
// 所有已知键名
|
|
|
|
const keysSet = Array.from(
|
|
|
|
new Set([...Object.keys(config1), ...Object.keys(config2)]),
|
|
|
|
);
|
2023-03-23 20:09:00 +08:00
|
|
|
|
2023-04-03 21:03:33 +08:00
|
|
|
for (const key of keysSet) {
|
|
|
|
const val1 = config1[key] as any;
|
|
|
|
const val2 = config2[key] as any;
|
2023-03-23 20:09:00 +08:00
|
|
|
|
2023-04-03 21:03:33 +08:00
|
|
|
// 只从 config2 中取值
|
|
|
|
if (fromConfig2Map[key]) {
|
|
|
|
if (!isUndefined(val2)) config[key] = val2;
|
2023-03-23 20:09:00 +08:00
|
|
|
}
|
2023-04-03 21:03:33 +08:00
|
|
|
// 深度合并 config1 和 config2 中的对象
|
|
|
|
else if (deepMergeConfigMap[key]) {
|
|
|
|
if (isPlainObject(val1) && isPlainObject(val2)) {
|
|
|
|
config[key] = deepMerge(val1, val2);
|
|
|
|
} else if (isPlainObject(val1)) {
|
|
|
|
config[key] = deepMerge(val1);
|
|
|
|
} else if (isPlainObject(val2)) {
|
|
|
|
config[key] = deepMerge(val2);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// 优先从 config2 中取值,如果没有值就从 config1 中取值
|
|
|
|
else {
|
|
|
|
if (!isUndefined(val2)) {
|
|
|
|
config[key] = val2;
|
|
|
|
} else if (!isUndefined(val1)) {
|
|
|
|
config[key] = val1;
|
|
|
|
}
|
2023-03-23 20:09:00 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return config;
|
|
|
|
}
|