• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

molinjun/koa2-validation: A koa2 middleware to validate the request with Joi

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

molinjun/koa2-validation

开源软件地址:

https://github.com/molinjun/koa2-validation

开源编程语言:

JavaScript 100.0%

开源软件介绍:

koa2-validation

npm Build Status Coverage Status Greenkeeper badge

KoaJs Slack

koa2-validation is a koa2 middleware to validate the request with Joi. Support body, params, query for Now.
Inspired by express-validation.

Version Tips

As new version Joi has some breaking changes, some old schema is not workable. To avoid the big change for using legacy koa2-validation version, you need to update your code as follows, if you want to use new version Joi.

// default
const validate = require('koa2-validation');

// with specific Joi 
const joi = require("@hapi/joi");
const Validation = require("koa2-validation").Validation;
const validator = new Validation(joi);
const validate = validator.validate.bind(validator);

Please use the same Joi version when define your joi schema!!!

Usage

Install with npm:

npm i -S koa2-validation

Then, you can use koa2-valition to configure the validation schemas in routes. The example below is to define three validations about user.
file: test/lib/server.js

const http = require('http');
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const router = require('koa-router')();
const validate = require('koa2-validation'); // 1. import the koa2-validation

const user = require('./user');


router.post('/users', validate(user.v.addUser), user.addUser);  // 3. setup the validate middleware
router.get('/users/:id', validate(user.v.getUserInfo), user.getUserInfo);
router.get('/users', validate(user.v.getUserList), user.getUserList);

const app = new Koa();

// error handler
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status || err.code;
    ctx.body = {
      success: false,
      message: err.message,
    };
  }
});
app.use(bodyParser()); // bodyParser should be before the routers
app.use(router.routes());

const server = http.createServer(app.callback());
module.exports = server;

You still need to define the validation schema in your controllers, as follows:
file: test/lib/user.js

const _ = require('lodash');
const Joi = require('joi');

const v = {};
exports.v = v;

const users = [{
  id: '001',
  name: 'dennis1',
  age: 18,
}, {
  id: '002',
  name: 'dennis2',
  age: 20,
}];

// 2. define the validation schema
v.addUser = {
  body: {
    id: Joi.string().required(),
    name: Joi.string(),
    age: Joi.number(),
  },
};
exports.addUser = async (ctx) => {
  const user = ctx.request.body;
  users.push(user);
  ctx.body = { success: true, data: users };
};

The validation schema is followed by Joi. You can define more effective schemas based on joi docs.

Error handler

When bad request, koa2-validation has catched the error, and throw a standard Error instance, which has an attr status 400.

app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status || err.code;
    ctx.body = {
      success: false,
      message: err.message,
    };
  }
});

Example

In the test foler, I made a demo about user management. You can get how to use koa2-validation from it. If you have some questions, you can post an issue.




鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
turboMaCk/koa-sslify: Enforce HTTPS in node.js koa apps发布时间:2022-06-24
下一篇:
moajs/moa2: Moa2 Core = Moajs with koa 2.x发布时间:2022-06-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap