Package Exports
- koa-superstruct
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (koa-superstruct) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
koa-superstruct
Use the superstruct data validation library as middleware for your koa app.
usage
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
fortitle
but receivedundefined
.
intallation
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. The top-level keys should map to koa's ctx.request
object (ex. body
, query
, headers
) and, failing that, to the ctx
object (ex. ctx.params
).
const schema = struct({
headers: {
'X-Foo': 'string'
},
body: {
'count': 'number'
},
query: {
'page': 'number?'
},
params: {
'slug': 'string'
}
})
validate(schema)