Skip to content

Commit

Permalink
feat: useJsonSchemaDiff recursively lists object properties
Browse files Browse the repository at this point in the history
  • Loading branch information
matthieu-foucault committed Mar 31, 2021
1 parent d45fb1a commit 1fd3dc1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
27 changes: 23 additions & 4 deletions app/hooks/useJsonSchemaDiff.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
import diff from 'deep-diff';

const addObjectToDiffMap = (path, lhs, rhs, idDiffMap) => {
if (typeof lhs !== 'object' && typeof rhs !== 'object') {
idDiffMap[path] = {lhs: lhs ?? null, rhs: rhs ?? null};
return;
}
if (typeof lhs === 'object' || typeof rhs === 'object') {
const keys = new Set<string>();

if (lhs) Object.keys(lhs).forEach((k) => keys.add(k));
if (rhs) Object.keys(rhs).forEach((k) => keys.add(k));

keys.forEach((k) =>
addObjectToDiffMap(`${path}_${k}`, lhs?.[k], rhs?.[k], idDiffMap)
);
}
};

/**
*
* @param formData the form data to display when not diffing
Expand Down Expand Up @@ -59,10 +76,12 @@ const useJsonSchemaDiff = (
}
} else if (difference.path) {
const {lhs, rhs} = difference;
idDiffMap[[formIdPrefix, ...difference.path].join('_')] = {
lhs: lhs ?? null,
rhs: rhs ?? null
};
addObjectToDiffMap(
[formIdPrefix, ...difference.path].join('_'),
lhs,
rhs,
idDiffMap
);
}
});
}
Expand Down
14 changes: 14 additions & 0 deletions app/tests/hooks/useJsonSchemaDiff.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,20 @@ describe('The useJsonSchemaDiff hook', () => {
});
});

it('should return field-level differences when a nested object is added', () => {
const lhs = {};
const rhs = {
a: {
b: 'foo'
}
};
const result = useJsonSchemaDiff(rhs, true, prefix, lhs, rhs);
expect(result.formData).toStrictEqual(rhs);
expect(result.idDiffMap).toStrictEqual({
[`${prefix}_a_b`]: {lhs: null, rhs: 'foo'}
});
});

it('should return differences when a value is added', () => {
const lhs = {
a: 1,
Expand Down

0 comments on commit 1fd3dc1

Please sign in to comment.