0.0.4 • Published 6 years ago

koa-joi-mw v0.0.4

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

koa-joi-mw

Koa middleware to validate requests against joi schemas.

API

const validate = require('koa-joi-mw');

validate(options)

A koa middleware which will validate and transform the request

paramtyperequireddescription
optionsobjecttrue
options.failCodenumberfalseThe error code to throw in case of validation error, defaults to 400
options.optionsobjectfalseOptions passed to Joi validator, such as allowUnknown
options.bodyJoi.objectfalseA joi schema validated against the request body
options.paramsJoi.objectfalseA joi schema validated against the request params
options.headersJoi.objectfalseA joi schema validated against the request headers
options.queryJoi.objectfalseA joi schema validated against the request query

Usage

const joi = require('joi'),
  validate = require('koa-joi-mw');

router.post('/:number/:string/:date',
  validate({
    params: joi.object({
      number: joi.number().required(),
      string: joi.string().required(),
      date: joi.date().required()
    }),
    body: joi.object({
      number: joi.number().required(),
      string: joi.string().required(),
      date: joi.date().required()
    }),
    headers: joi.object({
      number: joi.number().required(),
      string: joi.string().required(),
      date: joi.date().required()
    }),
    query: joi.object({
      number: joi.number().required(),
      string: joi.string().required(),
      date: joi.date().required()
    }),
    options: { allowUnknown: true }
  }),
  function * () {
    this.assert(typeof this.params.number === 'number');
    this.assert(typeof this.params.string === 'string');
    this.assert(this.params.date instanceof Date);

    ['body', 'headers', 'query'].forEach(el => {
      this.assert(typeof this.request[el].number === 'number');
      this.assert(typeof this.request[el].string === 'string');
      this.assert(this.request[el].date instanceof Date);
    });

    this.status = 204;
  }
);
0.0.4

6 years ago

0.0.3

7 years ago

0.0.1

7 years ago