Files
steel_prices_service/src/middlewares/validator.js
2026-01-06 09:19:12 +08:00

127 lines
2.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 请求验证中间件
*/
/**
* 验证查询价格请求
*/
function validatePriceQuery(req, res, next) {
const { region, date } = req.query;
// 地区参数验证
if (!region) {
return res.status(400).json({
success: false,
message: '缺少必需参数: region地区'
});
}
// 日期格式验证(如果提供)
if (date && !isValidDate(date)) {
return res.status(400).json({
success: false,
message: '日期格式无效,应为 YYYY-MM-DD'
});
}
next();
}
/**
* 验证搜索请求
*/
function validateSearch(req, res, next) {
const { material, specification, startDate, endDate, page, pageSize } = req.query;
// 至少需要一个搜索条件
if (!material && !specification && !startDate && !endDate) {
return res.status(400).json({
success: false,
message: '至少提供一个搜索条件: material, specification, startDate, endDate'
});
}
// 日期格式验证
if (startDate && !isValidDate(startDate)) {
return res.status(400).json({
success: false,
message: '开始日期格式无效,应为 YYYY-MM-DD'
});
}
if (endDate && !isValidDate(endDate)) {
return res.status(400).json({
success: false,
message: '结束日期格式无效,应为 YYYY-MM-DD'
});
}
// 分页参数验证
if (page && (isNaN(page) || parseInt(page) < 1)) {
return res.status(400).json({
success: false,
message: '页码必须大于 0'
});
}
if (pageSize && (isNaN(pageSize) || parseInt(pageSize) < 1 || parseInt(pageSize) > 1000)) {
return res.status(400).json({
success: false,
message: '每页数量必须在 1-1000 之间'
});
}
next();
}
/**
* 验证统计请求
*/
function validateStats(req, res, next) {
const { region, material, days, startDate, endDate } = req.query;
// 天数验证
if (days && (isNaN(days) || parseInt(days) < 1 || parseInt(days) > 3650)) {
return res.status(400).json({
success: false,
message: '天数必须在 1-3650 之间'
});
}
// 日期格式验证
if (startDate && !isValidDate(startDate)) {
return res.status(400).json({
success: false,
message: '开始日期格式无效,应为 YYYY-MM-DD'
});
}
if (endDate && !isValidDate(endDate)) {
return res.status(400).json({
success: false,
message: '结束日期格式无效,应为 YYYY-MM-DD'
});
}
next();
}
/**
* 验证日期格式 YYYY-MM-DD
*/
function isValidDate(dateString) {
const regex = /^\d{4}-\d{2}-\d{2}$/;
if (!regex.test(dateString)) {
return false;
}
const date = new Date(dateString);
return date instanceof Date && !isNaN(date);
}
module.exports = {
validatePriceQuery,
validateSearch,
validateStats
};