/** * Infrastructure Adapter: InMemoryDriverRepository * * In-memory implementation of IDriverRepository. * Stores data in Map structure with UUID generation. */ import { v4 as uuidv4 } from 'uuid'; import { Driver } from '../../domain/entities/Driver'; import { IDriverRepository } from '../../application/ports/IDriverRepository'; export class InMemoryDriverRepository implements IDriverRepository { private drivers: Map; constructor(seedData?: Driver[]) { this.drivers = new Map(); if (seedData) { seedData.forEach(driver => { this.drivers.set(driver.id, driver); }); } } async findById(id: string): Promise { return this.drivers.get(id) ?? null; } async findByIRacingId(iracingId: string): Promise { const driver = Array.from(this.drivers.values()).find( d => d.iracingId === iracingId ); return driver ?? null; } async findAll(): Promise { return Array.from(this.drivers.values()); } async create(driver: Driver): Promise { if (await this.exists(driver.id)) { throw new Error(`Driver with ID ${driver.id} already exists`); } if (await this.existsByIRacingId(driver.iracingId)) { throw new Error(`Driver with iRacing ID ${driver.iracingId} already exists`); } this.drivers.set(driver.id, driver); return driver; } async update(driver: Driver): Promise { if (!await this.exists(driver.id)) { throw new Error(`Driver with ID ${driver.id} not found`); } this.drivers.set(driver.id, driver); return driver; } async delete(id: string): Promise { if (!await this.exists(id)) { throw new Error(`Driver with ID ${id} not found`); } this.drivers.delete(id); } async exists(id: string): Promise { return this.drivers.has(id); } async existsByIRacingId(iracingId: string): Promise { return Array.from(this.drivers.values()).some( d => d.iracingId === iracingId ); } /** * Utility method to generate a new UUID */ static generateId(): string { return uuidv4(); } }