Koa系列-Middleware:koa-validation
2019-06-20
#koa
字数统计:5.2k 字
阅读时长 ≈ 5 分钟
koa-validation
可以用来验证请求体的内容格式。具体的验证是通过 Joi
来实现。
现在来看一下源码吧。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| module.exports = (schema = {}) => { const { opt = {} } = schema; const options = _.defaultsDeep(opt, { allowUnknown: true, }); return async (ctx, next) => { const defaultValidateKeys = ['body', 'query', 'params']; const needValidateKeys = _.intersection(defaultValidateKeys, Object.keys(schema)); const errors = []; needValidateKeys.find((item) => { const toValidateObj = item === 'body' ? ctx.request.body : ctx[item]; const result = Joi.validate(toValidateObj, schema[item], options); if (result.error) { errors.push(result.error.details[0]); return true; } _.assignIn(toValidateObj, result.value); return false; });
if (errors.length !== 0) { throw new ValidationError(errors); } await next(); }; };
|
除此之外还有一个自定义验证错误 ValidationError
。
确实不复杂,但是建议单独使用 Joi
会更灵活。