fastify-split-validator
is a plugin which allows you to setup, granularly, different validates per HTTP part of the request. This works at a route level, doing a fallback into a default validator using the default server config from the instance where the plugin is being installed.
You can provide your own default validator to act as fallback in case this is not defined within the definition of the route (by default uses Ajv@8 as default fallback).
Install by running npm install fastify-split-validator
.
Instance
defaultValidator
: default validator to be used as fallback in case nothing is provided at a route level definition
Example:
const fastify = require('fastify');
const splitValidator = require('fastify-split-validator');
const Ajv = require('ajv');
const app = fastify();
const validator = new Ajv({});
await app.register(splitValidator, { defaultValidator: validator });
Note: It is important to advice that with the new fastify@v4, all the route registration now happens asynchronously. This change translates in a way that if any plugin is meant to set logic into the
onRoute
hook for manipulating routes after registration, it is necessary to await until the plugin is fully loaded before proceeding with the next parts of your route definition. Otherwise, this can lead to non-deterministic behaviours when the plugin will not the expected effect on your fastify application.
On Route
schemaValidators
: an object with the HTTP parts as keys and the validators to be used for that part as valuesschemaValidators.body
: validator to be used for the body of the requestschemaValidators.params
: validator to be used for the params of the requestschemaValidators.headers
: validator to be used for the headers of the requestschemaValidators.querystring
: validator to be used for the querystring of the requestschemaValidators.query
: alias forschemaValidators.querystring
import fastify from 'fastify';
import splitValidator from 'fastify-split-validator';
import Ajv from 'ajv';
const app = fastify();
const validator = new Ajv({});
const bodyValidator = new Ajv({});
const headersValidator = new Ajv({});
await app.register(splitValidator, { defaultValidator: validator });
app.post('/', {
config: {
schemaValidators: {
body: bodyValidator,
headers: headersValidator,
},
},
}, (req, reply) => {
// ...
});
const fastify = require('fastify');
const splitValidator = require('fastify-split-validator');
const Ajv = require('ajv');
const app = fastify();
const validator = new Ajv({});
const bodyValidator = new Ajv({});
const headersValidator = new Ajv({});
await app.register(splitValidator, { defaultValidator: validator });
app.post('/', {
config: {
schemaValidators: {
body: bodyValidator,
headers: headersValidator,
},
},
}, (req, reply) => {
// ...
});
See test for more examples.