koa-joi-bouncer
An http parameter validation library for Koa web apps
Last updated 8 months ago by psypersky .
ISC · Repository · Bugs · Original npm · Tarball
$ cnpm install koa-joi-bouncer 
SYNC missed versions from official npm registry.

Koa-joi-bouncer

An http parameter validation library for Koa.js web apps

npm install --save koa-joi-bouncer

The idea

Separate the validation logic from the route itself, just define an schema and use it before the route.

Koa 2

If you want to use it with koa v2 use the tag 'next'

npm install --save koa-joi-bouncer@next

Usage

const koa = require('koa');
const app = new koa();
const Router = require('koa-router');
const koaJoiBouncer = require('koa-joi-bouncer');
const Joi = koaJoiBouncer.Joi;

const router = new Router();

const myRouteValidation = koaJoiBouncer.middleware({
  body: Joi.object().keys({
     username: koaJoiBouncer.string().alphanum().min(3).max(30).required(),
  }),
  headers: Joi.object().keys({
    foo: koaJoiBouncer.string().required().
  }),
});

const myRoute = function* myRouter(next) {
  this.response.body = `Hello there ${this.request.body.username}`;
}

router.post('/myroute', myRouteValidation, myRoute);

app.use(function* onValidationError(next) {
  try {
    yield next;
  } catch (e) {
    if (!e.isJoi) {
      throw e;
    }
    this.response.body = {
      status: 'fail',
      details: e.details,
    };
    this.response.status = 400;
  }
});

app.use(router.routes()).use(router.allowedMethods());

app.listen(3000);

Check the tests for more examples

TODO:

Maintainers (1)
Downloads
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 0
Dependencies (2)
Dev Dependencies (9)
Dependents (0)
None

Copyright 2014 - 2017 © taobao.org |