Skip to content

frontdog/egg-jsonschema

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

egg-jsonschema

基于 jsonschema 提供数据校验方法。

安装

$ npm i egg-jsonschema --save

配置

// {app_root}/config/plugin.js
exports.jsonschema = {
  enable: true,
  package: 'egg-jsonschema',
};

使用方法

  • ctx.validate(rule[, data])

默认验证请求 Body

const Controller = require('egg').Controller;

const createSchema = {
  type: 'object',
  properties: {
    name: {
      type: 'string',
      required: true
    }
  }
};

class AppController extends Controller {
  async create() {
    // 校验失败自动返回 422 响应
    this.validate(createSchema);
    // 可以传递自己处理过的数据,默认使用 this.request.body
    // this.validate(createRule[, your_data]);
    // 校验通过
    this.body = {
      code: 200,
      result: {
        pass: true,
      },
    };
  }
}

如果验证失败,会返回:

{
  "message": "Validation Failed",
  "errors": [
    ...
  ]
}

About

egg validator

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published