Skip to content

Commit

Permalink
improve schema.response validation error message (#3935)
Browse files Browse the repository at this point in the history
  • Loading branch information
evanshortiss committed May 26, 2022
1 parent b1ede58 commit d1dc83d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,19 @@ const {
kSchemaBody: bodySchema,
kSchemaResponse: responseSchema
} = require('./symbols')
const scChecker = /^[1-5]{1}[0-9]{2}$|^[1-5]xx$/

function compileSchemasForSerialization (context, compile) {
if (!context.schema || !context.schema.response) {
return
}

const { method, url } = context.config || {}
context[responseSchema] = Object.keys(context.schema.response)
.reduce(function (acc, statusCode) {
if (!scChecker.exec(statusCode)) {
throw new Error('response schemas should be nested under a valid status code, e.g { 2xx: { type: "object" } }')
}

acc[statusCode] = compile({
schema: context.schema.response[statusCode],
url,
Expand Down
24 changes: 24 additions & 0 deletions test/schema-feature.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1755,3 +1755,27 @@ test('Should coerce the array if the default validator is used', async t => {
t.error(err)
}
})

test('Should return a human-friendly error if response status codes are not specified', t => {
t.plan(2)
const fastify = Fastify()

fastify.route({
url: '/',
method: 'GET',
schema: {
response: {
// This should be nested under a status code key, e.g { 200: { type: 'array' } }
type: 'array'
}
},
handler: (req, reply) => {
reply.send([])
}
})

fastify.ready(err => {
t.equal(err.code, 'FST_ERR_SCH_SERIALIZATION_BUILD')
t.match(err.message, 'Failed building the serialization schema for GET: /, due to error response schemas should be nested under a valid status code, e.g { 2xx: { type: "object" } }')
})
})

0 comments on commit d1dc83d

Please sign in to comment.