Use the superstruct data validation library as middleware for your koa app.
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
stringfortitlebut receivedundefined.
npm install koa-superstructInstall superstruct separately, allowing you to pass custom types and avoid peer dependency.
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)