refactor racing use cases
This commit is contained in:
@@ -3,13 +3,12 @@ import type { ILeagueRepository } from '../../domain/repositories/ILeagueReposit
|
||||
import type { IResultRepository } from '../../domain/repositories/IResultRepository';
|
||||
import type { IDriverRepository } from '../../domain/repositories/IDriverRepository';
|
||||
import type { IStandingRepository } from '../../domain/repositories/IStandingRepository';
|
||||
import { Result } from '../../domain/entities/Result';
|
||||
import type { AsyncUseCase, Logger } from '@core/shared/application';
|
||||
import { Result as SharedResult } from '@core/shared/application/Result';
|
||||
import { Result as RaceResult } from '../../domain/entities/Result';
|
||||
import type { Logger, UseCaseOutputPort } from '@core/shared/application';
|
||||
import { Result } from '@core/shared/application/Result';
|
||||
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
|
||||
import type { ImportRaceResultsApiOutputPort } from '../ports/output/ImportRaceResultsApiOutputPort';
|
||||
|
||||
export interface ImportRaceResultDTO {
|
||||
export type ImportRaceResultDTO = {
|
||||
id: string;
|
||||
raceId: string;
|
||||
driverId: string;
|
||||
@@ -17,9 +16,23 @@ export interface ImportRaceResultDTO {
|
||||
fastestLap: number;
|
||||
incidents: number;
|
||||
startPosition: number;
|
||||
}
|
||||
};
|
||||
|
||||
type ImportRaceResultsApiErrorCode =
|
||||
export type ImportRaceResultsApiInput = {
|
||||
raceId: string;
|
||||
resultsFileContent: string;
|
||||
};
|
||||
|
||||
export type ImportRaceResultsApiResult = {
|
||||
success: true;
|
||||
raceId: string;
|
||||
leagueId: string;
|
||||
driversProcessed: number;
|
||||
resultsRecorded: number;
|
||||
errors: string[];
|
||||
};
|
||||
|
||||
export type ImportRaceResultsApiErrorCode =
|
||||
| 'PARSE_ERROR'
|
||||
| 'RACE_NOT_FOUND'
|
||||
| 'LEAGUE_NOT_FOUND'
|
||||
@@ -27,9 +40,12 @@ type ImportRaceResultsApiErrorCode =
|
||||
| 'DRIVER_NOT_FOUND'
|
||||
| 'REPOSITORY_ERROR';
|
||||
|
||||
type ImportRaceResultsApiApplicationError = ApplicationErrorCode<ImportRaceResultsApiErrorCode, { message: string }>;
|
||||
type ImportRaceResultsApiApplicationError = ApplicationErrorCode<
|
||||
ImportRaceResultsApiErrorCode,
|
||||
{ message: string }
|
||||
>;
|
||||
|
||||
export class ImportRaceResultsApiUseCase implements AsyncUseCase<{ raceId: string; resultsFileContent: string }, ImportRaceResultsApiOutputPort, ImportRaceResultsApiErrorCode> {
|
||||
export class ImportRaceResultsApiUseCase {
|
||||
constructor(
|
||||
private readonly raceRepository: IRaceRepository,
|
||||
private readonly leagueRepository: ILeagueRepository,
|
||||
@@ -37,77 +53,132 @@ export class ImportRaceResultsApiUseCase implements AsyncUseCase<{ raceId: strin
|
||||
private readonly driverRepository: IDriverRepository,
|
||||
private readonly standingRepository: IStandingRepository,
|
||||
private readonly logger: Logger,
|
||||
private readonly output: UseCaseOutputPort<ImportRaceResultsApiResult>,
|
||||
) {}
|
||||
|
||||
async execute(params: { raceId: string; resultsFileContent: string }): Promise<SharedResult<ImportRaceResultsApiOutputPort, ApplicationErrorCode<ImportRaceResultsApiErrorCode>>> {
|
||||
this.logger.debug('ImportRaceResultsApiUseCase:execute', { raceId: params.raceId });
|
||||
const { raceId, resultsFileContent } = params;
|
||||
async execute(
|
||||
input: ImportRaceResultsApiInput,
|
||||
): Promise<Result<void, ApplicationErrorCode<ImportRaceResultsApiErrorCode, { message: string }>>> {
|
||||
const { raceId, resultsFileContent } = input;
|
||||
|
||||
this.logger.debug('ImportRaceResultsApiUseCase:execute', { raceId });
|
||||
|
||||
let results: ImportRaceResultDTO[];
|
||||
try {
|
||||
results = JSON.parse(resultsFileContent);
|
||||
} catch (error) {
|
||||
this.logger.error('ImportRaceResultsApiUseCase:parse error', error instanceof Error ? error : new Error('Parse error'));
|
||||
return SharedResult.err({ code: 'PARSE_ERROR', details: { message: 'Invalid JSON in results file content' } });
|
||||
this.logger.error(
|
||||
'ImportRaceResultsApiUseCase:parse error',
|
||||
error instanceof Error ? error : new Error('Parse error'),
|
||||
);
|
||||
|
||||
return Result.err({
|
||||
code: 'PARSE_ERROR',
|
||||
details: { message: 'Invalid JSON in results file content' },
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const race = await this.raceRepository.findById(raceId);
|
||||
|
||||
if (!race) {
|
||||
this.logger.warn(`ImportRaceResultsApiUseCase: Race with ID ${raceId} not found.`);
|
||||
return SharedResult.err({ code: 'RACE_NOT_FOUND', details: { message: `Race ${raceId} not found` } });
|
||||
|
||||
return Result.err({
|
||||
code: 'RACE_NOT_FOUND',
|
||||
details: { message: `Race ${raceId} not found` },
|
||||
});
|
||||
}
|
||||
|
||||
this.logger.debug(`ImportRaceResultsApiUseCase: Race ${raceId} found.`);
|
||||
|
||||
const league = await this.leagueRepository.findById(race.leagueId);
|
||||
|
||||
if (!league) {
|
||||
this.logger.warn(`ImportRaceResultsApiUseCase: League with ID ${race.leagueId} not found for race ${raceId}.`);
|
||||
return SharedResult.err({ code: 'LEAGUE_NOT_FOUND', details: { message: `League ${race.leagueId} not found` } });
|
||||
this.logger.warn(
|
||||
`ImportRaceResultsApiUseCase: League with ID ${race.leagueId} not found for race ${raceId}.`,
|
||||
);
|
||||
|
||||
return Result.err({
|
||||
code: 'LEAGUE_NOT_FOUND',
|
||||
details: { message: `League ${race.leagueId} not found` },
|
||||
});
|
||||
}
|
||||
|
||||
this.logger.debug(`ImportRaceResultsApiUseCase: League ${league.id} found.`);
|
||||
|
||||
const existing = await this.resultRepository.existsByRaceId(raceId);
|
||||
|
||||
if (existing) {
|
||||
this.logger.warn(`ImportRaceResultsApiUseCase: Results already exist for race ID: ${raceId}.`);
|
||||
return SharedResult.err({ code: 'RESULTS_EXIST', details: { message: 'Results already exist for this race' } });
|
||||
this.logger.warn(
|
||||
`ImportRaceResultsApiUseCase: Results already exist for race ID: ${raceId}.`,
|
||||
);
|
||||
|
||||
return Result.err({
|
||||
code: 'RESULTS_EXIST',
|
||||
details: { message: 'Results already exist for this race' },
|
||||
});
|
||||
}
|
||||
|
||||
this.logger.debug(`ImportRaceResultsApiUseCase: No existing results for race ${raceId}.`);
|
||||
|
||||
// Lookup drivers by iracingId and create results with driver.id
|
||||
const entities: SharedResult<Result, ImportRaceResultsApiApplicationError>[] = await Promise.all(
|
||||
results.map(async (dto) => {
|
||||
const entities: Result<RaceResult, ImportRaceResultsApiApplicationError>[] = await Promise.all(
|
||||
results.map(async dto => {
|
||||
const driver = await this.driverRepository.findByIRacingId(dto.driverId);
|
||||
|
||||
if (!driver) {
|
||||
this.logger.warn(`ImportRaceResultsApiUseCase: Driver with iRacing ID ${dto.driverId} not found for race ${raceId}.`);
|
||||
return SharedResult.err({ code: 'DRIVER_NOT_FOUND', details: { message: `Driver with iRacing ID ${dto.driverId} not found` } });
|
||||
this.logger.warn(
|
||||
`ImportRaceResultsApiUseCase: Driver with iRacing ID ${dto.driverId} not found for race ${raceId}.`,
|
||||
);
|
||||
|
||||
return Result.err({
|
||||
code: 'DRIVER_NOT_FOUND',
|
||||
details: { message: `Driver with iRacing ID ${dto.driverId} not found` },
|
||||
});
|
||||
}
|
||||
return SharedResult.ok(Result.create({
|
||||
id: dto.id,
|
||||
raceId: dto.raceId,
|
||||
driverId: driver.id,
|
||||
position: dto.position,
|
||||
fastestLap: dto.fastestLap,
|
||||
incidents: dto.incidents,
|
||||
startPosition: dto.startPosition,
|
||||
}));
|
||||
|
||||
return Result.ok(
|
||||
RaceResult.create({
|
||||
id: dto.id,
|
||||
raceId: dto.raceId,
|
||||
driverId: driver.id,
|
||||
position: dto.position,
|
||||
fastestLap: dto.fastestLap,
|
||||
incidents: dto.incidents,
|
||||
startPosition: dto.startPosition,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const errors = entities.filter(e => e.isErr()).map(e => (e.error as ImportRaceResultsApiApplicationError).details.message);
|
||||
const errors = entities
|
||||
.filter(entity => entity.isErr())
|
||||
.map(entity => (entity.error as ImportRaceResultsApiApplicationError).details.message);
|
||||
|
||||
if (errors.length > 0) {
|
||||
return SharedResult.err({ code: 'DRIVER_NOT_FOUND', details: { message: errors.join('; ') } });
|
||||
return Result.err({
|
||||
code: 'DRIVER_NOT_FOUND',
|
||||
details: { message: errors.join('; ') },
|
||||
});
|
||||
}
|
||||
|
||||
const validEntities = entities.filter(e => e.isOk()).map(e => e.unwrap());
|
||||
this.logger.debug('ImportRaceResultsApiUseCase:entities created', { count: validEntities.length });
|
||||
const validEntities = entities.filter(entity => entity.isOk()).map(entity => entity.unwrap());
|
||||
|
||||
this.logger.debug('ImportRaceResultsApiUseCase:entities created', {
|
||||
count: validEntities.length,
|
||||
});
|
||||
|
||||
await this.resultRepository.createMany(validEntities);
|
||||
|
||||
this.logger.info('ImportRaceResultsApiUseCase:race results created', { raceId });
|
||||
|
||||
await this.standingRepository.recalculate(league.id);
|
||||
this.logger.info('ImportRaceResultsApiUseCase:standings recalculated', { leagueId: league.id });
|
||||
|
||||
const output: ImportRaceResultsApiOutputPort = {
|
||||
this.logger.info('ImportRaceResultsApiUseCase:standings recalculated', {
|
||||
leagueId: league.id,
|
||||
});
|
||||
|
||||
const result: ImportRaceResultsApiResult = {
|
||||
success: true,
|
||||
raceId,
|
||||
leagueId: league.id,
|
||||
@@ -116,10 +187,24 @@ export class ImportRaceResultsApiUseCase implements AsyncUseCase<{ raceId: strin
|
||||
errors: [],
|
||||
};
|
||||
|
||||
return SharedResult.ok(dto);
|
||||
} catch (error) {
|
||||
this.logger.error('ImportRaceResultsApiUseCase:execution error', error instanceof Error ? error : new Error('Unknown error'));
|
||||
return SharedResult.err({ code: 'REPOSITORY_ERROR', details: { message: error instanceof Error ? error.message : 'Unknown error' } });
|
||||
this.output.present(result);
|
||||
|
||||
return Result.ok(undefined);
|
||||
} catch (error: unknown) {
|
||||
this.logger.error(
|
||||
'ImportRaceResultsApiUseCase:execution error',
|
||||
error instanceof Error ? error : new Error('Unknown error'),
|
||||
);
|
||||
|
||||
const message =
|
||||
error instanceof Error && error.message
|
||||
? error.message
|
||||
: 'Failed to import race results via API';
|
||||
|
||||
return Result.err({
|
||||
code: 'REPOSITORY_ERROR',
|
||||
details: { message },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user