封装函数:
const { ErrorModel } = require("../model/resModel");
function schema(method, schemas) {
async function validateSchema(ctx, next) {
let data = null;
if (method === "get") {
data = await ctx.request.query;
} else {
data = await ctx.request.body;
}
const { error } = schemas.validate(data);
if (error) {
ctx.body = new ErrorModel(error.message);
return;
}
await next();
}
return validateSchema;
}
module.exports = schema;
规则:
/**
* string() 值必须是字符串
* alphanum() 值只能是包含 a-zA-Z0-9 的字符串
* min(length) 最小长度
* max(length) 最大长度
* required() 值是必填项,不能为 undefined
* pattern(正则表达式) 值必须符合正则表达式的规则
*/
const Joi = require("joi");
const user = Joi.object({
username: Joi.string().alphanum().min(1).max(10).required(),
password: Joi.string()
.pattern(/^[\S]{6,12}$/)
.required()
});
module.exports = {
user
};
路由:
const Router = require("koa-router");
const { regUser, blogList, login } = require("../controllers/user");
const schema = require("../model/schema");
// 导入 Joi 来定义验证规则
const { user } = require("../schema/user");
// const upload = require("../model/upload");
const router = new Router({ prefix: "/api/user" });
// 查询博客信息
router.get("/bloglist", blogList);
// 注册
router.post("/reguser", schema("post", user), regUser);
// 上传头像
// router.post("/upload", upload.single("avatar"), ctx => {
// console.log("ctx.request.file", ctx.request.file);
// console.log("ctx.file", ctx.file.path);
// console.log("ctx.request.body", ctx.request.body);
// ctx.body = "done";
// });
// 登录
router.post("/login", login);
module.exports = router;