Update lib/services/collection_service.dart

n+1 performance

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Lukas Müllner 2026-02-24 20:13:39 +01:00 committed by GitHub
parent 4b9cefb319
commit ca11df0152
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -60,34 +60,60 @@ class CollectionService {
.select('role, collections(id, name, description, owner_id, created_at)')
.eq('user_id', userId);
// If the user has no memberships, return early.
if (memberships.isEmpty) {
return <Collection>[];
}
// Collect all distinct collection IDs from memberships.
final collectionIds = <String>{};
for (final m in memberships) {
final c = m['collections'] as Map<String, dynamic>;
final collectionId = c['id'] as String;
collectionIds.add(collectionId);
}
final collectionIdList = collectionIds.toList();
// Fetch all items for these collections in a single query and count them in memory.
final items = await supabase
.from('hotwheels')
.select('id, collection_id')
.in_('collection_id', collectionIdList);
final itemCounts = <String, int>{};
for (final item in items) {
final collectionId = item['collection_id'] as String;
itemCounts[collectionId] = (itemCounts[collectionId] ?? 0) + 1;
}
// Fetch all members for these collections in a single query and count them in memory.
final members = await supabase
.from('collection_members')
.select('id, collection_id')
.in_('collection_id', collectionIdList);
final memberCounts = <String, int>{};
for (final member in members) {
final collectionId = member['collection_id'] as String;
memberCounts[collectionId] = (memberCounts[collectionId] ?? 0) + 1;
}
final collections = <Collection>[];
for (final m in memberships) {
final c = m['collections'] as Map<String, dynamic>;
// Count items in this collection.
final itemCount = await supabase
.from('hotwheels')
.select('id')
.eq('collection_id', c['id'])
.count(CountOption.exact);
// Count members.
final memberCount = await supabase
.from('collection_members')
.select('id')
.eq('collection_id', c['id'])
.count(CountOption.exact);
final collectionId = c['id'] as String;
collections.add(Collection(
id: c['id'] as String,
id: collectionId,
name: c['name'] as String,
description: c['description'] as String?,
ownerId: c['owner_id'] as String,
createdAt: DateTime.parse(c['created_at'] as String),
role: m['role'] as String,
itemCount: itemCount.count,
memberCount: memberCount.count,
itemCount: itemCounts[collectionId] ?? 0,
memberCount: memberCounts[collectionId] ?? 1,
));
}