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
40 changes: 40 additions & 0 deletions src/__tests__/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,5 +321,45 @@ describe('Main', () => {
},
]);
});
it('formats array keyword errors (minItems, maxItems, uniqueItems) without awkward keyword repetition (#171)', () => {
const schema = {
type: 'object',
properties: {
operators: {
type: 'array',
minItems: 1,
maxItems: 3,
uniqueItems: true,
},
},
};

expect(getErrors(schema, { operators: [] })).toEqual([
{
start: { line: 1, column: 14, offset: 13 },
end: { line: 1, column: 16, offset: 15 },
error: '/operators: must NOT have fewer than 1 items',
path: '/operators',
},
]);

expect(getErrors(schema, { operators: [1, 2, 3, 4] })).toEqual([
{
start: { line: 1, column: 14, offset: 13 },
end: { line: 1, column: 23, offset: 22 },
error: '/operators: must NOT have more than 3 items',
path: '/operators',
},
]);

expect(getErrors(schema, { operators: [1, 1] })).toEqual([
{
start: { line: 1, column: 14, offset: 13 },
end: { line: 1, column: 19, offset: 18 },
error: '/operators: must NOT have duplicate items (items ## 0 and 1 are identical)',
path: '/operators',
},
]);
});
});
});
13 changes: 9 additions & 4 deletions src/validation-errors/default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,29 @@ import { styleText } from 'node:util';
import type { IOutputError } from '../index';
import BaseValidationError from './base';

const ARRAY_KEYWORDS = new Set(['minItems', 'maxItems', 'uniqueItems']);

export default class DefaultValidationError extends BaseValidationError {
print(): string[] {
const { keyword, message } = this.options;
const output = [
styleText('red', styleText('bold', keyword.toUpperCase()) + ' ' + message) + '\n',
];

return output.concat(
this.getCodeFrame('👈🏽 ' + styleText('magentaBright', keyword) + ' ' + message)
);
const label = ARRAY_KEYWORDS.has(keyword)
? message
: `${styleText('magentaBright', keyword)} ${message}`;

return output.concat(this.getCodeFrame(`👈🏽 ${label}`));
}

getError(): IOutputError {
const { keyword, message } = this.options;
const errorMsg = ARRAY_KEYWORDS.has(keyword) ? (message ?? '') : `${keyword} ${message}`;

return {
...this.getLocation(),
error: this.withDecoratedPath(`${keyword} ${message}`, ': '),
error: this.withDecoratedPath(errorMsg, ': '),
path: this.instancePath,
};
}
Expand Down