Files
gridpilot.gg/apps/website/infrastructure/repositories/InMemoryRaceRepository.ts
2025-12-03 00:46:08 +01:00

110 lines
2.9 KiB
TypeScript

/**
* 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 '../../domain/entities/Race';
import { IRaceRepository } from '../../application/ports/IRaceRepository';
export class InMemoryRaceRepository implements IRaceRepository {
private races: Map<string, Race>;
constructor(seedData?: Race[]) {
this.races = new Map();
if (seedData) {
seedData.forEach(race => {
this.races.set(race.id, race);
});
}
}
async findById(id: string): Promise<Race | null> {
return this.races.get(id) ?? null;
}
async findAll(): Promise<Race[]> {
return Array.from(this.races.values());
}
async findByLeagueId(leagueId: string): Promise<Race[]> {
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<Race[]> {
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<Race[]> {
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<Race[]> {
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<Race[]> {
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<Race> {
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<Race> {
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<void> {
if (!await this.exists(id)) {
throw new Error(`Race with ID ${id} not found`);
}
this.races.delete(id);
}
async exists(id: string): Promise<boolean> {
return this.races.has(id);
}
/**
* Utility method to generate a new UUID
*/
static generateId(): string {
return uuidv4();
}
}