Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,23 @@ describe('removeField', function () {
},
});
});

it('clean up required', function () {
const schema = {
bsonType: 'object',
properties: {
name: { bsonType: 'string' },
age: { bsonType: ['string', 'int'] },
},
required: ['name', 'age'],
};
const result = updateSchema({
fieldPath: ['name'],
jsonSchema: schema,
update: 'removeField',
});
expect(result.required).to.deep.equal(['age']);
});
});

describe('nested schema', function () {
Expand Down Expand Up @@ -797,6 +814,24 @@ describe('renameField', function () {
},
});
});

it('update required', function () {
const schema = {
bsonType: 'object',
properties: {
name: { bsonType: 'string' },
age: { bsonType: ['string', 'int'] },
},
required: ['name', 'age'],
};
const result = updateSchema({
fieldPath: ['name'],
jsonSchema: schema,
update: 'renameField',
newFieldName: 'newName',
});
expect(result.required).to.deep.equal(['newName', 'age']);
});
});

describe('nested schema', function () {
Expand Down
18 changes: 16 additions & 2 deletions packages/compass-data-modeling/src/utils/schema-traversal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -184,26 +184,40 @@ const applySchemaUpdate = ({
case 'removeField': {
if (!schema.properties || !schema.properties[fieldName])
throw new Error('Field to remove does not exist');
return {
const newSchema = {
...schema,
properties: Object.fromEntries(
Object.entries(schema.properties).filter(([key]) => key !== fieldName)
),
};
// clean up required if needed
if (newSchema.required && Array.isArray(newSchema.required)) {
newSchema.required = newSchema.required.filter(
(key) => key !== fieldName
);
}
return newSchema;
}
case 'renameField': {
if (!schema.properties || !schema.properties[fieldName])
throw new Error('Field to rename does not exist');
if (!newFieldName)
throw new Error('New field name is required for the rename operation');
return {
const newSchema = {
...schema,
properties: Object.fromEntries(
Object.entries(schema.properties).map(([key, value]) =>
key === fieldName ? [newFieldName, value] : [key, value]
)
),
};
// update required if needed
if (newSchema.required && Array.isArray(newSchema.required)) {
newSchema.required = newSchema.required.map((key) =>
key !== fieldName ? key : newFieldName
);
}
return newSchema;
}
default:
return schema;
Expand Down
Loading