Skip to content

fastify/fastify-response-validation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

fastify-response-validation

Node.js CI js-standard-style

A simple plugin that enables response validation for Fastify.
The use of this plugin will slow down your overall performances, so we suggest using it only during development.

Install

npm i fastify-response-validation

Usage

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
  }
})

License

MIT