Skip to content

Commit 4322a0e

Browse files
committed
refactor(api): improve data route query handling
- Added camelCase to snake_case conversion. - Improved sortBy parameter handling. - Enhanced query parameter parsing.
1 parent bf23c06 commit 4322a0e

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

routes/api/v1/data/index.dart

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,16 @@ import 'package:ht_shared/ht_shared.dart';
88

99
import '../../../_middleware.dart'; // Assuming RequestId is here
1010

11+
/// Converts a camelCase string to snake_case.
12+
String _camelToSnake(String input) {
13+
return input
14+
.replaceAllMapped(
15+
RegExp(r'(?<!^)(?=[A-Z])'),
16+
(match) => '_${match.group(0)}',
17+
)
18+
.toLowerCase();
19+
}
20+
1121
/// Handles requests for the /api/v1/data collection endpoint.
1222
/// Dispatches requests to specific handlers based on the HTTP method.
1323
Future<Response> onRequest(RequestContext context) async {
@@ -109,10 +119,15 @@ Future<Response> _handleGet(
109119
final queryParams = context.request.uri.queryParameters;
110120
final startAfterId = queryParams['startAfterId'];
111121
final limitParam = queryParams['limit'];
112-
final sortBy = queryParams['sortBy'];
122+
final sortByParam = queryParams['sortBy'];
113123
final sortOrderRaw = queryParams['sortOrder']?.toLowerCase();
114124
final limit = limitParam != null ? int.tryParse(limitParam) : null;
115125

126+
// Convert sortBy from camelCase to snake_case for the database query.
127+
// This prevents errors where the client sends 'createdAt' and the database
128+
// expects 'created_at'.
129+
final sortBy = sortByParam != null ? _camelToSnake(sortByParam) : null;
130+
116131
SortOrder? sortOrder;
117132
if (sortOrderRaw != null) {
118133
if (sortOrderRaw == 'asc') {

0 commit comments

Comments
 (0)