some function

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

Runs each middleware in order and short-circuits on the first one that passes (i.e. calls next()).

If a middleware rejects (sets a response without calling next()), it is skipped and the next candidate is tried. Only when all middlewares reject does the combined middleware fail — keeping the last rejection response.

Typical use: "if the client has a valid token, skip rate-limiting; otherwise apply rate-limiting."

app.mount('/api/*', some(
  bearerAuth(token: token),
  myRateLimit(limit: 100),
));

// Nested composition:
app.mount('/api/*', some(
  myCheckLocalNetwork(),
  every(bearerAuth(token: token), myRateLimit(limit: 100)),
));

Implementation

Middleware some(
  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 {
    Object? lastError;

    for (int i = 0; i < middlewares.length; i++) {
      final isLast = i == middlewares.length - 1;
      var called = false;

      try {
        await middlewares[i](c, () async {
          called = true;
        });

        if (called) {
          // This middleware passed — clear any stale rejection and proceed.
          c.clearResponse();
          await next();
          return;
        }

        // Soft rejection (set a response without calling next).
        lastError = null;
        if (!isLast) c.clearResponse();
      } catch (e) {
        if (called) {
          // Error occurred after calling next — unexpected, rethrow.
          rethrow;
        }
        lastError = e;
        if (!isLast) c.clearResponse();
      }
    }

    final err = lastError;
    if (err != null) throw err;
    // All middlewares rejected; c._response holds the last rejection.
  };
}