基于 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])
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'",
}
]
}