egg-validate-jsonschema
v1.0.1
Published
JSON Schema validate plugin for egg
Downloads
5
Readme
egg-validate
基于 JSON Schema + AJV 的校验中间件,致力于:
- 前后端公用校验规则
- 保证前后端校验一致
- 减少规则编写成本
依赖说明
依赖的 egg 版本
egg-validate 版本 | egg 1.x --- | --- 1.x | 😁 0.x | ❌
依赖的插件
开启插件
// config/plugin.js
exports.validate = {
enable: true,
package: 'egg-validate',
};
方式
服务器端
中间件校验处理
// router
// 在需要校验处理的路由,开启中间件,中间件会自己校验,如果校验失败,返回失败信息
module.exports = app => {
const { router, controller } = app
const validator = app.middleware.validate(app.config.validate, app)
router.post('/', validator, controller.home.index)
}
// /app/validate/test.json
{
"$id": "login",
"type": "object",
"properties": {
"phone": {
"title": "手机",
"type: "string"
}
},
"required": [
"phone"
]
}
// 错误信息
http.request('/').post({
validateSchema: 'test' // config配置,指定的schema路径
})
// response
{
success: false,
errors: [
{
...
message: "手机不能为空"
}
]
}
Controller自己处理错误
接上栗
// home Controller
async index () => {
if (body.formValidate) {
return {
success: true,
message: '手机是必填项哦'
}
}
}
http.request('/').post({
validateSchema: 'test', // config配置,指定的schema路径
validateBySelf: true // config配置,由Controller自己处理错误
})
// response
{
success: true,
message: '手机是必填项哦'
}
浏览器端
请求 Schema
exports.validateSchema = {
uri: '/api/schema' // 配置项,指定了通过请求schema路由
}
axios.get('/api/schema?id=test').then(res => {
res === {
success: truem
data: {
"$id": "login",
"type": "object",
"properties": {
"phone": {
"title": "手机",
"type: "string"
}
},
"required": [
"phone"
]
}
}
})
详细配置
请到 config/config.default.js 查看详细配置项说明。
单元测试
提问交流
请到 egg issues 异步交流。