Giter Club home page Giter Club logo

fastify-response-validation's Introduction

@fastify/response-validation

CI NPM version js-standard-style

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.

Install

npm i @fastify/response-validation

Usage

You just need to register the plugin and you will have response validation enabled:

import fastify from 'fastify'

const app = fastify()

await app.register(require('@fastify/response-validation'))

app.route({
  method: 'GET',
  path: '/',
  schema: {
    response: {
      '2xx': {
        type: 'object',
        properties: {
          answer: { type: 'number' }
        }
      }
    }
  },
  handler: async (req, reply) => {
    return { answer: '42' }
  }
})

app.inject({
  method: 'GET',
  path: '/'
}, (err, res) => {
  if (err) throw err
  console.log(res.payload)
})

Different content types responses are supported by @fastify/response-validation, @fastify/swagger and fastify. Please use content for the response otherwise Fastify itself will fail to compile the schema:

{
  response: {
    200: {
      description: 'Description and all status-code based properties are working',
      content: {
        'application/json': {
          schema: { 
            name: { type: 'string' }, 
            image: { type: 'string' }, 
            address: { type: 'string' } 
          }
        }, 
        'application/vnd.v1+json': {
          schema: { 
            fullName: { type: 'string' }, 
            phone: { type: 'string' } 
          }
        }
      }
    }
  }
}

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

import responseValidator from '@fastify/response-validation'

// ... App setup

await fastify.register(responseValidator, {
  ajv: {
    coerceTypes: true
  }
})

You can also pass in an instance of ajv

// Default configuration:
//    coerceTypes: false
//    useDefaults: true
//    removeAdditional: true
//    allErrors: true

import responseValidator from '@fastify/response-validation'
import Ajv from 'ajv'

// ... App setup

const ajv = new Ajv()
await fastify.register(responseValidator, { ajv })

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:

import responseValidator from '@fastify/response-validation'

// ... App setup
await fastify.register(responseValidator, {
  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' }
  }
})

Plugins

You can also extend the functionalities of the ajv instance embedded in this validator by adding new ajv plugins.

fastify.register(require('fastify-response-validation'), {
  ajv: {
    plugins: [
      require('ajv-formats'),
      [require('ajv-errors'), { singleError: false }]
      // Usage: [plugin, pluginOptions] - Plugin with options
      // Usage: plugin - Plugin without options
    ]
  }
})

License

MIT

fastify-response-validation's People

Contributors

dependabot[bot] avatar fdawgs avatar delvedor avatar mcollina avatar eomm avatar uzlopak avatar jsumners avatar metcoder95 avatar dancastillo avatar felixfbecker avatar is2ei avatar climba03003 avatar committomaster avatar nicobuzeta avatar sceccotti89 avatar sleepwalker avatar woh avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.