Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle non-string enum values #82

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
12 changes: 12 additions & 0 deletions src/validation-errors/__tests__/__snapshots__/enum.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,18 @@ Array [
]
`;

exports[`Enum when value is an object prints correctly for allowedValues containing null 1`] = `
Array [
"ENUM should be equal to one of the allowed values",
"(one, two, null)
",
"  1 | {
> 2 |  \\"id\\": \\"baz\\"
  |  ^^^^^ 👈🏽 Unexpected value, should be equal to one of the allowed values
  3 | }",
]
`;

exports[`Enum when value is an object prints correctly for empty value 1`] = `
Array [
"ENUM should be equal to one of the allowed values",
Expand Down
15 changes: 15 additions & 0 deletions src/validation-errors/__tests__/enum.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,21 @@ describe('Enum', () => {

expect(error.print(schema, { id: '' })).toMatchSnapshot();
});

it('prints correctly for allowedValues containing null', () => {
const error = new EnumValidationError(
{
keyword: 'enum',
dataPath: '/id',
schemaPath: '#/enum',
params: { allowedValues: ['one', 'two', null] },
message: `should be equal to one of the allowed values`,
},
{ data, schema, jsonRaw, jsonAst }
);

expect(error.print()).toMatchSnapshot();
});
});

describe('when value is a primitive', () => {
Expand Down
27 changes: 20 additions & 7 deletions src/validation-errors/enum.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@ import leven from 'leven';
import pointer from 'jsonpointer';
import BaseValidationError from './base';

function printAllowedValues(allowedValues) {
return allowedValues
.map(value =>
value === null || value === undefined ? String(value) : value
)
.join(', ');
}

export default class EnumValidationError extends BaseValidationError {
print() {
const {
Expand All @@ -13,7 +21,7 @@ export default class EnumValidationError extends BaseValidationError {

const output = [
chalk`{red {bold ENUM} ${message}}`,
chalk`{red (${allowedValues.join(', ')})}\n`,
chalk`{red (${printAllowedValues(allowedValues)})}\n`,
];

return output.concat(
Expand All @@ -33,7 +41,7 @@ export default class EnumValidationError extends BaseValidationError {
...this.getLocation(),
error: `${this.getDecoratedPath(
dataPath
)} ${message}: ${params.allowedValues.join(', ')}`,
)} ${message}: ${printAllowedValues(params.allowedValues)}`,
path: dataPath,
};

Expand All @@ -53,18 +61,23 @@ export default class EnumValidationError extends BaseValidationError {
const currentValue =
dataPath === '' ? this.data : pointer.get(this.data, dataPath);

if (!currentValue) {
if (typeof currentValue !== 'string') {
return null;
}

const bestMatch = allowedValues
const matches = allowedValues
.filter(value => typeof value === 'string')
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

allowedValues can be numbers too.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will it produce anything reasonable for numbers, though?
If we don't filter out number here, we will also need to adjust the condition above (line 64)

.map(value => ({
value,
weight: leven(value, currentValue.toString()),
}))
.sort((x, y) =>
x.weight > y.weight ? 1 : x.weight < y.weight ? -1 : 0
)[0];
.sort((x, y) => (x.weight > y.weight ? 1 : x.weight < y.weight ? -1 : 0));

if (matches.length === 0) {
return;
}

const bestMatch = matches[0];

return allowedValues.length === 1 ||
bestMatch.weight < bestMatch.value.length
Expand Down