restify-ajv-middleware
v0.0.3
Published
json-schema middleware for restify using ajv for validation.
Downloads
47
Readme
restify-ajv-middleware
A json-schema validation middleware for restify using ajv. Inspired by restify-joi-middleware
Installation
npm install restify-ajv-middleware --save
Usage
const restify = require('restify')
const validator = require('restify-ajv-middleware')
const server = restify.createServer()
server.use(validator(/* options */))
server.get({
path: '/:id',
validation: {
params: {
type: 'object',
properties: { id: { type: 'number' } },
required: [ 'id' ],
additionalProperties: false
}
}
}, (req, res) => {
return res.send(200, { id: req.params.id })
});
Options
- keysToValidate: override the default keys to validate against
server.use(validator({
// changes the request keys validated
keysToValidate: ['params', 'body', 'query', 'user', 'headers', 'trailers'],
});
- errorResponder: a function in the form
(transformedErr, req, res, next)
used to modify the default response strategy after failed validation.
server.use(validator({
// changes how errors are returned
errorResponder: (transformedErr, req, res, next) => {
res.send(400, transformedErr)
return next()
}
});
- errorTransformer: a function in the form
(validationInput, errors)
, used to transform the error generated after failed validation
server.use(validator({
// changes how json-schema errors are transformed
errorTransformer: (validationInput, errors) => new restifyErrors.BadRequestError('Something else'),
});
- ajv: options passed to the internal ajv instance. See options for more info.