chain function

RequestHandler chain (
  1. Iterable<RequestHandler> handlers
)

Sequentially runs a list of handlers of middleware, and returns early if any does not return true. Works well with Router.chain.

Implementation

RequestHandler chain(Iterable<RequestHandler> handlers) {
  return (req, res) {
    Future Function() runPipeline;

    for (var handler in handlers) {
      if (handler == null) break;

      if (runPipeline == null) {
        runPipeline = () => Future.sync(() => handler(req, res));
      } else {
        var current = runPipeline;
        runPipeline = () => current().then((result) => !res.isOpen
            ? Future.value(result)
            : req.app.executeHandler(handler, req, res));
      }
    }

    runPipeline ??= () => Future.value();
    return runPipeline();
  };
}