Skip to content

Commit daa6a4e

Browse files
committed
Enhance UserData schema and service for flexible preferences handling
- Updated UserDataBase schema to accept preferences as either a comma-separated string or a list of strings. - Implemented a new internal helper method in UserDataService to serialize preferences into a consistent format for database storage. - Adjusted user data retrieval and creation methods to ensure preferences are correctly formatted before database operations.
1 parent 491fae2 commit daa6a4e

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

backend/app/schemas/user_data.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,10 @@ class UserDataBase(BaseModel):
3535
children_status: Optional[bool] = None
3636
treatment: Optional[str] = None
3737
experience: Optional[str] = None
38-
preferences: Optional[str] = None
38+
# NOTE: preferences can either be a comma-separated string or an array of strings coming from the
39+
# client. We keep the underlying DB column as Text but allow the schema to accept both shapes so
40+
# that the service layer can serialise the list form when necessary.
41+
preferences: Optional[str | list[str]] = None # type: ignore[valid-type]
3942

4043

4144
class UserDataCreateRequest(UserDataBase):

backend/app/services/implementations/user_data_service.py

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,36 @@ def __init__(self, db: Session):
1919
self.db = db
2020
self.logger = logging.getLogger(LOGGER_NAME("user_data_service"))
2121

22+
# ---------------------------------------------------------------------
23+
# Internal helpers
24+
# ---------------------------------------------------------------------
25+
26+
@staticmethod
27+
def _serialise_preferences(preferences):
28+
"""Ensure preferences are stored as a comma-separated string.
29+
30+
The API allows the client to send either a list of strings **or** a
31+
comma-separated string. This helper converts the list form into the
32+
canonical string representation used in the database.
33+
"""
34+
if preferences is None:
35+
return None
36+
37+
# If the incoming value is already a string, strip extra whitespace
38+
if isinstance(preferences, str):
39+
# Collapse any excess whitespace around commas
40+
return ", ".join([p.strip() for p in preferences.split(",") if p.strip()])
41+
42+
# If it is a list/tuple, join using a comma and space
43+
if isinstance(preferences, (list, tuple)):
44+
return ", ".join([str(p).strip() for p in preferences if str(p).strip()])
45+
46+
# Fallback – we do not expect other types, but log in case
47+
logging.getLogger(LOGGER_NAME("user_data_service")).warning(
48+
"Unexpected preferences data type %s – storing as string", type(preferences)
49+
)
50+
return str(preferences)
51+
2252
def get_user_data_by_id(self, user_data_id: UUID) -> UserDataResponse:
2353
"""Get user data by its ID"""
2454
user_data = self.db.query(UserData).filter(UserData.id == user_data_id).first()
@@ -52,8 +82,14 @@ def create_user_data(self, user_data: UserDataCreateRequest) -> UserDataResponse
5282
detail=f"User data already exists for user {user_data.user_id}",
5383
)
5484

85+
# Prepare payload – ensure preferences field is in the correct format
86+
data_dict = user_data.model_dump()
87+
data_dict["preferences"] = self._serialise_preferences(
88+
data_dict.get("preferences")
89+
)
90+
5591
# Create new user data
56-
db_user_data = UserData(**user_data.model_dump())
92+
db_user_data = UserData(**data_dict)
5793
self.db.add(db_user_data)
5894
self.db.commit()
5995
self.db.refresh(db_user_data)
@@ -83,6 +119,11 @@ def update_user_data_by_user_id(
83119

84120
# Update only provided fields
85121
update_data = user_data.model_dump(exclude_unset=True)
122+
123+
# Serialise preferences if present
124+
if "preferences" in update_data:
125+
update_data["preferences"] = self._serialise_preferences(update_data["preferences"])
126+
86127
for key, value in update_data.items():
87128
setattr(db_user_data, key, value)
88129

0 commit comments

Comments
 (0)