Skip to content
Open
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
38 changes: 38 additions & 0 deletions src/__tests__/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,5 +321,43 @@ describe('Main', () => {
},
]);
});
it('prioritizes specific child errors over required errors from unselected anyOf branches (#153)', () => {
const schema = {
type: 'object',
properties: {
processor: {
anyOf: [
{
type: 'object',
properties: {
defaultConfigPath: { type: 'string' },
},
required: ['defaultConfigPath'],
},
{
type: 'object',
properties: {
defaultConfigPackageKey: { type: 'string' },
},
required: ['defaultConfigPackageKey'],
},
],
},
},
};
const data = {
processor: {
defaultConfigPath: true,
},
};
expect(getErrors(schema, data)).toEqual([
{
start: { line: 1, column: 35, offset: 34 },
end: { line: 1, column: 39, offset: 38 },
error: '/processor/defaultConfigPath: type must be string',
path: '/processor/defaultConfigPath',
},
]);
});
});
});
29 changes: 24 additions & 5 deletions src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,18 +97,37 @@ export function filterRedundantErrors(root: ErrorNode, parent?: ErrorNode, key?:
);

/**
* If there is are `required` errors then we can just drop every non-required error.
* And, also `required` should have more priority than `anyOf`. @see #8
* If there are `required` errors then we drop non-required errors.
* However, if a `required` error comes from an `anyOf`/`oneOf` branch
* and there are child errors (meaning the user provided properties matching
* an alternative branch), we should not let that branch required error
* hide the child errors. @see #8, #81, #153
*/

if (requiredErrors.length > 0) {
root.errors = requiredErrors;
const isBranchRequiredError = (error: AjvError): boolean => {
return Boolean(
error.schemaPath &&
(error.schemaPath.includes('/anyOf/') || error.schemaPath.includes('/oneOf/'))
);
};

const directRequiredErrors = requiredErrors.filter(e => !isBranchRequiredError(e));
const branchRequiredErrors = requiredErrors.filter(isBranchRequiredError);

if (directRequiredErrors.length > 0) {
root.errors = directRequiredErrors;
root.children = {};

// No need for further processing, as we've emptied out children
return;
}

if (branchRequiredErrors.length > 0 && Object.keys(root.children).length === 0) {
root.errors = branchRequiredErrors;
root.children = {};

return;
}

/**
* If there is an `anyOf` error that means we have more meaningful errors
* inside children. So we will just remove all errors from this level.
Expand Down