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

feat: add validationErrors to schema mismatch errors #641

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
8 changes: 6 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -866,6 +866,7 @@ function buildValue (context, location, input) {

if ((type === undefined || type === 'object') && (schema.anyOf || schema.oneOf)) {
context.validatorSchemasIds.add(location.getSchemaId())
code = 'const errors = []\n'
MoLow marked this conversation as resolved.
Show resolved Hide resolved

if (schema.type === 'object') {
context.wrapObjects = false
Expand All @@ -885,8 +886,9 @@ function buildValue (context, location, input) {
const schemaRef = optionLocation.getSchemaRef()
const nestedResult = buildValue(context, optionLocation, input)
code += `
${index === 0 ? 'if' : 'else if'}(validator.validate("${schemaRef}", ${input}))
${index === 0 ? 'if' : 'else if'}(validator.validate("${schemaRef}", ${input}, errors)) {
${nestedResult}
}
`
}

Expand All @@ -896,7 +898,9 @@ function buildValue (context, location, input) {
}

code += `
else throw new TypeError(\`The value of '${schemaRef}' does not match schema definition.\`)
else throw Object.assign(new TypeError(\`The value of '${schemaRef}' does not match schema definition.\`), {
validationErrors: errors
})
Comment on lines +901 to +903
Copy link
Contributor

Choose a reason for hiding this comment

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

Why not use cause and avoid the Object.assign?

Suggested change
else throw Object.assign(new TypeError(\`The value of '${schemaRef}' does not match schema definition.\`), {
validationErrors: errors
})
else throw new TypeError(\`The value of '${schemaRef}' does not match schema definition.\`, {
cause: errors
})

`
if (schema.type === 'object') {
code += `
Expand Down
6 changes: 4 additions & 2 deletions lib/validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,10 @@ class Validator {
}
}

validate (schemaRef, data) {
return this.ajv.validate(schemaRef, data)
validate (schemaRef, data, errors) {
const valid = this.ajv.validate(schemaRef, data)
if (this.ajv.errors && Array.isArray(errors)) errors.push(...this.ajv.errors)
Eomm marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Contributor

Choose a reason for hiding this comment

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

could this be faster?

Suggested change
if (this.ajv.errors && Array.isArray(errors)) errors.push(...this.ajv.errors)
Array.isArray(errors) && Arrry.prototype.push.apply(errors, this.ajv.errors)

return valid
}

// Ajv does not support js date format. In order to properly validate objects containing a date,
Expand Down
28 changes: 24 additions & 4 deletions test/any.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ test('empty schema on anyOf', (t) => {
})

test('should throw a TypeError with the path to the key of the invalid value /1', (t) => {
t.plan(1)
t.plan(3)

// any on Foo codepath.
const schema = {
Expand Down Expand Up @@ -186,11 +186,21 @@ test('should throw a TypeError with the path to the key of the invalid value /1'

const stringify = build(schema)

t.throws(() => stringify({ kind: 'Baz', value: 1 }), new TypeError('The value of \'#\' does not match schema definition.'))
try {
stringify({ kind: 'Baz', value: 1 })
t.fail('should throw')
} catch (err) {
t.equal(err.message, 'The value of \'#\' does not match schema definition.')
t.same(err.validationErrors, [
Copy link
Contributor

Choose a reason for hiding this comment

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

This would be then:

Suggested change
t.same(err.validationErrors, [
t.same(err.cause, [

{ message: 'must be equal to one of the allowed values', schemaPath: '#/properties/kind/enum', instancePath: '/kind', keyword: 'enum', params: { allowedValues: ['Foo'] } },
{ message: 'must be equal to one of the allowed values', schemaPath: '#/properties/kind/enum', instancePath: '/kind', keyword: 'enum', params: { allowedValues: ['Bar'] } }
])
t.ok(err instanceof TypeError)
}
})

test('should throw a TypeError with the path to the key of the invalid value /2', (t) => {
t.plan(1)
t.plan(3)

// any on Foo codepath.
const schema = {
Expand Down Expand Up @@ -227,5 +237,15 @@ test('should throw a TypeError with the path to the key of the invalid value /2'

const stringify = build(schema)

t.throws(() => stringify({ data: { kind: 'Baz', value: 1 } }), new TypeError('The value of \'#/properties/data\' does not match schema definition.'))
try {
stringify({ data: { kind: 'Baz', value: 1 } })
t.fail('should throw')
} catch (err) {
t.equal(err.message, 'The value of \'#/properties/data\' does not match schema definition.')
t.same(err.validationErrors, [
Copy link
Contributor

Choose a reason for hiding this comment

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

dito

Suggested change
t.same(err.validationErrors, [
t.same(err.cause, [

Copy link
Member

Choose a reason for hiding this comment

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

i think the rationale here was to call it as fastify with ajv implementation:

https://github.com/fastify/fastify/blob/9b3ca58097954c4df20b253906ed6697461e2486/lib/handleRequest.js#L109

{ message: 'must be equal to one of the allowed values', schemaPath: '#/properties/kind/enum', instancePath: '/kind', keyword: 'enum', params: { allowedValues: ['Foo'] } },
{ message: 'must be equal to one of the allowed values', schemaPath: '#/properties/kind/enum', instancePath: '/kind', keyword: 'enum', params: { allowedValues: ['Bar'] } }
])
t.ok(err instanceof TypeError)
}
})