Skip to content

Commit e4c54f5

Browse files
committed
refactor(country): improve country caching mechanism
- Introduce _CacheEntry class to enhance caching with expiration - Modify _getEventCountries and _getHeadquarterCountries to use new caching system - Update cache validation logic to check both existence and expiration
1 parent f5a46f9 commit e4c54f5

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

lib/src/services/country_service.dart

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -109,9 +109,9 @@ class CountryService {
109109
/// Uses MongoDB aggregation to efficiently get distinct country IDs
110110
/// and then fetches the full Country objects. Results are cached.
111111
Future<List<Country>> _getEventCountries() async {
112-
if (_cachedEventCountries != null) {
112+
if (_cachedEventCountries != null && _cachedEventCountries!.isValid()) {
113113
_log.finer('Returning cached event countries.');
114-
return _cachedEventCountries!;
114+
return _cachedEventCountries!.data;
115115
}
116116

117117
_log.finer('Fetching distinct event countries via aggregation.');
@@ -142,7 +142,10 @@ class CountryService {
142142
.map(Country.fromJson)
143143
.toList();
144144

145-
_cachedEventCountries = distinctCountries;
145+
_cachedEventCountries = _CacheEntry(
146+
distinctCountries,
147+
DateTime.now().add(_cacheDuration),
148+
);
146149
_log.info(
147150
'Successfully fetched and cached ${distinctCountries.length} '
148151
'event countries.',
@@ -160,9 +163,10 @@ class CountryService {
160163
/// Uses MongoDB aggregation to efficiently get distinct country IDs
161164
/// and then fetches the full Country objects. Results are cached.
162165
Future<List<Country>> _getHeadquarterCountries() async {
163-
if (_cachedHeadquarterCountries != null) {
166+
if (_cachedHeadquarterCountries != null &&
167+
_cachedHeadquarterCountries!.isValid()) {
164168
_log.finer('Returning cached headquarter countries.');
165-
return _cachedHeadquarterCountries!;
169+
return _cachedHeadquarterCountries!.data;
166170
}
167171

168172
_log.finer('Fetching distinct headquarter countries via aggregation.');
@@ -193,7 +197,10 @@ class CountryService {
193197
.map(Country.fromJson)
194198
.toList();
195199

196-
_cachedHeadquarterCountries = distinctCountries;
200+
_cachedHeadquarterCountries = _CacheEntry(
201+
distinctCountries,
202+
DateTime.now().add(_cacheDuration),
203+
);
197204
_log.info(
198205
'Successfully fetched and cached ${distinctCountries.length} '
199206
'headquarter countries.',

0 commit comments

Comments
 (0)