Skip to content

Commit

Permalink
feat: added eventResponse to event object, can now extract event resp…
Browse files Browse the repository at this point in the history
…onse in middleware, will be null if event is not handled.
  • Loading branch information
iyifr committed Dec 30, 2024
1 parent 7986902 commit 726fca4
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 6 deletions.
5 changes: 3 additions & 2 deletions bin/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ void main() async {
event.context["user"] = 'Ogunlepon';
print(getRequestUrl(event));
},
afterResponse: (event) => {},
afterResponse: (event) => {print(event.eventResponse)},
);

var router = createRouter();
Expand All @@ -31,7 +31,8 @@ void main() async {
});

apiRouter.post("/upload", (event) async {
var files = await readFiles(event, fieldName: 'file', customFilePath: 'uploads');
var files =
await readFiles(event, fieldName: 'file', customFilePath: 'uploads');
setResponseHeader(event, header: 'Content-Type', value: 'application/json');
return files;
});
Expand Down
7 changes: 7 additions & 0 deletions lib/src/event.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import 'package:h4/src/logger.dart';
class H4Event {
Map<String, String> params;
Map<String, dynamic> context;
dynamic eventResponse;

/// The HTTP request that triggered the event.
///
Expand All @@ -23,6 +24,7 @@ class H4Event {

H4Event(this._request)
: params = {},
eventResponse = null,
context = {
'path': _request.uri.path,
'query_params': _request.uri.queryParameters,
Expand Down Expand Up @@ -87,11 +89,14 @@ class H4Event {
case 'json':
headers.add(HttpHeaders.contentTypeHeader, 'application/json');
break;

case 'null':
_request.response.statusCode = 204;
break;

default:
logger.warning('Invalid response format: $type');
break;
}
}

Expand Down Expand Up @@ -147,6 +152,8 @@ class H4Event {
}

_resolveRequest(H4Event event, handlerResult) {
event.eventResponse = handlerResult;

// ignore: type_check_with_null
if (handlerResult is Null) {
event.statusCode = 204;
Expand Down
10 changes: 6 additions & 4 deletions lib/src/h4.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ void Function(String error, String? stackTrace, H4Event? event)
'$error\n$stackTrace Error occured while attempting ${event?.method.toUpperCase()} request at - ${event?.path}');

/// A middleware function that takes an [H4Event] and has access to it's snapshot.
/// Can also
typedef Middleware = void Function(H4Event event)?;

/// The [ErrorHandler] is used to process and potentially report errors that occur
Expand All @@ -37,6 +38,7 @@ typedef Middleware = void Function(H4Event event)?;
///
typedef ErrorHandler = void Function(String, String?, H4Event?);

// Workaround for union types.
typedef MiddlewareStack = Map<String, Either<Middleware?, ErrorHandler?>?>?;

class H4 {
Expand Down Expand Up @@ -75,11 +77,11 @@ class H4 {
bool autoStart = true,
this.middlewares,
}) {
initLogger();

if (autoStart) {
start(port: port);
}

initLogger();
}

/// Initializes the server on an available localhost port and starts listening for requests.
Expand Down Expand Up @@ -109,7 +111,7 @@ class H4 {
await server?.close(force: force);
}

/// Add a [H4Router] to the app instance for mapping requests.
/// Add a [H4Router] to the app instance for mapping requests to a different url.
void use(H4Router router, {String basePath = '/'}) {
routeStack[basePath] = router;
this.router = router;
Expand Down Expand Up @@ -170,7 +172,7 @@ class H4 {
_bootstrap() {
server!.listen((HttpRequest request) {
if (routeStack.values.isEmpty) {
logger.warning("No router instances were found.");
logger.warning("No router instances found.");
return404(request)(middlewares, null);
return;
}
Expand Down

0 comments on commit 726fca4

Please sign in to comment.