diff --git a/lib/services/collection_service.dart b/lib/services/collection_service.dart index 23d4efd..9fd93dd 100644 --- a/lib/services/collection_service.dart +++ b/lib/services/collection_service.dart @@ -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 []; + } + + // Collect all distinct collection IDs from memberships. + final collectionIds = {}; + for (final m in memberships) { + final c = m['collections'] as Map; + 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 = {}; + 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 = {}; + for (final member in members) { + final collectionId = member['collection_id'] as String; + memberCounts[collectionId] = (memberCounts[collectionId] ?? 0) + 1; + } + final collections = []; for (final m in memberships) { final c = m['collections'] as Map; - - // 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, )); }