照片列表支持分页
Some checks failed
Dart CI / build (push) Failing after 45s

This commit is contained in:
2026-04-05 16:41:45 +08:00
parent 8386dc09aa
commit d476d097dd
4 changed files with 194 additions and 10 deletions

View File

@@ -0,0 +1,13 @@
class PageResult<T> {
final List<T> items;
final int total;
final int page;
final int size;
const PageResult({
required this.items,
required this.total,
required this.page,
required this.size,
});
}

View File

@@ -4,6 +4,7 @@ import 'dart:typed_data';
import 'package:path/path.dart' as p;
import '../entities/photo.dart';
import '../page_result.dart';
class PhotoRepository {
final String basePath;
@@ -12,7 +13,30 @@ class PhotoRepository {
PhotoRepository(this.basePath);
/// 获取相册中所有照片(不分页,保留兼容)
Future<List<Photo>> getPhotosByAlbumId(int id) async {
final all = await _loadPhotosForAlbum(id);
return all;
}
/// 获取相册中的照片(分页)
Future<PageResult<Photo>> getPhotosByAlbumIdPaged(
int id, {
int page = 1,
int size = 20,
}) async {
final all = await _loadPhotosForAlbum(id);
final total = all.length;
final startIndex = (page - 1) * size;
final endIndex = startIndex + size;
final items = startIndex < total
? all.sublist(startIndex, endIndex > total ? total : endIndex)
: <Photo>[];
return PageResult(items: items, total: total, page: page, size: size);
}
/// 内部方法:加载相册照片(带缓存)
Future<List<Photo>> _loadPhotosForAlbum(int id) async {
if (_updatedMap.containsKey(id) &&
DateTime.now().difference(_updatedMap[id]!).inSeconds <= 60) {
return _map[id]!;

View File

@@ -135,7 +135,7 @@ Future<Response> _getPhotoHandler(Request req, PhotoRepository repo) async {
if (photo == null) {
return Response.notFound('Photo not found');
}
return jsonResponse(photo);
return jsonResponse(photo.toJson());
}
Future<Response> _getPhotoFileHandler(Request req, PhotoRepository repo) async {
@@ -199,8 +199,23 @@ Future<Response> _getPhotosOfAlbumHandler(
if (albumId == null) {
return Response.badRequest(body: 'Invalid album id: $idParam');
}
final photos = await repo.getPhotosByAlbumId(albumId);
return jsonResponse(photos);
// 获取分页参数
final page = int.tryParse(req.url.queryParameters['page'] ?? '1') ?? 1;
final size = int.tryParse(req.url.queryParameters['size'] ?? '20') ?? 20;
final result = await repo.getPhotosByAlbumIdPaged(
albumId,
page: page,
size: size,
);
return jsonResponse({
'items': result.items.map((p) => p.toJson()).toList(),
'total': result.total,
'page': result.page,
'size': result.size,
});
}
Future<Response> _getPhotoPreviewHandler(