Files
jiapuapp/services/api/request-normalizers.js

66 lines
2.6 KiB
JavaScript

import { isNormalDisableStatus } from './normal-disable-status.js'
export const assertPlainPayload = (payload, allowedFields, label) => {
if (!payload || typeof payload !== 'object' || Array.isArray(payload) || Object.getPrototypeOf(payload) !== Object.prototype) {
throw new TypeError(`${label}必须是普通对象`)
}
if (Object.keys(payload).some((field) => !allowedFields.has(field))) {
throw new TypeError(`${label}包含未声明字段`)
}
}
export const normalizeOptionalText = (value, label) => {
if (value === undefined || value === null) return undefined
if (typeof value !== 'string') {
throw new TypeError(`${label}必须是字符串`)
}
const normalized = value.trim()
return normalized || undefined
}
export const normalizeOptionalNormalDisableStatus = (value, label = 'status') => {
const status = normalizeOptionalText(value, label)
if (status === undefined) return undefined
if (!isNormalDisableStatus(status)) throw new TypeError(`${label}必须为 0 或 1`)
return status
}
export const normalizeOssIdString = (value, field) => {
if (typeof value !== 'string' || !/^[1-9]\d*$/.test(value)) {
throw new TypeError(`${field} 必须是正整数 OSS ID 字符串`)
}
return value
}
export const normalizeOptionalSafeInteger = (value, field) => {
if (value === undefined || value === null || value === '') return undefined
const numericValue = typeof value === 'number' ? value : Number(value)
if (!Number.isSafeInteger(numericValue)) throw new TypeError(`${field} 必须是安全整数`)
return numericValue
}
export const normalizeOptionalCurrencyNumber = (value, label) => {
if (value === undefined || value === null || value === '') return undefined
const amountText = String(value)
if (!/^(?:0|[1-9]\d{0,9})(?:\.\d{1,2})?$/.test(amountText)) {
throw new TypeError(`${label}必须在 0 至 9999999999.99 之间且最多保留两位小数`)
}
return Number(amountText)
}
export const normalizeResourcePathId = (value, label) => {
if (typeof value === 'string' && /^[1-9]\d*$/.test(value)) return value
if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) return String(value)
throw new TypeError(`${label}必须是有效的正整数标识`)
}
export const normalizeOptionalOssIdList = (value) => {
if (value === undefined || value === null || value === '') return undefined
if (typeof value !== 'string') throw new TypeError('mediaOssIds 必须是字符串')
const normalized = value.trim()
if (!/^[1-9]\d*(,[1-9]\d*)*$/.test(normalized)) {
throw new TypeError('mediaOssIds 必须是以英文逗号分隔的正整数文件标识')
}
return normalized
}