Why do we need to do calibration parameters
In development, whether App
developed or 服务器接口
developing, we are unable to predict the incoming user data, 参数(数据)校验
it is an integral part of the development.
For example, like App
to submit registration page login form, we must do a good job judge layers. Such 用户名是否为空,用户密码是否为空,密码长度是否足够等等
as: .
Is there a more elegant way to achieve it?
How to achieve elegance
Used herein are based validator.js package Lin-Validator
, the source is 七月老师
provided.
Lin-Validator
It has the features:
- Calibration parameters,
header,query,path,body
all calibration parameters
Parameter check
Validator statement:
const { LinValidator, Rule } = require('lin-mizar');
/**
* 正整数 参数校验
*/
class PositiveIntegerValidator extends LinValidator {
constructor() {
// 使用 this 一定要使用 super
super()
// 数组,且关系,也就是数组中所有都满足才能通过
this.id = [
new Rule('isInt', '需要是正整数', {
min: 1
}),
]
}
}
/**
* 更新用户信息
*/
class UpdateInfoValidator extends LinValidator {
constructor () {
super();
this.email = [
new Rule('isOptional'),
new Rule('isEmail', '电子邮箱不符合规范,请输入正确的邮箱')
];
this.nickname = [
new Rule('isOptional'),
new Rule('isLength', '昵称长度必须在2~10之间', 2, 10)
]
}
}
module.exports = {
PositiveIntegerValidator,
UpdateInfoValidator
};
Custom alias
// 获取书籍的喜欢状态
router.get('/like', new Auth().m, async ctx => {
// 接口中传递的参数是`bkid`,为了复用 PositiveIntegerValidator 对 id 的校验
// 这里使用了自定义别名 id: 'bkid' 来完成验证器的调用
const v =await new PositiveIntegerValidator().validate(ctx, {
id: 'bkid'
})
const like = await Like.userLikeIt(
ctx.auth.uid, v.get('query.bkid'))
ctx.body = like
})
Detailed use
By npm
using the installation lin-mizar
In package.json
add lin-mizar
initialization can be of:
"dependencies": {
"lin-mizar": "^0.2.1"
}
Introduced in the file you want to use Validator
const { Rule, LinValidator, isNotEmpty } = require('lin-mizar');
[ Details Reference: TaleLin / lin-cms-koa in /app/validators/
], it is convenient to easily spot a star
support wave.
Advice please add micro letter: Light to tease.