Skip to content

Commit

Permalink
feat: add request caching service (TBD54566975#280)
Browse files Browse the repository at this point in the history
  • Loading branch information
aashish-g03 committed Oct 15, 2024
1 parent 0bc1feb commit ca5ac62
Showing 1 changed file with 100 additions and 0 deletions.
100 changes: 100 additions & 0 deletions lib/shared/services/request_cache_service.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import 'dart:async';
import 'dart:convert';

import 'package:collection/collection.dart';
import 'package:hive/hive.dart';
import 'package:http/http.dart' as http;

class RequestCacheService<T> {
final T Function(Map<String, dynamic>) fromJson;
final Map<String, dynamic> Function(T) toJson;
final Duration cacheDuration;
final String networkCacheKey;

RequestCacheService({
required this.fromJson,
required this.toJson,
this.cacheDuration = const Duration(minutes: 1),
this.networkCacheKey = 'network_cache',
});

/// Fetches data from the cache and API.
Stream<T> fetchData(String url) async* {
final box = await Hive.openBox(networkCacheKey);
final cacheKey = _generateCacheKey(url);
bool cacheEmitted = false;

try {
// Check for cached data
final cachedEntry = await box.get(cacheKey);
if (cachedEntry != null && cachedEntry is Map) {
final cachedMap = Map<String, dynamic>.from(cachedEntry);
final cachedTimestamp =
DateTime.parse(cachedMap['timestamp'] as String);
final cachedDataJson =
Map<String, dynamic>.from(cachedMap['data'] ?? {});
final cachedData = fromJson(cachedDataJson);
// Emit cached data
yield cachedData;
cacheEmitted = true;

final now = DateTime.now();
// Decide whether to fetch new data based on cache validity
if (now.difference(cachedTimestamp) < cacheDuration) {
// Cache is still valid, but we'll fetch new data to check for updates
// return; // Uncomment this line to skip fetching new data
}
}

// Fetch data from the network
try {
final response = await http.get(Uri.parse(url));

if (response.statusCode == 200) {
final dataMap = jsonDecode(response.body) as Map<String, dynamic>;
final data = fromJson(dataMap);

// Compare with cached data
bool isDataUpdated = true;
if (cachedEntry != null && cachedEntry is Map) {
final cachedDataJson =
Map<String, dynamic>.from(cachedEntry['data'] ?? {});
// Use DeepCollectionEquality for deep comparison
const equalityChecker = DeepCollectionEquality();
if (equalityChecker.equals(cachedDataJson, dataMap)) {
isDataUpdated = false;
}
}

// Cache the new data with a timestamp
final cacheEntry = {
'data': toJson(data),
'timestamp': DateTime.now().toIso8601String(),
};
await box.put(cacheKey, cacheEntry);

if (isDataUpdated) {
yield data;
}
} else {
throw Exception(
'Failed to load data from $url. Status code: ${response.statusCode}',
);
}
} catch (e) {
if (!cacheEmitted) {
// No cached data was emitted before, so we need to throw an error
throw Exception('Error fetching data from $url: $e');
}
// Else, we have already emitted cached data, so we can silently fail or log the error
}
} finally {
await box.close();
}
}

/// Generates a cache key by hashing the URL.
String _generateCacheKey(String url) {
return url.hashCode.toString();
}
}

0 comments on commit ca5ac62

Please sign in to comment.