startRequest method

Future<Response> startRequest({
  1. bool forceNewRequest = false,
})

Performs the request.

The resulting Response will either be obtained from a valid cache file or a web request. If a valid web Response has been sent, it will be saved in the cache. If setting forceNewRequest to true, not using the cache will be prioritized.

Implementation

Future<Response> startRequest({bool forceNewRequest = false}) async {
  final currentlyHasCachedDocument = await hasCachedDocument();
  if (currentlyHasCachedDocument) {
    final WebCacheDocument cacheDocument = await loadCachedDocument();
    if (webCacheType.useCachedDocument(cacheDocument) && !forceNewRequest) {
      return buildResponseFromDocument(cacheDocument);
    }
  }

  final uri = Uri.tryParse(url);
  if (uri == null) {
    return Response('Invalid URL format.', 500);
  }

  try {
    Response response = await responseFunction.call(Uri.parse(url), headers: headers);
    if (isValidResponse(response)) {
      await saveNewCacheResponse(response);
    } else if (currentlyHasCachedDocument) {
      // if the response was not valid and there are save-data, use them anyways
      return buildResponseFromDocument(await loadCachedDocument());
    }

    return response;
  } catch (e) {

    if (currentlyHasCachedDocument) {
      return buildResponseFromDocument(await loadCachedDocument());
    }

    return Response('An error occurred while performing the request.', 500);
  }
}