This commit is contained in:
2025-08-15 16:55:43 +08:00
parent 2986b212a0
commit 10b714e441
7 changed files with 129 additions and 10 deletions
+80
View File
@@ -0,0 +1,80 @@
// HTTP请求参数验证工具
/**
* 验证必需参数
* @param {Object} params 参数对象
* @param {Array} requiredFields 必需字段数组
* @param {String} apiName API名称(用于错误提示)
* @throws {Error} 参数验证失败时抛出错误
*/
export function validateRequired(params, requiredFields, apiName = 'API') {
if (!params || typeof params !== 'object') {
throw new Error(`${apiName}: 参数不能为空`)
}
for (const field of requiredFields) {
if (params[field] === undefined || params[field] === null || params[field] === '') {
throw new Error(`${apiName}: 缺少必需参数 ${field}`)
}
}
}
/**
* 验证ID参数
* @param {String|Number} id ID值
* @param {String} fieldName 字段名称
* @param {String} apiName API名称
* @throws {Error} ID验证失败时抛出错误
*/
export function validateId(id, fieldName = 'id', apiName = 'API') {
if (!id || (typeof id !== 'string' && typeof id !== 'number')) {
throw new Error(`${apiName}: ${fieldName} 不能为空且必须是字符串或数字`)
}
if (typeof id === 'string' && id.trim() === '') {
throw new Error(`${apiName}: ${fieldName} 不能为空字符串`)
}
if (typeof id === 'number' && (id <= 0 || !Number.isInteger(id))) {
throw new Error(`${apiName}: ${fieldName} 必须是正整数`)
}
}
/**
* 验证分页参数
* @param {Object} params 分页参数
* @param {String} apiName API名称
*/
export function validatePagination(params, apiName = 'API') {
if (params.page !== undefined) {
if (!Number.isInteger(params.page) || params.page < 1) {
throw new Error(`${apiName}: page 必须是大于0的整数`)
}
}
if (params.limit !== undefined) {
if (!Number.isInteger(params.limit) || params.limit < 1 || params.limit > 100) {
throw new Error(`${apiName}: limit 必须是1-100之间的整数`)
}
}
}
/**
* 验证文件上传参数
* @param {Object} fileData 文件数据
* @param {String} apiName API名称
*/
export function validateFileUpload(fileData, apiName = 'API') {
if (!fileData || typeof fileData !== 'object') {
throw new Error(`${apiName}: 文件数据不能为空`)
}
if (!fileData.filePath || typeof fileData.filePath !== 'string') {
throw new Error(`${apiName}: filePath 不能为空且必须是字符串`)
}
// 验证文件路径格式(简单验证)
if (!fileData.filePath.includes('/') && !fileData.filePath.includes('\\')) {
throw new Error(`${apiName}: filePath 格式不正确`)
}
}