summaryrefslogtreecommitdiff
path: root/src/soc_collector/schema.py
diff options
context:
space:
mode:
authorVictor Näslund <victor@sunet.se>2022-11-17 22:04:24 +0100
committerVictor Näslund <victor@sunet.se>2022-11-17 22:04:24 +0100
commit03735d4c6fc17193e5019d3bd595bad2ce41c61f (patch)
tree889e5b6615f62930ef2ebd1e36616a177fca539e /src/soc_collector/schema.py
parenta276c55e8f1f7f2c5872a43485425dd85f1dfa9f (diff)
added tests
Diffstat (limited to 'src/soc_collector/schema.py')
-rw-r--r--src/soc_collector/schema.py28
1 files changed, 27 insertions, 1 deletions
diff --git a/src/soc_collector/schema.py b/src/soc_collector/schema.py
index 221990a..2c2dfb9 100644
--- a/src/soc_collector/schema.py
+++ b/src/soc_collector/schema.py
@@ -1,6 +1,8 @@
"""Our schema module"""
-from typing import Any, Dict
+from typing import Any, Dict, Optional, Union
import jsonschema
+from bson import ObjectId
+from bson.errors import InvalidId
# fmt:off
# NOTE: Commented out properties are left intentionally, so it is easier to see
@@ -99,9 +101,33 @@ def valid_schema(json_data: Dict[str, Any]) -> bool:
:param json_data: Json object
:return: bool
"""
+
try:
jsonschema.validate(json_data, schema, format_checker=jsonschema.FormatChecker())
except jsonschema.exceptions.ValidationError as exc:
print(f"Validation failed with error: {exc.message}")
return False
return True
+
+
+def object_id_from_data(data: Union[str, Dict[str, Any]]) -> Optional[ObjectId]:
+ """Get ObjectId from key. None if invalid.
+
+ :param data: Key.
+ :return: Optional[ObjectId]
+ """
+
+ if isinstance(data, str):
+ try:
+ return ObjectId(data)
+ except InvalidId:
+ return None
+
+ elif isinstance(data, Dict):
+ if "_id" in data and isinstance(data["_id"], str):
+ try:
+ return ObjectId(data["_id"])
+ except InvalidId:
+ return None
+
+ return None