feat: 添加请求参数验证中间件和设计令牌Hook
feat(validation): 为机房、机柜和设备路由添加Joi验证中间件 feat(hooks): 创建useDesignTokens Hook集中管理主题配置 feat(models): 为耗材模型添加乐观锁version字段和updatedAt索引 feat(3d): 增强3D场景和设备模型视觉效果与交互 refactor: 移除数据备份相关功能并优化代码结构 fix: 修复前端安全日志和密码加密工具 chore: 更新依赖并添加axios和joi库 docs: 更新注释和文档说明 style: 改进代码格式和命名一致性
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* 请求参数验证中间件
|
||||
* 使用Joi进行参数校验
|
||||
*/
|
||||
|
||||
const validate = (schema, source = 'body') => {
|
||||
return (req, res, next) => {
|
||||
const data = source === 'query' ? req.query : req.body;
|
||||
|
||||
const { error, value } = schema.validate(data, {
|
||||
abortEarly: false, // 返回所有错误
|
||||
stripUnknown: true, // 移除未定义的字段
|
||||
allowUnknown: source === 'query' // 查询参数允许未知字段
|
||||
});
|
||||
|
||||
if (error) {
|
||||
const errorMessages = error.details.map(detail => ({
|
||||
field: detail.path.join('.'),
|
||||
message: detail.message
|
||||
}));
|
||||
|
||||
return res.status(400).json({
|
||||
error: '参数验证失败',
|
||||
details: errorMessages
|
||||
});
|
||||
}
|
||||
|
||||
// 将验证后的值替换到请求对象
|
||||
if (source === 'query') {
|
||||
req.query = value;
|
||||
} else {
|
||||
req.body = value;
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
};
|
||||
|
||||
// 验证查询参数
|
||||
const validateQuery = (schema) => validate(schema, 'query');
|
||||
|
||||
// 验证请求体
|
||||
const validateBody = (schema) => validate(schema, 'body');
|
||||
|
||||
module.exports = {
|
||||
validate,
|
||||
validateQuery,
|
||||
validateBody
|
||||
};
|
||||
Reference in New Issue
Block a user