Skip to content

Commit 92ccee9

Browse files
committed
feat(api): create ResponseHelper for standardized success responses
Introduces a new `ResponseHelper` class with a static `success` method. This helper centralizes the logic for creating standardized `SuccessApiResponse` objects, automatically populating metadata like the request ID and timestamp, and serializing the final payload into a `Response.json` object. This refactoring prepares the ground for simplifying the response-building logic in various route handlers, reducing boilerplate code and improving maintainability.
1 parent d532bc4 commit 92ccee9

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import 'dart:io';
2+
3+
import 'package:dart_frog/dart_frog.dart';
4+
import 'package:ht_shared/ht_shared.dart';
5+
6+
import '../../routes/_middleware.dart';
7+
8+
/// A utility class to simplify the creation of standardized API responses.
9+
abstract final class ResponseHelper {
10+
/// Creates a standardized success JSON response.
11+
///
12+
/// This helper encapsulates the boilerplate of creating metadata, wrapping the
13+
/// payload in a [SuccessApiResponse], and serializing it to JSON.
14+
///
15+
/// - [context]: The request context, used to read the `RequestId`.
16+
/// - [data]: The payload to be included in the response.
17+
/// - [toJsonT]: A function that knows how to serialize the [data] payload.
18+
/// This is necessary because of Dart's generics. For a simple object, this
19+
/// would be `(data) => data.toJson()`. For a paginated list, it would be
20+
/// `(paginated) => paginated.toJson((item) => item.toJson())`.
21+
/// - [statusCode]: The HTTP status code for the response. Defaults to 200 OK.
22+
static Response success<T>({
23+
required RequestContext context,
24+
required T data,
25+
required Map<String, dynamic> Function(T data) toJsonT,
26+
int statusCode = HttpStatus.ok,
27+
}) {
28+
final metadata = ResponseMetadata(
29+
requestId: context.read<RequestId>().id,
30+
timestamp: DateTime.now().toUtc(),
31+
);
32+
33+
final responsePayload = SuccessApiResponse<T>(
34+
data: data,
35+
metadata: metadata,
36+
);
37+
38+
return Response.json(
39+
statusCode: statusCode,
40+
body: responsePayload.toJson(toJsonT),
41+
);
42+
}
43+
}

0 commit comments

Comments
 (0)