Skip to content

Latest commit

 

History

History
102 lines (84 loc) · 2.57 KB

README.zh-CN.md

File metadata and controls

102 lines (84 loc) · 2.57 KB

egg-validate-schema

NPM version build status Test coverage David deps Known Vulnerabilities npm download

基于 ajv, 通过 JSON Schema 校验数据方法。

安装

$ npm i egg-validate-schema --save

使用

// {app_root}/config/plugin.js
exports.validateSchema = {
  package: 'egg-validate-schema',
};

配置

完整支持 ajv 配置,具体参考

// {app_root}/config/config.{env}.js
exports.validateSchema = {
  // allErrors: true,
  // v5: true,
};

使用方法

  • ctx.validateBySchema(jsonSchema[, data])

默认验证请求 Body

const jsonSchema = {
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "info": {
      "type": "object"
    }
  },
  "required": [
    "name",
    "info"
  ],
};

exports.create = function* () {
  // 校验失败自动返回 422 响应
  this.validateBySchema(jsonSchema);
  // 可以传递自己处理过的数据,默认使用 this.request.body
  // this.validateBySchema(jsonSchema[, your_data]);
  // 校验通过
  this.body = this.request.body;
};

如果验证失败,会返回:

HTTP/1.1 422 Unprocessable Entity

{
  "message": "Validation Failed",
  "errors": [
    {
      "keyword": "required",
      "dataPath": "",
      "schemaPath": "#/required",
      "params": { missingProperty: 'name' },
      "message": "should have required property 'name'",
    }
  ]
}