1.0.7 • Published 7 years ago

koa-joi-bouncer v1.0.7

Weekly downloads
7
License
ISC
Repository
github
Last release
7 years ago

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:

1.0.7

7 years ago

2.0.8

7 years ago

0.0.7

7 years ago

0.0.6

7 years ago

0.0.5

7 years ago