healthy-checker/app/utils/schema.py

51 lines
1.1 KiB
Python

import yaml
import time
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
def load_schema(name: str) -> dict:
"""
Load schema YAML từ app/schemas/<name>.yaml
"""
path = BASE_DIR / "schemas" / f"{name}.yaml"
with open(path, "r", encoding="utf-8") as f:
return yaml.safe_load(f)
def render_response(schema: dict, data):
schema_type = schema.get("type")
# ---------- ARRAY ----------
if schema_type == "array":
if not isinstance(data, list):
return []
item_schema = schema.get("item", {})
return [
render_response(
{
"type": "object",
"fields": item_schema.get("fields", {})
},
item
)
for item in data
]
# ---------- OBJECT ----------
if schema_type == "object":
fields = schema.get("fields", {})
result = {}
for key, field_cfg in fields.items():
if key in data:
result[key] = data[key]
return result
# ---------- FALLBACK ----------
return data