创建 _validate.js校验函数
ajv是6版本,高于此版本,需要查看官网进行API更改
//
const Ajv = require('ajv')
const ajv = new Ajv({
// allErrors: true // 输出所有的错误(比较慢)
})
/**
* json schema 校验
* @param {Object} schema json schema 规则
* @param {Object} data 待校验的数据
*/
function validate(schema, data = {}) {
const valid = ajv.validate(schema, data)
if (!valid) {
return ajv.errors[0]
}
}
module.exports = validate
编写符合jsonschema的校验规则
const validate = require('./_validate')
// 校验规则
const SCHEMA = {
type: 'object',
properties: {
userName: {
type: 'string',
pattern: '^[a-zA-Z][a-zA-Z0-9_]+$', // 字母开头,字母数字下划线
maxLength: 255,
minLength: 2
},
password: {
type: 'string',
maxLength: 255,
minLength: 3
},
newPassword: {
type: 'string',
maxLength: 255,
minLength: 3
},
nickName: {
type: 'string',
maxLength: 255
},
picture: {
type: 'string',
maxLength: 255
},
city: {
type: 'string',
maxLength: 255,
minLength: 2
},
gender: {
type: 'number',
minimum: 1,
maximum: 3
}
}
}
/**
* 校验用户数据格式
* @param {Object} data 用户数据
*/
function userValidate(data = {}) {
return validate(SCHEMA, data)
}
module.exports = userValidate
编写中间件生成函数
const { ErrorModel } = require('../model/ResModel')
const { jsonSchemaFileInfo } = require('../model/ErrorInfo')
/**
* 生成 json schema 验证的中间件
* @param {function} validateFn 验证函数
*/
function genValidator(validateFn) {
async function x(ctx,next) {
const data=validateFn(ctx.request.body)
if(data){
ctx.body = new ErrorModel(jsonSchemaFileInfo)
return
}
await next()
}
return x
}
module.exports = {
genValidator
}
使用中间件生成函数
router.post('/register', genValidator(userValidate), async function (ctx, next) {
const {userName, password, gender} = ctx.request.body;
ctx.body = await register({userName, password, gender})
})