From 73a06f900f1893c07ea87af872725ca066cf36a2 Mon Sep 17 00:00:00 2001
From: Felix Blanke <info@fblanke.de>
Date: Tue, 4 Mar 2025 14:34:19 +0100
Subject: [PATCH] Add schema validator as utils

---
 AKModel/utils.py | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)
 create mode 100644 AKModel/utils.py

diff --git a/AKModel/utils.py b/AKModel/utils.py
new file mode 100644
index 0000000..b53e650
--- /dev/null
+++ b/AKModel/utils.py
@@ -0,0 +1,28 @@
+import json
+from pathlib import Path
+
+from jsonschema import Draft202012Validator
+from jsonschema.protocols import Validator
+from referencing import Registry, Resource
+
+from AKPlanning import settings
+
+def construct_schema_validator(schema: str | dict) -> Validator:
+    """Construct a validator for a JSON schema.
+
+    In particular, all schemas from the 'schemas' directory
+    are loaded into the registry.
+    """
+    schema_base_path = Path(settings.BASE_DIR) / "schemas"
+    resources = []
+    for schema_path in schema_base_path.glob("**/*.schema.json"):
+        with schema_path.open("r") as ff:
+            res = Resource.from_contents(json.load(ff))
+        resources.append((res.id(), res))
+    registry = Registry().with_resources(resources)
+    if isinstance(schema, str):
+        with (schema_base_path / schema).open("r") as ff:
+            schema = json.load(ff)
+    return Draft202012Validator(
+        schema=schema, registry=registry
+    )
-- 
GitLab