callPipe method

Future<List<Res>> callPipe(
  1. List<Future<Res> Function(List<Res>)> pipe
)

Implementation

Future<List<Res>> callPipe(
  List<Future<Res> Function(List<Res>)> pipe,
) {
  // Make sure pipe has at least two calls, to simplify method structure
  if (pipe.length < 2) {
    throw InvalidPipeLengthException();
  }

  List<Res> resAggregate = [];
  Completer<List<Res>> completer = new Completer();

  Future(() async {
    int currentCall = -1;
    try {
      for (final call in pipe) {
        currentCall += 1;
        resAggregate.add(await call(resAggregate));
      }
      completer.complete(resAggregate);
    } catch (err) {
      NawahDI.get<INawahLogger>()?.error(
        this,
        'Error in call-pipe with call index $currentCall: $err',
      );
      try {
        // Wrap adding err to resAggregate with try..catch to handle non-Res value
        resAggregate.add(err as Res);
      } catch (_) {
        resAggregate.add({
          'status': 400,
          'msg': 'Unexpected error: $err',
          'args': {
            'code': 'UNEXPECTED_ERROR',
          }
        });
      }
      completer.completeError(resAggregate);
    }
  });

  return completer.future;
}