npm.io
3.0.2 • Published 6 months ago

koa-dee-validator

Licence
MIT
Version
3.0.2
Deps
2
Size
7 kB
Vulns
0
Weekly
0

Koa Dee Validator

npm npm

Dee-validator port for Koa framework.

Table of contents

Migration to v2-v3

The v1 doesn't support async validators meaning the API is synchronous. For migration to v2-v3, 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'
    }
}

Author

Ilya Markevich