handleRequest<ResultType, Item> method

Future<ApiResponse<ResultType, Item>> handleRequest<ResultType, Item>(
  1. ApiRequest<ResultType, Item> request, {
  2. CacheDescription? cache,
  3. int timeout = 50,
  4. bool retryWithCache = false,
  5. bool retry = false,
})

manages fetching data, decides where to fetch data from

Implementation

Future<ApiResponse<ResultType, Item>> handleRequest<ResultType, Item>(
    // NetworkCall<ApiResponse<ResultType, Item>> networkCall,
    ApiRequest<ResultType, Item> request,
    {CacheDescription? cache,
    int timeout = 50,
    bool retryWithCache = false,
    bool retry = false}) async {
  bool useCache = await shouldUseCache(localRepository, cache);

  /// fetches data from cache if a valid cached data exists
  if (useCache) {
    try {
      if (kDebugMode) print('fetching data from cache');
      request.build;
      var data = await localRepository.getData(cache!.key);
      // data = JsonInterceptor.convertFromJson<ResultType, Item>(data);
      // print('${data != null && data is ResultType}');
      if (kDebugMode) print('fetching data from cache $data');
      var d = Jsonutils.decode(data?.toString() ?? '');
      var res = ApiResponse<ResultType, Item>(
              request: request.copyWith(dataKey: '', nestedKey: ''),
              bodyString: d,
              // body: data,
              headers: {},
              statusCode: 210)
          .resolve;
      if (res.body != null && (d is! List || (d).isNotEmpty)) return res;
    } catch (e) {
      if (kDebugMode) {
        print(e);
      }
    }
  }

  /// else fetches data from the remote source
  ApiResponse<ResultType, Item> response = await remoteRepository
      .handleRequest<ResultType, Item>(request, timeout: timeout);

  // print('headers: ${response.request.headers}');

  if (!response.isSuccessful) {
    response = remoteRepository.handleError(response);
    if (retryWithCache && cache != null) {
      return handleRequest(request,
          cache: cache.copyWith(overrideTime: true));
    }
  }

  if (kDebugMode) print(response.error);
  if (kDebugMode) print(' finished request');

  if (cache != null &&
      !cache.ignoreSave &&
      cache.key.isNotEmpty &&
      response.body != null) {
    var data = validateData<ResultType, Item>(response);
    if (data != null) {
      String json = Jsonutils.convertToJson(data);
      localRepository.saveData(cache.key, json);
      localRepository.saveTime(
          cache.key,
          DateTime.now()
              .add(Duration(milliseconds: cache.lifeSpan))
              .millisecondsSinceEpoch);
    }
  }
  return response;
}