koa-better-validator

a koa validator middleware

Downloads
19
Stars
1
Committers
2

Installation


The library was inspired by the validator.js.

$ npm i koa-better-validator -S

or

$ yarn add koa-better-validator -S

Usage


const Koa = require('koa')
const { koaValidator, KoaValidatorException } = require('koa-better-validator')
const app = new Koa()

// catch exception
app.use(async (ctx, next) => {
  try {
    await next()
  } catch (e) {
    if(e instanceof KoaValidatorException) {
      ctx.body = {
        errMsg: e.errMsg || 'This is koa-better-validator catch errors'
      } 
    }
  } 
})

// customize you validator
app.use(koaValidator({
  customValidators: {
    isString (param) {
      return Object.prototype.toString.call(param) === '[object String]' ? param : false;
    }
    // other customValidators
}
}))

app.use(async (ctx, next) => {
  // The method verify will automatically identify from body、params、query、header
  // ctx.query, ctx.params, ctx.request.body(if you have used a library like koa-bodyparser), headers
  ctx.verify('name', 'the name length should be between 6 and 10 ').isLength({min: 6, max: 10})
  const { name } = await ctx.valid()
  console.log(name)
  await next()
})

app.listen(3000)