Joi是什么?
官方文档描述是:joi lets you describe your data using a simple, intuitive, and readable language.
简单理解就是:可以简单直接描述你的数据模型的语言。
所以重点是描述,然后校验很简单。
官方文档地址:https://joi.dev/api/?v=17.4.0
安装
在项目目录里执行 npm i joi
试用环境
@google-cloud/functions-framework
简单试用
对一个字符串型参数进行校验
代码如下:
const Joi = require('joi');
const schema = Joi.object({
username: Joi.string()
.alphanum()
.min(3)
.max(30)
})
exports.helloWorld = (req, res) => {
const { error, value } = schema.validate(req.query)
if (error) {
return res.status(422).json({ error: error })
}
res.send('Hello, World')
}
效果如下:
访问 http://localhost:8080/
返回 Hello, World
访问 http://localhost:8080/?username=aaaa
返回 Hello, World
访问 http://localhost:8080/?username=aa
返回
{
"error": {
"_original": {
"username": "aa"
},
"details": [
{
"message": "\"username\" length must be at least 3 characters long",
"path": [
"username"
],
"type": "string.min",
"context": {
"limit": 3,
"value": "aa",
"label": "username",
"key": "username"
}
}
]
}
}
访问 http://localhost:8080/?username=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
返回
{
"error": {
"_original": {
"username": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
},
"details": [
{
"message": "\"username\" length must be less than or equal to 30 characters long",
"path": [
"username"
],
"type": "string.max",
"context": {
"limit": 30,
"value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"label&