JSON Schema validation middleware for Expresso
This middleware validates an input against a JSON Schema and automatically throws a boom error for badData
(which is HTTP code 422 - Unprocessable Entity
) if this input is not matched.
Install:
$ npm i @expresso/validator
Import and use:
import { validate } from '@expresso/validator'
// Your expresso initialization here
const schema = {
type: 'object',
properties: {
name: {
type: 'string'
},
age: {
type: 'integer'
}
},
additionalProperties: false,
required: ['name', 'age']
}
app.post('/users', validate(schema), (req: Reques, res: Response, next: NextFunction) => { // ... // })
By default, the validator will match the schema against the body of the request, this is why the root type is { type: 'object' }
. It is also possible to validate the query string params:
import { validate } from '@expresso/validator'
// Your expresso initialization here
const schema = {
type: 'object',
properties: {
name: {
type: 'string'
},
age: {
type: 'integer'
}
},
required: ['name', 'age']
}
app.get('/users', validate.query(schema), (req: Reques, res: Response, next: NextFunction) => { // ... // })
This will validate the whole query string against the given schema.
validateType
is actually a dummy function that should be removed in runtime. It exists to give type
safety for using @expresso/ts-transformer-type-validator
This validator follows Expresso's directives and returns a Boom error for BadData, right now it is not possible to change this behavior