handleRequests method
Handles incoming HTTP requests by processing them through routing functions and the onRequest function.
If config.dbConfig.enable is true, this method ensures the MongoDB database is connected before handling requests.
The request is processed in a guarded zone to catch and log errors, and an error response is sent if needed.
Implementation
Future<void> handleRequests(HttpServer server) async {
server.forEach((HttpRequest httpRequest) async {
if (config.fakeDelay != 0) {
await Future.delayed(Duration(seconds: config.fakeDelay)).then(
(value) => Console.i("Server has fake delay"),
);
}
Request(httpRequest).init().then((Request rq) {
Context.run(rq, () async {
var router = Route(routing: await getAllRoutes());
runZonedGuarded(() async {
if (config.dbConfig.enable) {
if (_mongoDb == null) {
_mongoDb =
await connectMongoDb().onError((error, stackTrace) async {
throw ("Error connect to DB");
});
} else if (!_mongoDb!.isConnected) {
await _mongoDb!.open().onError((error, stackTrace) async {
throw ("Error connect to DB");
});
}
}
if (onRequest != null) {
rq = await onRequest!(rq);
}
router.handle();
}, (error, StackTrace stack) async {
Console.e({
'error': error,
'stack': stack.toString().split("#"),
});
rq.addParams({
'error': error,
'stack': stack.toString().split("#"),
});
await rq.renderError(502);
await rq.writeAndClose('');
});
});
}).catchError((error, stack) {
Console.e({
'error': error,
'stack': stack.toString().split("#"),
});
});
});
}