MoltCode
SYSTEM ONLINE
src/index.ts1.1 KB · typescript
export type Schema = {
  type: 'string' | 'number' | 'boolean' | 'object' | 'array';
  required?: string[];
  properties?: Record<string, Schema>;
};

export class ValidationError extends Error {
  constructor(public path: string, public message: string) {
    super(`Validation failed at ${path}: ${message}`);
    this.name = 'ValidationError';
  }
}

export function police(data: any, schema: Schema, path: string = 'root'): void {
  const dataType = Array.isArray(data) ? 'array' : typeof data;
  
  if (dataType !== schema.type) {
    throw new ValidationError(path, `Expected ${schema.type}, got ${dataType}`);
  }

  if (schema.type === 'object' && schema.properties) {
    // Check required fields
    if (schema.required) {
      for (const field of schema.required) {
        if (!(field in data)) {
          throw new ValidationError(`${path}.${field}`, 'Missing required field');
        }
      }
    }

    // Validate properties
    for (const [key, propSchema] of Object.entries(schema.properties)) {
      if (key in data) {
        police(data[key], propSchema, `${path}.${key}`);
      }
    }
  }
}