Files
social-app/apps/lib/features/todo/data/todo_repository.dart
T

68 lines
1.7 KiB
Dart

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<List<TodoResponse>> {
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<List<TodoResponse>> getPendingTodos({
bool forceRefresh = false,
}) async {
return getOrLoad(
key: pendingListKey,
forceRefresh: forceRefresh,
loadFromRemote: api.getPendingTodos,
);
}
Future<void> completeTodo(String id) async {
final CacheEntry<List<TodoResponse>>? 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<CacheEntry<List<TodoResponse>>>(
pendingListKey,
cached,
);
}
rethrow;
}
}
Future<void> invalidatePending() {
invalidator.invalidate(pendingListKey);
return Future<void>.value();
}
}