Fix N+1 user queries in buildOwnerMap

Replace the Promise.all+findUserByClerkId loop with a single
findUsersByClerkIds batch query, consistent with the league loader
and settings loader fixes.

https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH
This commit is contained in:
Claude 2026-03-18 23:42:37 +00:00
parent 1b5016ab2a
commit 4ebcc061bb
No known key found for this signature in database

View file

@ -1,4 +1,4 @@
import { findUserByClerkId, getUserDisplayName } from "~/models/user"; import { findUsersByClerkIds, getUserDisplayName } from "~/models/user";
/** /**
* Builds a map of teamId -> manager username (or displayName fallback). * Builds a map of teamId -> manager username (or displayName fallback).
@ -7,30 +7,20 @@ import { findUserByClerkId, getUserDisplayName } from "~/models/user";
export async function buildOwnerMap( export async function buildOwnerMap(
slots: Array<{ team: { id: string; ownerId: string | null } }> slots: Array<{ team: { id: string; ownerId: string | null } }>
): Promise<Record<string, string>> { ): Promise<Record<string, string>> {
const ownerIds = slots const uniqueOwnerIds = [...new Set(
.map((s) => s.team.ownerId) slots.map((s) => s.team.ownerId).filter((id): id is string => id !== null)
.filter((id): id is string => id !== null); )];
const uniqueOwnerIds = [...new Set(ownerIds)];
const ownerEntries = await Promise.all( const userRows = await findUsersByClerkIds(uniqueOwnerIds);
uniqueOwnerIds.map(async (ownerId) => { const userByClerkId = new Map(
const user = await findUserByClerkId(ownerId); userRows
const name = user ? getUserDisplayName(user) : null; .map((u) => [u.clerkId, getUserDisplayName(u)] as const)
return name ? { ownerId, name } : null; .filter((entry): entry is [string, string] => entry[1] != null)
})
);
const ownerByClerkId = new Map(
ownerEntries
.filter((e): e is NonNullable<typeof e> => e !== null)
.map((e) => [e.ownerId, e.name])
); );
const ownerMap: Record<string, string> = {}; const ownerMap: Record<string, string> = {};
for (const slot of slots) { for (const slot of slots) {
const name = slot.team.ownerId const name = slot.team.ownerId ? userByClerkId.get(slot.team.ownerId) : undefined;
? ownerByClerkId.get(slot.team.ownerId)
: undefined;
if (name) { if (name) {
ownerMap[slot.team.id] = name; ownerMap[slot.team.id] = name;
} }