https://github.com/timwis/koa-superstruct
Use the superstruct data validation library as middleware for your koa app.
https://github.com/timwis/koa-superstruct
Last synced: 24 days ago
JSON representation
Use the superstruct data validation library as middleware for your koa app.
- Host: GitHub
- URL: https://github.com/timwis/koa-superstruct
- Owner: timwis
- Created: 2018-02-10T16:38:51.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2018-08-28T19:23:42.000Z (over 6 years ago)
- Last Synced: 2025-03-25T08:42:46.922Z (about 1 month ago)
- Language: JavaScript
- Homepage:
- Size: 6.84 KB
- Stars: 9
- Watchers: 1
- Forks: 2
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# koa-superstruct
Use the [superstruct][superstruct] data validation library as middleware for your [koa][koa] app.## usage
```javascript
const { struct } = require('superstruct')
const validate = require('koa-superstruct')const schema = struct({
body: {
id: 'number',
title: 'string',
isPublished: 'boolean?',
tags: ['string'],
author: {
id: 'number'
}
}
})router.post('/entry', validate(schema), handler)
```If validation fails, it throws an HTTP 422 error (Unprocessable Entity) with descriptive message, ex:
> Expected a value of type `string` for `title` but received `undefined`.
## intallation
```bash
npm install koa-superstruct
```
Install `superstruct` separately, allowing you to pass custom types and avoid peer dependency.## api
### `validate`
`validate(schema: Function) => Function`Accepts a [Struct validator function][validator-function]. The top-level keys should map to koa's [`ctx.request` object][request-object] (ex. `body`, `query`, `headers`) and, failing that, to the `ctx` object (ex. `ctx.params`).
```javascript
const schema = struct({
headers: {
'X-Foo': 'string'
},
body: {
'count': 'number'
},
query: {
'page': 'number?'
},
params: {
'slug': 'string'
}
})
validate(schema)
```[superstruct]: https://github.com/ianstormtaylor/superstruct
[koa]: https://github.com/koajs/koa
[validator-function]: https://github.com/ianstormtaylor/superstruct/blob/master/docs/reference.md
[request-object]: http://koajs.com/#request