Skip to content

Commit 4347fd0

Browse files
committed
feat(api): automatically add ID and timestamps to created documents
- Implement automatic generation of 'id', 'createdAt', and 'updatedAt' fields for new documents - Use ObjectId for 'id' and ISO 8601 string for timestamps - Ensure UTC time is used for timestamps
1 parent 63ac699 commit 4347fd0

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

routes/api/v1/data/index.dart

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import 'package:ht_api/src/rbac/permission_service.dart';
77
import 'package:ht_api/src/registry/model_registry.dart';
88
import 'package:ht_data_repository/ht_data_repository.dart';
99
import 'package:ht_shared/ht_shared.dart';
10+
import 'package:mongo_dart/mongo_dart.dart';
1011

1112
/// Handles requests for the /api/v1/data collection endpoint.
1213
/// Dispatches requests to specific handlers based on the HTTP method.
@@ -152,6 +153,12 @@ Future<Response> _handlePost(RequestContext context) async {
152153
throw const BadRequestException('Missing or invalid request body.');
153154
}
154155

156+
// Standardize ID and timestamps before model creation
157+
final now = DateTime.now().toUtc().toIso8601String();
158+
requestBody['id'] = ObjectId().oid;
159+
requestBody['createdAt'] = now;
160+
requestBody['updatedAt'] = now;
161+
155162
dynamic itemToCreate;
156163
try {
157164
itemToCreate = modelConfig.fromJson(requestBody);

0 commit comments

Comments
 (0)