为查询添加缓存
All checks were successful
Dart CI / build (push) Successful in 28s

This commit is contained in:
2026-04-04 17:24:46 +08:00
parent 2a6c9ba8c2
commit 01cbb287ab
2 changed files with 24 additions and 3 deletions

View File

@@ -6,10 +6,17 @@ import '../entities/album.dart';
class AlbumRepository { class AlbumRepository {
final String basePath; final String basePath;
final List<Album> _albums = List.empty(growable: true);
DateTime _updated = DateTime.utc(1970);
AlbumRepository({required this.basePath}); AlbumRepository({required this.basePath});
Future<List<Album>> getAllAlbums() async { Future<List<Album>> getAllAlbums() async {
if (DateTime.now().difference(_updated).inSeconds <= 60) {
return _albums;
}
_updated = DateTime.now();
final dir = Directory(basePath); final dir = Directory(basePath);
if (!await dir.exists()) { if (!await dir.exists()) {
return []; return [];
@@ -29,7 +36,8 @@ class AlbumRepository {
); );
}) })
.toList(); .toList();
_albums.clear();
_albums.addAll(albums);
return albums; return albums;
} }

View File

@@ -1,3 +1,4 @@
import 'dart:collection';
import 'dart:io'; import 'dart:io';
import 'dart:typed_data'; import 'dart:typed_data';
@@ -6,12 +7,19 @@ import '../entities/photo.dart';
class PhotoRepository { class PhotoRepository {
final String basePath; final String basePath;
final Map<int, List<Photo>> _map = HashMap();
final Map<int, DateTime> _updatedMap = HashMap();
PhotoRepository(this.basePath); PhotoRepository(this.basePath);
Future<List<Photo>> getPhotosByAlbumId(int id) async { Future<List<Photo>> getPhotosByAlbumId(int id) async {
final dir = Directory(basePath); if (_updatedMap.containsKey(id) &&
DateTime.now().difference(_updatedMap[id]!).inSeconds <= 60) {
return _map[id]!;
}
_updatedMap[id] = DateTime.now();
final dir = Directory(basePath);
if (!await dir.exists()) { if (!await dir.exists()) {
return []; return [];
} }
@@ -57,10 +65,15 @@ class PhotoRepository {
); );
}); });
return Future.wait(photoFutures); final photos = await Future.wait(photoFutures);
_map[id] = List.from(photos);
return photos;
} }
Future<Photo?> getPhotoById(int id) async { Future<Photo?> getPhotoById(int id) async {
try {
return _map.values.expand((l) => l).firstWhere((p) => p.id == id);
} catch (e) {}
final dir = Directory(basePath); final dir = Directory(basePath);
if (!await dir.exists()) { if (!await dir.exists()) {