Skip to content

Commit

Permalink
fix: array child pattern match validation (#248)
Browse files Browse the repository at this point in the history
  • Loading branch information
paulatulis committed Jan 11, 2024
1 parent ea0ac6f commit 1c11c12
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
20 changes: 14 additions & 6 deletions src/components/shared/Validations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -183,16 +183,24 @@ export function validationCount(schemaNode: RegularNode) {
return uniq(validationKeys.map(key => ([...numberValidationNames].includes(key) ? 'number' : key))).length;
}

const getArrayValidations = (schemaNode: RegularNode) => {
if (schemaNode.children?.length === 1 && isRegularNode(schemaNode.children[0])) {
if (schemaNode.children[0].enum !== null) {
return { enum: schemaNode.children[0].enum };
} else if (schemaNode.children[0].fragment.pattern !== void 0) {
return { pattern: schemaNode.children[0].fragment.pattern };
}
}
return null;
};

export function getValidationsFromSchema(schemaNode: RegularNode) {
return {
...(schemaNode.enum !== null
? { enum: schemaNode.enum }
: // in case schemaNode is type: "array", check if its child have defined enum
schemaNode.primaryType === 'array' &&
schemaNode.children?.length === 1 &&
isRegularNode(schemaNode.children[0]) &&
schemaNode.children[0].enum !== null
? { enum: schemaNode.children[0].enum }
: schemaNode.primaryType === 'array'
? // in case schemaNode is type: "array", check if its child has an additional validation
getArrayValidations(schemaNode)
: null),
...('annotations' in schemaNode
? {
Expand Down
18 changes: 18 additions & 0 deletions src/components/shared/__tests__/Validations.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,24 @@ describe('Validations component', () => {
expect(wrapper).toIncludeText('Allowed values:p1p2p3');
});

it('should check for array child fragment.pattern', () => {
const tree = buildTree({
type: 'array',
items: {
type: 'string',
pattern: '^[a-z0-9]{13}$',
},
});

const node = tree.children[0] as RegularNode;

expect(isRegularNode(node)).toBe(true);
const validations = getValidationsFromSchema(node);
const wrapper = mount(<Validations validations={validations} />);

expect(wrapper).toIncludeText('Match pattern:^[a-z0-9]{13}$');
});

it('should not render hidden example validations', () => {
const node = new RegularNode({
type: 'number',
Expand Down

0 comments on commit 1c11c12

Please sign in to comment.