55from ted_sws import config
66from ted_sws .data_manager .adapters import inject_date_string_fields
77from ted_sws .event_manager .model .event_message import EventMessage
8+ from enum import Enum
89
910"""
1011This module contains the event logging repository adapters.
@@ -114,7 +115,18 @@ def add(self, event_message: EventMessage) -> str:
114115 :param event_message: The event message to be added
115116 :return:
116117 """
117- record = self .prepare_record (event_message )
118+ record = event_message .model_dump (mode = "python" )
119+
120+ # Convert all Enum fields recursively
121+ record = convert_enums_to_values (record )
122+
123+ for event_date_field_name in LOGGING_DATE_FIELD_NAMES :
124+ inject_date_string_fields (
125+ data = record ,
126+ date_field_name = event_date_field_name ,
127+ date_string_fields_suffix_map = LOGGING_DATE_STRING_FIELDS_SUFFIX_MAP ,
128+ )
129+
118130 result = self .collection .insert_one (record )
119131 return result .inserted_id
120132
@@ -171,3 +183,41 @@ def __init__(self, mongodb_client: MongoClient, database_name: str = None,
171183 :param collection_name: The collection name
172184 """
173185 super ().__init__ (mongodb_client , database_name , collection_name )
186+
187+
188+
189+
190+
191+
192+ def convert_enums_to_values (obj ):
193+ """
194+ Recursively convert all Enum instances within a data structure to their corresponding values.
195+
196+ This function walks through nested dictionaries and lists, replacing any instances of
197+ Python `Enum` objects with their `.value`. This is useful for preparing data to be
198+ serialised into formats like JSON or inserted into databases such as MongoDB, which do not
199+ support serialising Enum instances directly.
200+
201+ Args:
202+ obj (Any): The object to convert. Can be a dict, list, Enum, or any other type.
203+
204+ Returns:
205+ Any: A copy of the object with all Enums replaced by their raw values.
206+ The structure and other data types remain unchanged.
207+
208+ Example:
209+ class Color(Enum):
210+ ... RED = "red"
211+ ... BLUE = "blue"
212+ data = {"favourite": Color.RED, "others": [Color.BLUE, "green"]}
213+ convert_enums_to_values(data)
214+ {'favourite': 'red', 'others': ['blue', 'green']}
215+ """
216+ if isinstance (obj , dict ):
217+ return {k : convert_enums_to_values (v ) for k , v in obj .items ()}
218+ elif isinstance (obj , list ):
219+ return [convert_enums_to_values (item ) for item in obj ]
220+ elif isinstance (obj , Enum ):
221+ return obj .value
222+ else :
223+ return obj
0 commit comments