get method

Future<ApiResponse> get(
  1. String url, {
  2. bool useCache = true,
  3. Duration? ttl,
})

Implementation

Future<ApiResponse> get(String url,
    {bool useCache = true, Duration? ttl}) async {
  final key = _key('GET', url);
  if (!ConnectivityService.isConnected) {
    if (useCache) {
      final cached = await CacheManager.getJson(key);
      if (cached != null) return ApiResponse.success(cached);
      return ApiResponse.error('No connection and no cache');
    }
    return ApiResponse.error('No connection');
  }

  try {
    final res = await _dio.get(url);
    final data = res.data;
    if (useCache) {
      await CacheManager.putJson(key, data, ttl: ttl ?? defaultCacheTtl);
    }
    return ApiResponse.success(data, status: res.statusCode);
  } catch (e) {
    // fallback to cache on error
    if (useCache) {
      final cached = await CacheManager.getJson(key);
      if (cached != null) return ApiResponse.success(cached);
    }
    return ApiResponse.error(e.toString());
  }
}