cw-cloud/struct-police/pulls
Fix: Handle null values correctly to prevent TypeError#2
opennull-pointer wants to merge
NU
null-pointerFixes #3.
typeof null is object, which caused the validator to proceed into the object check block. Accessing field in data on null throws a TypeError.
This fix explicitly treats null as type null, which causes the type check to fail (as expected) instead of crashing.
Files changed (1)
src/index.tsmodify
| 1 | + | export type Schema = { | |
| 2 | + | type: 'string' | 'number' | 'boolean' | 'object' | 'array'; | |
| 3 | + | required?: string[]; | |
| 4 | + | properties?: Record<string, Schema>; | |
| 5 | + | }; | |
| 6 | + | ||
| 7 | + | export class ValidationError extends Error { | |
| 8 | + | constructor(public path: string, public message: string) { | |
| 9 | + | super(`Validation failed at ${path}: ${message}`); | |
| 10 | + | this.name = 'ValidationError'; | |
| 11 | + | } | |
| 12 | + | } | |
| 13 | + | ||
| 14 | + | export function police(data: any, schema: Schema, path: string = 'root'): void { | |
| 15 | + | let dataType = typeof data; | |
| 16 | + | if (data === null) dataType = 'null'; | |
| 17 | + | if (Array.isArray(data)) dataType = 'array'; | |
| 18 | + | ||
| 19 | + | if (dataType !== schema.type) { | |
| 20 | + | throw new ValidationError(path, `Expected ${schema.type}, got ${dataType}`); | |
| 21 | + | } | |
| 22 | + | ||
| 23 | + | if (schema.type === 'object' && schema.properties) { | |
| 24 | + | // Check required fields | |
| 25 | + | if (schema.required) { | |
| 26 | + | for (const field of schema.required) { | |
| 27 | + | if (!(field in data)) { | |
| 28 | + | throw new ValidationError(`${path}.${field}`, 'Missing required field'); | |
| 29 | + | } | |
| 30 | + | } | |
| 31 | + | } | |
| 32 | + | ||
| 33 | + | // Validate properties | |
| 34 | + | for (const [key, propSchema] of Object.entries(schema.properties)) { | |
| 35 | + | if (key in data) { | |
| 36 | + | police(data[key], propSchema, `${path}.${key}`); | |
| 37 | + | } | |
| 38 | + | } | |
| 39 | + | } | |
| 40 | + | } |