Files
gridpilot.gg/core/racing/application/use-cases/CancelRaceUseCase.ts
2025-12-16 18:17:48 +01:00

48 lines
2.1 KiB
TypeScript

import type { IRaceRepository } from '../../domain/repositories/IRaceRepository';
import type { AsyncUseCase } from '@core/shared/application';
import type { Logger } from '@core/shared/application';
import { Result } from '@core/shared/result/Result';
import { RacingDomainValidationError, RacingDomainInvariantError } from '../../domain/errors/RacingDomainError';
import type { CancelRaceCommandDTO } from '../dto/CancelRaceCommandDTO';
/**
* Use Case: CancelRaceUseCase
*
* Encapsulates the workflow for cancelling a race:
* - loads the race by id
* - returns error if the race does not exist
* - delegates cancellation rules to the Race domain entity
* - persists the updated race via the repository.
*/
export class CancelRaceUseCase
implements AsyncUseCase<CancelRaceCommandDTO, Result<void, RacingDomainValidationError | RacingDomainInvariantError>> {
constructor(
private readonly raceRepository: IRaceRepository,
private readonly logger: Logger,
) {}
async execute(command: CancelRaceCommandDTO): Promise<Result<void, RacingDomainValidationError | RacingDomainInvariantError>> {
const { raceId } = command;
this.logger.debug(`[CancelRaceUseCase] Executing for raceId: ${raceId}`);
try {
const race = await this.raceRepository.findById(raceId);
if (!race) {
this.logger.warn(`[CancelRaceUseCase] Race with ID ${raceId} not found.`);
return Result.err(new RacingDomainValidationError('Race not found'));
}
const cancelledRace = race.cancel();
await this.raceRepository.update(cancelledRace);
this.logger.info(`[CancelRaceUseCase] Race ${raceId} cancelled successfully.`);
return Result.ok(undefined);
} catch (error) {
if (error instanceof RacingDomainInvariantError || error instanceof RacingDomainValidationError) {
this.logger.warn(`[CancelRaceUseCase] Domain error cancelling race ${raceId}: ${error.message}`);
return Result.err(error);
}
this.logger.error(`[CancelRaceUseCase] Unexpected error cancelling race ${raceId}`, error instanceof Error ? error : new Error(String(error)));
throw error;
}
}
}