86 lines
2.1 KiB
TypeScript
86 lines
2.1 KiB
TypeScript
/**
|
|
* 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<string, Driver>;
|
|
|
|
constructor(seedData?: Driver[]) {
|
|
this.drivers = new Map();
|
|
|
|
if (seedData) {
|
|
seedData.forEach(driver => {
|
|
this.drivers.set(driver.id, driver);
|
|
});
|
|
}
|
|
}
|
|
|
|
async findById(id: string): Promise<Driver | null> {
|
|
return this.drivers.get(id) ?? null;
|
|
}
|
|
|
|
async findByIRacingId(iracingId: string): Promise<Driver | null> {
|
|
const driver = Array.from(this.drivers.values()).find(
|
|
d => d.iracingId === iracingId
|
|
);
|
|
return driver ?? null;
|
|
}
|
|
|
|
async findAll(): Promise<Driver[]> {
|
|
return Array.from(this.drivers.values());
|
|
}
|
|
|
|
async create(driver: Driver): Promise<Driver> {
|
|
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<Driver> {
|
|
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<void> {
|
|
if (!await this.exists(id)) {
|
|
throw new Error(`Driver with ID ${id} not found`);
|
|
}
|
|
|
|
this.drivers.delete(id);
|
|
}
|
|
|
|
async exists(id: string): Promise<boolean> {
|
|
return this.drivers.has(id);
|
|
}
|
|
|
|
async existsByIRacingId(iracingId: string): Promise<boolean> {
|
|
return Array.from(this.drivers.values()).some(
|
|
d => d.iracingId === iracingId
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Utility method to generate a new UUID
|
|
*/
|
|
static generateId(): string {
|
|
return uuidv4();
|
|
}
|
|
} |