/** * Infrastructure Adapter: InMemoryRaceRepository * * In-memory implementation of IRaceRepository. * Stores data in Map structure with UUID generation. */ import { v4 as uuidv4 } from 'uuid'; import { Race, RaceStatus } from '@gridpilot/racing/domain/entities/Race'; import type { IRaceRepository } from '@gridpilot/racing/domain/repositories/IRaceRepository'; export class InMemoryRaceRepository implements IRaceRepository { private races: Map; constructor(seedData?: Race[]) { this.races = new Map(); if (seedData) { seedData.forEach(race => { this.races.set(race.id, race); }); } } async findById(id: string): Promise { return this.races.get(id) ?? null; } async findAll(): Promise { return Array.from(this.races.values()); } async findByLeagueId(leagueId: string): Promise { return Array.from(this.races.values()) .filter(race => race.leagueId === leagueId) .sort((a, b) => a.scheduledAt.getTime() - b.scheduledAt.getTime()); } async findUpcomingByLeagueId(leagueId: string): Promise { const now = new Date(); return Array.from(this.races.values()) .filter(race => race.leagueId === leagueId && race.status === 'scheduled' && race.scheduledAt > now ) .sort((a, b) => a.scheduledAt.getTime() - b.scheduledAt.getTime()); } async findCompletedByLeagueId(leagueId: string): Promise { return Array.from(this.races.values()) .filter(race => race.leagueId === leagueId && race.status === 'completed' ) .sort((a, b) => b.scheduledAt.getTime() - a.scheduledAt.getTime()); } async findByStatus(status: RaceStatus): Promise { return Array.from(this.races.values()) .filter(race => race.status === status) .sort((a, b) => a.scheduledAt.getTime() - b.scheduledAt.getTime()); } async findByDateRange(startDate: Date, endDate: Date): Promise { return Array.from(this.races.values()) .filter(race => race.scheduledAt >= startDate && race.scheduledAt <= endDate ) .sort((a, b) => a.scheduledAt.getTime() - b.scheduledAt.getTime()); } async create(race: Race): Promise { if (await this.exists(race.id)) { throw new Error(`Race with ID ${race.id} already exists`); } this.races.set(race.id, race); return race; } async update(race: Race): Promise { if (!await this.exists(race.id)) { throw new Error(`Race with ID ${race.id} not found`); } this.races.set(race.id, race); return race; } async delete(id: string): Promise { if (!await this.exists(id)) { throw new Error(`Race with ID ${id} not found`); } this.races.delete(id); } async exists(id: string): Promise { return this.races.has(id); } /** * Utility method to generate a new UUID */ static generateId(): string { return uuidv4(); } }