Skip to content

Commit e9ffedf

Browse files
committed
fix(api): correctly serialize nested objects for db insertion
When creating new headlines or sources, the API was failing with a database error because it tried to insert nested `source`, `category`, and `headquarters` objects directly into the database. The database schema expects flattened foreign key columns (`source_id`, `category_id`, `headquarters_country_id`). This fix updates the `toJson` functions provided during the setup of the `headlineRepository` and `sourceRepository` in `AppDependencies`. These custom functions now correctly flatten the nested objects into their respective ID fields before the data is sent to the database client, resolving the "column does not exist" error.
1 parent 4322a0e commit e9ffedf

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

lib/src/config/app_dependencies.dart

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,21 @@ class AppDependencies {
115115
}
116116
return Headline.fromJson(json);
117117
},
118-
(h) => h.toJson(), // toJson already handles DateTime correctly
118+
(headline) {
119+
final json = headline.toJson();
120+
// The database expects source_id and category_id, not nested objects.
121+
// We extract the IDs and remove the original objects to match the
122+
// schema.
123+
if (headline.source != null) {
124+
json['source_id'] = headline.source!.id;
125+
}
126+
if (headline.category != null) {
127+
json['category_id'] = headline.category!.id;
128+
}
129+
json.remove('source');
130+
json.remove('category');
131+
return json;
132+
},
119133
);
120134
categoryRepository = _createRepository(
121135
connection,
@@ -147,7 +161,15 @@ class AppDependencies {
147161
}
148162
return Source.fromJson(json);
149163
},
150-
(s) => s.toJson(),
164+
(source) {
165+
final json = source.toJson();
166+
// The database expects headquarters_country_id, not a nested object.
167+
// We extract the ID and remove the original object to match the
168+
// schema.
169+
json['headquarters_country_id'] = source.headquarters?.id;
170+
json.remove('headquarters');
171+
return json;
172+
},
151173
);
152174
countryRepository = _createRepository(
153175
connection,

0 commit comments

Comments
 (0)