Node/Koa2[49]: 微博数据校验
·
Yin灏
src/validator/blog.js
const validate = require("./_validate");
const SCHEMA = {
type: "object",
properties: {
content: {
type: "string",
},
image: {
type: "string",
maxLength: 255,
},
},
};
function blogValidate(data = {}) {
return validate(SCHEMA, data);
}
module.exports = blogValidate;
使用格式校验
src/routes/api/blog-home.js
const router = require("koa-router")();
const { loginCheck } = require("../../middlewares/loginChecks");
const { create } = require("../../controller/blog-home");
const { genValidator } = require("../../middlewares/validator");
const blogValidate = require("../../validator/blog");
router.prefix("/api/blog");
router.post(
"/create",
loginCheck,
genValidator(blogValidate),
async (ctx, next) => {
const { content, image } = ctx.request.body;
const { id: userId } = ctx.session.userInfo;
// controller 层
ctx.body = await create({
userId,
content,
image,
});
}
);
module.exports = router;