Skip to content

Commit f5a46f9

Browse files
committed
refactor(country_service): implement time-based caching for improved performance
- Introduce _CacheEntry class to hold cached data with expiration time - Replace simple in-memory caching with time-based caching mechanism - Add cache duration constant for aggregated country lists - Update cache handling logic in _cachedEventCountries and _cachedHeadquarterCountries
1 parent 56df6b6 commit f5a46f9

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

lib/src/services/country_service.dart

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,30 @@ import 'package:core/core.dart';
22
import 'package:data_repository/data_repository.dart';
33
import 'package:logging/logging.dart';
44

5+
/// {@template _cache_entry}
6+
/// A simple class to hold cached data along with its expiration time.
7+
/// {@endtemplate}
8+
class _CacheEntry<T> {
9+
/// {@macro _cache_entry}
10+
const _CacheEntry(this.data, this.expiry);
11+
12+
/// The cached data.
13+
final T data;
14+
15+
/// The time at which the cached data expires.
16+
final DateTime expiry;
17+
18+
/// Checks if the cache entry is still valid (not expired).
19+
bool isValid() => DateTime.now().isBefore(expiry);
20+
}
21+
522
/// {@template country_service}
623
/// A service responsible for retrieving country data, including specialized
724
/// lists like countries associated with headlines or sources.
825
///
926
/// This service leverages database aggregation for efficient data retrieval
10-
/// and includes basic in-memory caching to optimize performance for frequently
11-
/// requested lists.
27+
/// and includes time-based in-memory caching to optimize performance for
28+
/// frequently requested lists.
1229
/// {@endtemplate}
1330
class CountryService {
1431
/// {@macro country_service}
@@ -27,11 +44,12 @@ class CountryService {
2744
final DataRepository<Source> _sourceRepository;
2845
final Logger _log;
2946

30-
// In-memory caches for frequently accessed lists.
31-
// These should be cleared periodically in a real-world application
32-
// or invalidated upon data changes. For this scope, simple caching is used.
33-
List<Country>? _cachedEventCountries;
34-
List<Country>? _cachedHeadquarterCountries;
47+
// Cache duration for aggregated country lists (e.g., 1 hour).
48+
static const Duration _cacheDuration = Duration(hours: 1);
49+
50+
// In-memory caches for frequently accessed lists with time-based invalidation.
51+
_CacheEntry<List<Country>>? _cachedEventCountries;
52+
_CacheEntry<List<Country>>? _cachedHeadquarterCountries;
3553

3654
/// Retrieves a list of countries based on the provided filter.
3755
///

0 commit comments

Comments
 (0)