Skip to content

Latest commit

 

History

History

schm-koa

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 

schm-koa

NPM version

Koa middlewares that leverages schm to parse and validate request query and body.

Install

$ npm install --save schm-koa

Usage

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)
})

API

Table of Contents

query

Returns a koa middleware that validates and parses querystring based on a given schema.

Parameters

Examples

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'] }
})

body

Returns a koa middleware that validates and parses request body based on a given schema.

Parameters

Examples

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'] }
})

errorHandler

Handles errors from schm-koa.

Examples

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

License

MIT © Diego Haz