All files / web/src/lib/arcade player-ownership.ts

92.18% Statements 59/64
50% Branches 1/2
100% Functions 1/1
92.18% Lines 59/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 651x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 1x  
/**
 * Server-side player ownership utilities
 *
 * This module contains database-backed utilities for server-side code.
 * For client-side code, import from player-ownership.client.ts instead.
 */
 
import { eq } from 'drizzle-orm'
import { db, schema } from '@/db'
import type { PlayerOwnershipMap } from './player-ownership.client'
 
// Re-export all client-safe utilities
export * from './player-ownership.client'
 
// ============================================================================
// SERVER-SIDE UTILITIES (async, database-backed)
// ============================================================================
 
/**
 * Build player ownership map from database
 *
 * Fetches all players (optionally filtered by room) and creates a mapping
 * of playerId -> userId for authorization checks.
 *
 * @param roomId - Optional room ID to filter players by room membership
 * @returns Map of playerId -> userId
 *
 * @example
 * ```ts
 * // Get ownership for all players
 * const ownership = await buildPlayerOwnershipMap()
 *
 * // Get ownership for players in a specific room
 * const roomOwnership = await buildPlayerOwnershipMap('room-123')
 * ```
 */
export async function buildPlayerOwnershipMap(roomId?: string): Promise<PlayerOwnershipMap> {
  let players: Array<{ id: string; userId: string }>
 
  if (roomId) {
    // Fetch players who belong to users that are members of this room
    const members = await db.query.roomMembers.findMany({
      where: eq(schema.roomMembers.roomId, roomId),
      columns: { userId: true },
    })
 
    const memberUserIds = members.map((m) => m.userId)
 
    // Fetch all players belonging to room members
    players = await db.query.players.findMany({
      columns: { id: true, userId: true },
    })
 
    // Filter to only players owned by room members
    players = players.filter((p) => memberUserIds.includes(p.userId))
  } else {
    // Fetch all players
    players = await db.query.players.findMany({
      columns: { id: true, userId: true },
    })
  }
 
  return Object.fromEntries(players.map((p) => [p.id, p.userId]))
}