3.0.0 • Published 6 years ago

koa-superstruct v3.0.0

Weekly downloads
12
License
MIT
Repository
github
Last release
6 years ago

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 for title but received undefined.

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)