4.0.0 • Published 7 years ago

koa-joi-validator v4.0.0

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

koa-joi-validator

A simple validator for your awesome koa application

API

validator.Joi The package Joi version (prefer this version over your custom version in case of breaking changes)

validator.validate(options) A koa middleware which will validate and transform the request

paramtyperequireddescription
options{}true
options.typestringOnly if you want the request body to be parsedthe coBody parser to call, can be json form or text
options.failureintfalseThe error code to throw on case of validation error, default to 400
options.options{}falseOptions 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

router.post('/:number/:string/:date',
  validator.validate({
    type: 'json',
    params: {
      number: validator.Joi.number().required(),
      string: validator.Joi.string().required(),
      date: validator.Joi.date().required()
    },
    body: {
      number: validator.Joi.number().required(),
      string: validator.Joi.string().required(),
      date: validator.Joi.date().required()
    },
    headers: validator.Joi.object({
      number: validator.Joi.number().required(),
      string: validator.Joi.string().required(),
      date: validator.Joi.date().required()
    }).options({ allowUnknown: true }),
    query: {
      number: validator.Joi.number().required(),
      string: validator.Joi.string().required(),
      date: validator.Joi.date().required()
    }
  }),
  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;
  }
);
5.1.3

7 years ago

5.1.2

7 years ago

5.0.2

8 years ago

5.0.1

8 years ago

5.0.0

8 years ago

4.0.0

8 years ago

3.0.1

8 years ago

3.0.0

8 years ago

2.0.1

8 years ago

2.0.0

8 years ago

1.1.0

8 years ago

1.0.0

8 years ago