https://github.com/expresso/validator
JSON Schema validation middleware for Expresso
https://github.com/expresso/validator
json-schema schema validation validator
Last synced: about 1 month ago
JSON representation
JSON Schema validation middleware for Expresso
- Host: GitHub
- URL: https://github.com/expresso/validator
- Owner: expresso
- License: mit
- Created: 2018-10-02T20:56:38.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2024-08-27T21:36:37.000Z (9 months ago)
- Last Synced: 2025-03-11T11:48:12.107Z (2 months ago)
- Topics: json-schema, schema, validation, validator
- Language: TypeScript
- Size: 756 KB
- Stars: 6
- Watchers: 1
- Forks: 1
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Expresso Validator
> JSON Schema validation middleware for [Expresso](https://github.com/expresso)
## Summary
- [Expresso Validator](#expresso-validator)
- [Summary](#summary)
- [What is this](#what-is-this)
- [Basic Usage](#basic-usage)
- [Validating queries](#validating-queries)
- [validateType function](#validatetype-function)
- [Errors](#errors)## What is this
This middleware validates an input against a [JSON Schema](https://json-schema.org) and automatically throws a boom error for `badData` (which is HTTP code `422 - Unprocessable Entity`) if this input is not matched.
## Basic Usage
**Install**:
```sh
$ npm i @expresso/validator
```**Import and use**:
```ts
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) => { // ... // })
```### Validating queries
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:
```ts
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 function
`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](https://www.npmjs.com/package/@expresso/ts-transformer-type-validator)## Errors
This validator follows Expresso's directives and returns a [Boom](https://github.com/hapijs/boom) error for BadData, right now it is not possible to change this behavior