A simple plugin that enables response validation for Fastify.
The use of this plugin will slow down your overall performance, so we suggest using it only during development.
npm i fastify-response-validation
You just need to register the plugin and you will have response validation enabled:
const fastify = require('fastify')()
fastify.register(require('fastify-response-validation'))
fastify.route({
method: 'GET',
path: '/',
schema: {
response: {
'2xx': {
type: 'object',
properties: {
answer: { type: 'number' }
}
}
}
},
handler: async (req, reply) => {
return { answer: '42' }
}
})
fastify.inject({
method: 'GET',
path: '/'
}, (err, res) => {
if (err) throw err
console.log(res.payload)
})
If you want to override the default ajv configuration, you can do that by using the ajv
option:
// Default configuration:
// coerceTypes: false
// useDefaults: true
// removeAdditional: true
// allErrors: true
// nullable: true
fastify.register(require('fastify-response-validation'), {
ajv: {
coerceTypes: true
}
})
By default the response validation is enabled on every route that has a response schema defined. If needed you can disable it all together with responseValidation: false
:
fastify.register(require('fastify-response-validation'), {
responseValidation: false
})
Alternatively, you can disable a specific route with the same option:
fastify.route({
method: 'GET',
path: '/',
responseValidation: false,
schema: {
response: {
'2xx': {
type: 'object',
properties: {
answer: { type: 'number' }
}
}
}
},
handler: async (req, reply) => {
return { answer: '42' }
}
})