import 'dart:async'; import '../../../data/cache/cache_entry.dart'; import '../../../data/cache/cache_invalidator.dart'; import '../../../data/cache/cache_policy.dart'; import '../../../data/cache/cached_repository.dart'; import 'todo_api.dart'; class TodoRepository extends CachedRepository> { static const String pendingListKey = 'todo:list:pending'; final TodoApi api; final CacheInvalidator invalidator; TodoRepository({ required this.api, required super.store, required this.invalidator, super.now, }) : super( policy: const CachePolicy( softTtl: Duration(days: 3650), hardTtl: Duration(days: 3650), minRefreshInterval: Duration(days: 3650), ), ); Future> getPendingTodos({ bool forceRefresh = false, }) async { return getOrLoad( key: pendingListKey, forceRefresh: forceRefresh, loadFromRemote: api.getPendingTodos, ); } Future completeTodo(String id) async { final CacheEntry>? cached = await readCacheEntry( pendingListKey, ); if (cached != null) { final next = cached.value .where((todo) => todo.id != id) .toList(growable: false); await writeCacheEntry(pendingListKey, next); } try { await api.completeTodo(id); invalidator.invalidate(pendingListKey); } catch (error) { if (cached != null) { await store.write>>( pendingListKey, cached, ); } rethrow; } } Future invalidatePending() { invalidator.invalidate(pendingListKey); return Future.value(); } }