perf: refs #8217 getDifferences fix

This commit is contained in:
Javier Segarra 2025-04-07 15:04:26 +02:00
parent 9b4f3c71c0
commit 5f43c4eaca
4 changed files with 18 additions and 49 deletions

View File

@ -98,6 +98,7 @@ defineExpose({
reset,
hasChanges,
saveChanges,
getChanges,
formData,
originalData,

View File

@ -221,7 +221,7 @@ async function save() {
isLoading.value = true;
try {
formData.value = trimData(formData.value);
const body = $props.mapper(formData.value, originalData.value);
const body = $props.mapper(originalData.value, formData.value);
const method = $props.urlCreate ? 'post' : 'patch';
const url =
$props.urlCreate || $props.urlUpdate || $props.url || arrayData.store.url;

View File

@ -1,54 +1,22 @@
export default function getDifferences(obj1, obj2) {
const diff = {};
export default function getDifferences(initialData, formData) {
const differences = {};
delete initialData.$index;
delete formData.$index;
const copyObj1 = { ...obj1 };
const copyObj2 = obj2 ? { ...obj2 } : {};
delete copyObj1.$index;
if (copyObj2) delete copyObj2.$index;
for (const key in copyObj1) {
if (copyObj1.hasOwnProperty(key)) {
for (const key in formData) {
if (formData.hasOwnProperty(key)) {
if (
!copyObj2.hasOwnProperty(key) ||
!deepCompare(copyObj1[key], copyObj2[key])
!initialData ||
!initialData.hasOwnProperty(key) ||
formData[key] !== initialData[key]
) {
diff[key] = copyObj1[key];
//Añadir la diferencia solo si existe initialData
if (initialData) {
differences[key] = formData[key];
}
}
}
}
for (const key in copyObj2) {
if (copyObj2.hasOwnProperty(key) && !copyObj1.hasOwnProperty(key)) {
diff[key] = copyObj2[key];
}
}
return diff;
}
function deepCompare(obj1, obj2) {
if (
typeof obj1 !== 'object' ||
obj1 === null ||
typeof obj2 !== 'object' ||
obj2 === null
) {
return obj1 === obj2;
}
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) {
return false;
}
for (const key of keys1) {
if (!obj2.hasOwnProperty(key) || !deepCompare(obj1[key], obj2[key])) {
return false;
}
}
return true;
return differences;
}

View File

@ -1,9 +1,9 @@
import getDifferences from './getDifferences';
import getUpdatedValues from './getUpdatedValues';
export default function onBeforeSave(formData, originalData) {
export default function onBeforeSave(originalData, formData) {
return getUpdatedValues(
Object.keys(getDifferences(formData, originalData)),
Object.keys(getDifferences(originalData, formData)),
formData,
);
}