middlewareAndControllerHandler function

Future middlewareAndControllerHandler(
  1. DoxRequest doxReq
)

Handle middleware and controllers

Implementation

Future<dynamic> middlewareAndControllerHandler(DoxRequest doxReq) async {
  dynamic result;
  RouteData route = doxReq.route;

  for (dynamic fn in route.controllers) {
    if (fn is Function) {
      /// when it is a function and last item int the list,
      /// it mean it is a final controller
      if (fn == route.controllers.last) {
        return await _handleController(route, fn, doxReq);
      }

      /// A function but not last item,
      /// it mean function base middleware which
      /// need to pass the result to next `fn`
      result = await fn(doxReq);
    }

    /// DoxMiddleware class
    /// with handle function
    if (fn is IDoxMiddleware) {
      result = await fn.handle(doxReq);
    }

    /// if result is dox Request, it mean result is from middleware
    /// and need to pass values to next controller.
    if (result is DoxRequest) {
      /// override doxReq from arguments in order to pass in the next loop
      doxReq = result;
    } else {
      /// else result is from controller and ready to response
      return result;
    }
  }
}