conditionalRequests function

Middleware conditionalRequests({
  1. EtagResolver? etag,
  2. LastModifiedResolver? lastModified,
})

Middleware that evaluates HTTP conditional request headers and short-circuits responses with 304 (Not Modified) or 412 (Precondition Failed) where appropriate.

Implementation

Middleware conditionalRequests({
  EtagResolver? etag,
  LastModifiedResolver? lastModified,
}) {
  return (EngineContext ctx, Next next) async {
    final method = ctx.request.method.toUpperCase();
    final resolvedEtag = etag != null
        ? await Future.sync(() => etag(ctx))
        : null;
    final resolvedLastModified = lastModified != null
        ? await Future.sync(() => lastModified(ctx))
        : null;

    final outcome = evaluateConditionals(
      method: method,
      headers: ctx.request.headers,
      etag: resolvedEtag,
      lastModified: resolvedLastModified,
    );

    if (outcome == ConditionalOutcome.notModified) {
      _applyValidators(ctx.response, resolvedEtag, resolvedLastModified);
      ctx.response.statusCode = HttpStatus.notModified;
      return ctx.response;
    }

    if (outcome == ConditionalOutcome.preconditionFailed) {
      _applyValidators(ctx.response, resolvedEtag, resolvedLastModified);
      ctx.response.statusCode = HttpStatus.preconditionFailed;
      return ctx.response;
    }

    final result = await next();
    _applyValidators(ctx.response, resolvedEtag, resolvedLastModified);
    return result;
  };
}