Koa middlewares that leverages schm to parse and validate request query and body.
$ npm install --save schm-koa
const koa = require('koa')
const bodyParser = require('koa-bodyparser')
const { query, body, errorHandler } = require('schm-koa')
const app = new Koa()
app.use(bodyParser())
app.use(errorHandler())
app.use(query({ foo: { type: Boolean, required: true } }))
app.use(body({ foo: Boolean }))
app.use((ctx) => {
console.log(ctx.state.query)
console.log(ctx.state.body)
})
Returns a koa middleware that validates and parses querystring based on a given schema.
params
Object
const Koa = require('koa')
const { query } = require('schm-koa')
const app = new Koa()
app.use(query({ foo: Boolean, bar: [String] }))
// request /?foo&bar=1&bar=baz
app.use((ctx) => {
console.log(ctx.state.query) // { foo: true, bar: ['1', 'baz'] }
})
Returns a koa middleware that validates and parses request body based on a given schema.
params
Object
const Koa = require('koa')
const bodyParser = require('koa-bodyparser')
const { body } = require('schm-koa')
const app = new Koa()
app.use(bodyParser())
app.use(body({ foo: Boolean, bar: [String] }))
// send { foo: 1, bar: 'baz' }
app.use((ctx) => {
console.log(ctx.state.body) // { foo: true, bar: ['baz'] }
})
Handles errors from schm-koa.
const Koa = require('koa')
const { query, errorHandler } = require('schm-koa')
const app = new Koa()
app.use(errorHandler())
app.use(query({ foo: { type: Boolean, required: true } }))
// request / without querystring
app.use((ctx) => {
...
})
// it will respond with 400 and error descriptor in response body
MIT © Diego Haz