feet/lib/api/cache.dart

49 lines
1.1 KiB
Dart

part of fever_api;
/// Caches items, feeds and groups
class APICache {
final FeverAPI api;
late final ItemCache items;
late final ObjectCache<int, Feed> feeds;
late final ObjectCache<int, Group> groups;
final List<FeedsGroup> feedsGroups = [];
APICache(this.api) {
items = ItemCache(api);
feeds = ObjectCache(api);
groups = ObjectCache(api);
}
}
class ObjectCache<K, T> {
final FeverAPI api;
final Map<K, T> _items = {};
ObjectCache(this.api);
/// Returns an item from the cache, or null if it doesn't exist
T? get(K key) {
return _items.containsKey(key) ? _items[key] : null;
}
/// Returns a copy of the cache content
Map<K, T> getAll() {
return {..._items};
}
void set(K key, T value) {
_items[key] = value;
}
}
class ItemCache extends ObjectCache<int, Item> {
/// Get all items for a given feed
List<Item> getForFeed(int feed) {
if (api.cache.feeds.get(feed) == null) throw Exception('Feed $feed doesn\'t exist');
return _items.values.where((item) => item.feedId == feed).toList();
}
ItemCache(FeverAPI api) : super(api);
}