forward method

Future<ProxyResponse> forward(
  1. ProxyRequest request
)

Forwards request to the target through the proxy.

If caching is enabled and a fresh cache entry exists, it is returned immediately without making a network call.

Implementation

Future<ProxyResponse> forward(ProxyRequest request) async {
  var req = request;
  if (_requestTransform != null) {
    req = _requestTransform!(req);
  }

  // Check cache.
  if (_config.cacheEnabled) {
    final cached = getCachedResponse(req);
    if (cached != null) {
      _stats.cacheHits++;
      _stats.requestCount++;
      return cached;
    }
    _stats.cacheMisses++;
  }

  final stopwatch = Stopwatch()..start();
  final maxAttempts = 1 + _config.retries;
  ProxyResponse? response;
  Object? lastError;

  for (var attempt = 0; attempt < maxAttempts; attempt++) {
    try {
      response = await _doForward(req);
      break;
    } catch (e) {
      lastError = e;
      if (attempt == maxAttempts - 1) {
        _stats.errors++;
        _stats.requestCount++;
        rethrow;
      }
    }
  }

  // If all attempts failed, the rethrow above exits. This guard
  // satisfies the analyzer for the non-nullable path below.
  if (response == null) throw lastError!;

  stopwatch.stop();
  response = ProxyResponse(
    statusCode: response.statusCode,
    headers: response.headers,
    body: response.body,
    cached: false,
    latency: stopwatch.elapsed,
  );

  if (_responseTransform != null) {
    response = _responseTransform!(response);
  }

  _stats.requestCount++;
  _stats.totalLatency += stopwatch.elapsed;
  _stats.bytesTransferred += response.body.length;

  // Store in cache.
  if (_config.cacheEnabled && response.statusCode == 200) {
    _putCache(req.cacheKey, response);
  }

  return response;
}