handleRequests method

Future<void> handleRequests(
  1. HttpServer server
)

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"),
      );
    }

    WebRequest(httpRequest).init().then((WebRequest rq) {
      runZonedGuarded(() async {
        List<WebRoute> routing = [];

        if (config.dbConfig.enable) {
          if (_db == null) {
            _db = await connectMongoDb().onError((error, stackTrace) async {
              throw ("Error connect to DB");
            });
          } else if (!_db!.isConnected) {
            await _db!.open().onError((error, stackTrace) async {
              throw ("Error connect to DB");
            });
          }
        }

        for (var webRoute in _webRoutes) {
          routing.addAll(await webRoute(rq));
        }

        if (onRequest != null) {
          rq = await onRequest!(rq);
        }

        Route(
          routing: routing,
          rq: rq,
        ).handel();
      }, (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("#"),
      });
    });
  });
}