|
| 1 | +from typing import Any |
| 2 | + |
| 3 | +from jsonschema_path import SchemaPath |
| 4 | + |
| 5 | +from openapi_core.util import forcebool |
| 6 | + |
| 7 | + |
| 8 | +def cast_primitive(value: Any, schema: SchemaPath) -> Any: |
| 9 | + """Cast a primitive value based on schema type.""" |
| 10 | + schema_type = (schema / "type").read_str("") |
| 11 | + |
| 12 | + if schema_type == "integer": |
| 13 | + return int(value) |
| 14 | + elif schema_type == "number": |
| 15 | + return float(value) |
| 16 | + elif schema_type == "boolean": |
| 17 | + return forcebool(value) |
| 18 | + |
| 19 | + return value |
| 20 | + |
| 21 | + |
| 22 | +def cast_value(value: Any, schema: SchemaPath, cast: bool) -> Any: |
| 23 | + """Recursively cast a value based on schema.""" |
| 24 | + if not cast: |
| 25 | + return value |
| 26 | + |
| 27 | + schema_type = (schema / "type").read_str("") |
| 28 | + |
| 29 | + # Handle arrays |
| 30 | + if schema_type == "array": |
| 31 | + if not isinstance(value, list): |
| 32 | + raise ValueError( |
| 33 | + f"Expected list for array type, got {type(value)}" |
| 34 | + ) |
| 35 | + items_schema = schema.get("items", SchemaPath.from_dict({})) |
| 36 | + return [cast_value(item, items_schema, cast) for item in value] |
| 37 | + |
| 38 | + # Handle objects |
| 39 | + if schema_type == "object": |
| 40 | + if not isinstance(value, dict): |
| 41 | + raise ValueError( |
| 42 | + f"Expected dict for object type, got {type(value)}" |
| 43 | + ) |
| 44 | + properties = schema.get("properties", SchemaPath.from_dict({})) |
| 45 | + result = {} |
| 46 | + for key, val in value.items(): |
| 47 | + if key in properties: |
| 48 | + prop_schema = schema / "properties" / key |
| 49 | + result[key] = cast_value(val, prop_schema, cast) |
| 50 | + else: |
| 51 | + result[key] = val |
| 52 | + return result |
| 53 | + |
| 54 | + # Handle primitives |
| 55 | + return cast_primitive(value, schema) |
0 commit comments