Skip to content

Commit 757baa8

Browse files
committed
fix(api): correctly serialize and deserialize user content preferences
User creation was failing with a type cast error when creating the default UserContentPreferences. This was caused by two issues: 1. Complex list objects were not being JSON-encoded before being sent to the database's JSONB columns. 2. DateTime objects returned from the database were not being converted to strings before being passed to the fromJson factory. This change introduces custom toJson and fromJson functions for the userContentPreferencesRepository. These functions handle the necessary data transformations, ensuring correct serialization and deserialization and resolving the runtime error.
1 parent 43454b4 commit 757baa8

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

lib/src/config/app_dependencies.dart

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -153,8 +153,27 @@ class AppDependencies {
153153
userContentPreferencesRepository = _createRepository(
154154
connection,
155155
'user_content_preferences',
156-
UserContentPreferences.fromJson,
157-
(p) => p.toJson(),
156+
(json) {
157+
// The postgres driver returns DateTime objects, but the model's
158+
// fromJson expects ISO 8601 strings. We must convert them first.
159+
if (json['created_at'] is DateTime) {
160+
json['created_at'] =
161+
(json['created_at'] as DateTime).toIso8601String();
162+
}
163+
if (json['updated_at'] is DateTime) {
164+
json['updated_at'] =
165+
(json['updated_at'] as DateTime).toIso8601String();
166+
}
167+
return UserContentPreferences.fromJson(json);
168+
},
169+
(preferences) {
170+
final json = preferences.toJson();
171+
json['followed_categories'] = jsonEncode(json['followed_categories']);
172+
json['followed_sources'] = jsonEncode(json['followed_sources']);
173+
json['followed_countries'] = jsonEncode(json['followed_countries']);
174+
json['saved_headlines'] = jsonEncode(json['saved_headlines']);
175+
return json;
176+
},
158177
);
159178
appConfigRepository = _createRepository(
160179
connection,

0 commit comments

Comments
 (0)