背景与价值统一的输入约束可阻断非法参数并提升接口稳健性。结合长度、范围与枚举校验减少异常路径。统一规范类型约束:统一 `string/number/boolean/array/object` 基础类型。长度与范围:为字符串与数字设置边界(`min/max`、`minLength/maxLength`)。枚举与必填:枚举值与必填字段严格校验。核心实现Schema与校验type Base = { type: 'string'|'number'|'boolean'|'array'|'object'; enum?: any[] } type StringSchema = Base & { type: 'string'; minLength?: number; maxLength?: number } type NumberSchema = Base & { type: 'number'; min?: number; max?: number } type ArraySchema = Base & { type: 'array'; items?: Schema; minItems?: number; maxItems?: number } type ObjectSchema = Base & { type: 'object'; properties?: Record<string, Schema>; required?: string[] } type Schema = StringSchema | NumberSchema | ArraySchema | ObjectSchema | Base function inEnum(v: any, e?: any[]): boolean { return !e || e.includes(v) } function validate(v: any, s: Schema): boolean { if (s.type === 'string') { if (typeof v !== 'string') return false; const L = v.length; if (s.minLength && L < s.minLength) return false; if (s.maxLength && L > s.maxLength) return false; return inEnum(v, s.enum) } if (s.type === 'number') { if (typeof v !== 'number' || !Number.isFinite(v)) return false; if (s.min !== undefined && v < s.min) return false; if (s.max !== undefined && v > s.max) return false; return inEnum(v, s.enum) } if (s.type === 'boolean') { return typeof v === 'boolean' } if (s.type === 'array') { if (!Array.isArray(v)) return false; if (s.minItems && v.length < s.minItems) return false; if (s.maxItems && v.length > s.maxItems) return false; return s.items ? v.every(x => validate(x, s.items!)) : true } if (s.type === 'object') { if (typeof v !== 'object' || v === null || Array.isArray(v)) return false; const props = s.properties || {}; const req = s.required || []; for (const r of req) if (!(r in v)) return false; for (const [k, sch] of Object.entries(props)) if (k in v && !validate((v as any)[k], sch)) return false; return true } return false } 落地建议为接口输入建立统一Schema并在入口执行校验,拒绝不合规参数并返回明确错误。根据业务为字符串与数字设置合理边界并维护枚举值集合。验证清单输入是否满足类型与边界约束;必填字段与枚举是否校验通过。

发表评论 取消回复