1.0.5 • Published 6 years ago

koa2-joi-validator v1.0.5

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

Koa Joi Validator

A simple validator for koa 2 application, inspired from koa-joi-validator, with Typescript supported

API

A koa middleware which will validate and transform the request

paramtyperequireddescription
optionsobjecttrue
options.typestringDefault to jsonthe coBody parser to call, can be json form or text
options.failureint(ctx: Context, err: ValidationError) => anyfalseThe error code or function 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

Requirement

  • NodeJS >= 7.6 is required.
  • Joi

Installation

Install using npm:

npm install koa2-joi-validator joi

Usage

import { KoaJoiValidator } from "koa2-joi-validator";
import * as Joi from "joi";


router.post('/:number/:string/:date',
  KoaJoiValidator({
    type: 'json',
    params: {
      number: Joi.number().required(),
      string: Joi.string().required(),
      date: Joi.string().isoDate().required()
    },
    body: {
      number: Joi.number().required(),
      string: Joi.string().required(),
      date: Joi.string().isoDate().required()
    },
    headers: Joi.object({
      number: Joi.number().required(),
      string: Joi.string().required(),
      date: Joi.string().isoDate().required()
    }).options({ allowUnknown: true }),
    query: {
      number: Joi.number().required(),
      string: Joi.string().required(),
      date: Joi.string().isoDate().required()
    },
    failure(ctx: Koa.Context, err: Joi.ValidationError) {
      console.log(err);
      ctx.throw(400);
      
    }
  }),
  (ctx: Koa.Context) => {
    expect(typeof ctx.params.number === 'number');
    expect(typeof ctx.params.string === 'string');
    expect(ctx.params.date instanceof Date);

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

    ctx.status = 204;
  },
  
);