every function

Middleware every(
  1. Middleware first,
  2. Middleware second, [
  3. Middleware? third,
  4. Middleware? fourth,
  5. Middleware? fifth,
])

Runs all middlewares in sequence and proceeds only when every one of them passes (calls next()).

As soon as any middleware rejects (sets a response without calling next() or throws), the chain is stopped and the rejection is returned immediately.

// Both bearerAuth AND rateLimit must pass:
app.mount('/api/*', every(
  bearerAuth(token: token),
  myRateLimit(limit: 100),
));

Implementation

Middleware every(
  Middleware first,
  Middleware second, [
  Middleware? third,
  Middleware? fourth,
  Middleware? fifth,
]) {
  final middlewares = [
    first,
    second,
    if (third != null) third,
    if (fourth != null) fourth,
    if (fifth != null) fifth,
  ];

  return (Context c, Next next) async {
    Future<void> dispatch(int i) async {
      if (i >= middlewares.length) {
        await next();
        return;
      }

      await middlewares[i](c, () async {
        await dispatch(i + 1);
      });

      // If the middleware did not call next, it rejected — stop the chain.
    }

    await dispatch(0);
  };
}