优化PUT请求传参机制,实现最小化传参以减少网络传输和提高性能,在请求拦截器中自动计算差异只传递修改过的字段,同时新增通用的表单差异比较工具函数,
This commit is contained in:
@@ -2,6 +2,7 @@ import axios, { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import { Session } from '/@/utils/storage';
|
||||
import qs from 'qs';
|
||||
import { getChangedFields } from '/@/utils/diffUtils';
|
||||
|
||||
// 标记是否正在处理 token 过期,避免重复弹窗
|
||||
let isHandlingTokenExpired = false;
|
||||
@@ -92,6 +93,33 @@ const requestInterceptor = (config: InternalAxiosRequestConfig) => {
|
||||
// 可以在这里添加 token 有效性检查(如果需要)
|
||||
config.headers!['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
// PUT 请求最小化传参处理
|
||||
// 如果请求数据中包含 _originalData,则自动计算差异,只传递修改过的字段
|
||||
if (config.method?.toLowerCase() === 'put' && config.data && typeof config.data === 'object') {
|
||||
const { _originalData, ...currentData } = config.data;
|
||||
|
||||
if (_originalData && typeof _originalData === 'object') {
|
||||
// 获取 id 字段(必须保留)
|
||||
const idField = currentData.id || currentData.Id || currentData.ID;
|
||||
|
||||
// 计算差异
|
||||
const changedFields = getChangedFields(_originalData, currentData, {
|
||||
exclude: ['_originalData', 'id', 'Id', 'ID'],
|
||||
});
|
||||
|
||||
// 如果有变化,只传递 id + 变化的字段
|
||||
if (Object.keys(changedFields).length > 0) {
|
||||
config.data = { id: idField, ...changedFields };
|
||||
} else {
|
||||
// 没有变化,只传递 id
|
||||
config.data = { id: idField };
|
||||
}
|
||||
|
||||
console.log('[最小化传参] 原始字段数:', Object.keys(currentData).length, '-> 传递字段数:', Object.keys(config.data).length);
|
||||
}
|
||||
}
|
||||
|
||||
return config;
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user