Skip to content

Commit

Permalink
fix(modify): Customize attrs as Array now overrides the value
Browse files Browse the repository at this point in the history
  • Loading branch information
sandrina-p committed Jul 19, 2024
1 parent f09dd3c commit 751f089
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 10 deletions.
30 changes: 21 additions & 9 deletions src/modify.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import get from 'lodash/get';
import merge from 'lodash/merge';
import mergeWith from 'lodash/mergeWith';

/**
*
Expand All @@ -11,6 +11,10 @@ function shortToFullPath(path) {
return path.replace('.', '.properties.');
}

function mergeReplaceArray(_, newVal) {
return Array.isArray(newVal) ? newVal : undefined;
}

function standardizeAttrs(attrs) {
const { errorMessage, properties, ...rest } = attrs;

Expand All @@ -35,10 +39,14 @@ function rewriteFields(schema, fieldsConfig) {
const fieldAttrs = get(schema.properties, fieldPath);
const fieldChanges = typeof mutation === 'function' ? mutation(fieldAttrs) : mutation;

merge(get(schema.properties, fieldPath), {
...fieldAttrs,
...standardizeAttrs(fieldChanges),
});
mergeWith(
get(schema.properties, fieldPath),
{
...fieldAttrs,
...standardizeAttrs(fieldChanges),
},
mergeReplaceArray
);

if (fieldChanges.properties) {
rewriteFields(get(schema.properties, fieldPath), fieldChanges.properties);
Expand All @@ -52,10 +60,14 @@ function rewriteAllFields(schema, configCallback, context) {

Object.entries(schema.properties).forEach(([fieldName, fieldAttrs]) => {
const fullName = parentName ? `${parentName}.${fieldName}` : fieldName;
merge(get(schema.properties, fieldName), {
...fieldAttrs,
...configCallback(fullName, fieldAttrs),
});
mergeWith(
get(schema.properties, fieldName),
{
...fieldAttrs,
...configCallback(fullName, fieldAttrs),
},
mergeReplaceArray
);

// Nested fields, go recursive (fieldset)
if (fieldAttrs.properties) {
Expand Down
25 changes: 24 additions & 1 deletion src/tests/modify.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ describe('modify() - basic mutations', () => {
});
});

it('replace field options (radio/select)', () => {
it('replace field attrs that are arrays (partial)', () => {
const result = modify(schemaPet, {
fields: {
has_pet: (fieldAttrs) => {
Expand Down Expand Up @@ -257,6 +257,29 @@ describe('modify() - basic mutations', () => {
});
});

it('replace field attrs that are arrays (full)', () => {
const result = modify(schemaPet, {
fields: {
has_pet: {
oneOf: [{ const: 'yaaas', title: 'YAAS!' }],
},
},
});

expect(result).toMatchObject({
properties: {
has_pet: {
oneOf: [
{
const: 'yaaas',
title: 'YAAS!',
},
],
},
},
});
});

it('error message', () => {
const result = modify(schemaPet, {
fields: {
Expand Down

0 comments on commit 751f089

Please sign in to comment.