send<TResponse extends Object?> method

Future<TResponse> send<TResponse extends Object?>(
  1. Request<TResponse> request
)

Sends a request to a single RequestHandler.

Make sure the RequestHandler is registered before calling this method.

This request can be wrapped by PipelineBehavior's see pipeline.

This will return TResponse.

Implementation

Future<TResponse> send<TResponse extends Object?>(
  Request<TResponse> request,
) async {
  final handler = _requestHandlerStore.getHandlerFor(request)
      as RequestHandler<TResponse, Request<TResponse>>;

  final pipelines = _pipelineBehaviorStore.getPipelines(request);

  FutureOr<TResponse> handle() => handler.handle(request);

  final RequestHandlerDelegate executionPlan = pipelines.fold(
    handle,
    (next, pipeline) {
      FutureOr<TResponse> pipelineHandler() async {
        final futureOrResult = pipeline.handle(request, next);
        final result =
            futureOrResult is Future ? await futureOrResult : futureOrResult;

        assert(
          result is TResponse,
          '$request expected a return type of $TResponse but '
          'got one of type ${result.runtimeType}. '
          'One of the registered pipelines is not correctly returning the '
          '`next()` call. Pipelines used: $pipelines',
        );

        return result;
      }

      return pipelineHandler;
    },
  );

  final futureOrResult = executionPlan();
  final response =
      futureOrResult is Future ? await futureOrResult : futureOrResult;

  return response;
}