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

improve schema.response validation error message #3935

Merged
merged 4 commits into from
May 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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" } }')
})
})