koa-dee-validator

2.0.1 • Public • Published

Koa Dee Validator

npm npm Coverage Status dependency Status devDependency Status Build Status Known Vulnerabilities node

Dee-validator port for Koa framework.

Table of contents

Migration to v2

The v1 doesn't support async validators meaning the API is synchronous. For migration to v2, await getErrors and hasErrors methods.

Usage

The middleware creates validator which contains three dee-validators for ctx.request.body, ctx.params and ctx.request.query objects. You can use each validator separately.

The example of code:

const Koa = require('koa');
const validator = require('koa-dee-validator');

const app = new Koa();
const customValidators = { // custom validators
    isTestString: {
        execute: value => value === 'test'
    }
}

app.use(validator(customValidators));

app.use(async (ctx, next) => {
    const validator = ctx.validator;
    const { bodyValidator, paramsValidator, queryValidator } = validator;

    console.log(validator.context); // you can get context object from the ctx.validator

    bodyValidator.property('name').isNotEmpty().isTestString();

    paramsValidator.property('id').isNotEmpty();

    if (await validator.hasErrors()) { // return true in case if no errors in body, params and query validators
      return Promise.reject({
        errors: await validator.getErrors() // here you can get errors from all of the validators
      });
    } else {
      return next();
    }
})

You can find more details about creation of custom validators and dee-validator usage here.

Example of errors format:

{
    'name': {
        param: 'name',
        message: 'name should be a string',
        value: 0
    },
    'id': {
        param: 'id',
        message: 'id should be an integer',
        value: 'test'
    }
}

What's in a name?

Dee is one of my favorite detective characters - Judge Dee.

Author

Ilya Markevich - @ilya_mark91

Package Sidebar

Install

npm i koa-dee-validator

Weekly Downloads

0

Version

2.0.1

License

MIT

Unpacked Size

8.48 kB

Total Files

6

Last publish

Collaborators

  • ilya.markevich