fix presenter issues

This commit is contained in:
2025-12-27 01:39:18 +01:00
parent 9a74e16f11
commit 901fb1ac83
9 changed files with 65 additions and 55 deletions

View File

@@ -149,24 +149,25 @@ export const DriverProviders: Provider[] = [
driverStatsService: IDriverStatsService,
imageService: IImageServicePort,
logger: Logger,
) => new GetDriversLeaderboardUseCase(driverRepo, rankingService, driverStatsService, (driverId: string) => Promise.resolve(imageService.getDriverAvatar(driverId)), logger),
inject: [DRIVER_REPOSITORY_TOKEN, RANKING_SERVICE_TOKEN, DRIVER_STATS_SERVICE_TOKEN, IMAGE_SERVICE_PORT_TOKEN, LOGGER_TOKEN],
output: UseCaseOutputPort<unknown>,
) => new GetDriversLeaderboardUseCase(driverRepo, rankingService, driverStatsService, (driverId: string) => Promise.resolve(imageService.getDriverAvatar(driverId)), logger, output),
inject: [DRIVER_REPOSITORY_TOKEN, RANKING_SERVICE_TOKEN, DRIVER_STATS_SERVICE_TOKEN, IMAGE_SERVICE_PORT_TOKEN, LOGGER_TOKEN, GET_DRIVERS_LEADERBOARD_OUTPUT_PORT_TOKEN],
},
{
provide: GET_TOTAL_DRIVERS_USE_CASE_TOKEN,
useFactory: (driverRepo: IDriverRepository) => new GetTotalDriversUseCase(driverRepo),
inject: [DRIVER_REPOSITORY_TOKEN],
useFactory: (driverRepo: IDriverRepository, output: UseCaseOutputPort<unknown>) => new GetTotalDriversUseCase(driverRepo, output),
inject: [DRIVER_REPOSITORY_TOKEN, GET_TOTAL_DRIVERS_OUTPUT_PORT_TOKEN],
},
{
provide: COMPLETE_DRIVER_ONBOARDING_USE_CASE_TOKEN,
useFactory: (driverRepo: IDriverRepository, logger: Logger) => new CompleteDriverOnboardingUseCase(driverRepo, logger),
inject: [DRIVER_REPOSITORY_TOKEN, LOGGER_TOKEN],
useFactory: (driverRepo: IDriverRepository, logger: Logger, output: UseCaseOutputPort<unknown>) => new CompleteDriverOnboardingUseCase(driverRepo, logger, output),
inject: [DRIVER_REPOSITORY_TOKEN, LOGGER_TOKEN, COMPLETE_DRIVER_ONBOARDING_OUTPUT_PORT_TOKEN],
},
{
provide: IS_DRIVER_REGISTERED_FOR_RACE_USE_CASE_TOKEN,
useFactory: (registrationRepo: IRaceRegistrationRepository, logger: Logger) =>
new IsDriverRegisteredForRaceUseCase(registrationRepo, logger),
inject: [RACE_REGISTRATION_REPOSITORY_TOKEN, LOGGER_TOKEN],
useFactory: (registrationRepo: IRaceRegistrationRepository, logger: Logger, output: UseCaseOutputPort<unknown>) =>
new IsDriverRegisteredForRaceUseCase(registrationRepo, logger, output),
inject: [RACE_REGISTRATION_REPOSITORY_TOKEN, LOGGER_TOKEN, IS_DRIVER_REGISTERED_FOR_RACE_OUTPUT_PORT_TOKEN],
},
{
provide: UPDATE_DRIVER_PROFILE_USE_CASE_TOKEN,

View File

@@ -1,4 +1,5 @@
import { Inject, Injectable } from '@nestjs/common';
import { Result } from '@core/shared/application/Result';
import { CompleteOnboardingInputDTO } from './dtos/CompleteOnboardingInputDTO';
import { CompleteOnboardingOutputDTO } from './dtos/CompleteOnboardingOutputDTO';
import { DriverRegistrationStatusDTO } from './dtos/DriverRegistrationStatusDTO';
@@ -69,14 +70,20 @@ export class DriverService {
async getDriversLeaderboard(): Promise<DriversLeaderboardDTO> {
this.logger.debug('[DriverService] Fetching drivers leaderboard.');
await this.getDriversLeaderboardUseCase.execute({});
const result = await this.getDriversLeaderboardUseCase.execute({});
if (result.isErr()) {
throw new Error(result.unwrapErr().details.message);
}
return this.driversLeaderboardPresenter.getResponseModel();
}
async getTotalDrivers(): Promise<DriverStatsDTO> {
this.logger.debug('[DriverService] Fetching total drivers count.');
await this.getTotalDriversUseCase.execute({});
const result = await this.getTotalDriversUseCase.execute({});
if (result.isErr()) {
throw new Error(result.unwrapErr().details.message);
}
return this.driverStatsPresenter.getResponseModel();
}
@@ -86,7 +93,7 @@ export class DriverService {
): Promise<CompleteOnboardingOutputDTO> {
this.logger.debug('Completing onboarding for user:', userId);
await this.completeDriverOnboardingUseCase.execute({
const result = await this.completeDriverOnboardingUseCase.execute({
userId,
firstName: input.firstName,
lastName: input.lastName,
@@ -95,6 +102,9 @@ export class DriverService {
...(input.bio !== undefined ? { bio: input.bio } : {}),
});
if (result.isErr()) {
throw new Error(result.unwrapErr().details.message);
}
return this.completeOnboardingPresenter.getResponseModel();
}
@@ -103,18 +113,22 @@ export class DriverService {
): Promise<DriverRegistrationStatusDTO> {
this.logger.debug('Checking driver registration status:', query);
await this.isDriverRegisteredForRaceUseCase.execute({
const result = await this.isDriverRegisteredForRaceUseCase.execute({
raceId: query.raceId,
driverId: query.driverId,
});
if (result.isErr()) {
throw new Error(result.unwrapErr().details.message);
}
return this.driverRegistrationStatusPresenter.getResponseModel();
}
async getCurrentDriver(userId: string): Promise<GetDriverOutputDTO | null> {
this.logger.debug(`[DriverService] Fetching current driver for userId: ${userId}`);
await this.driverRepository.findById(userId);
const driver = await this.driverRepository.findById(userId);
this.driverPresenter.present(Result.ok(driver));
return this.driverPresenter.getResponseModel();
}
@@ -136,14 +150,18 @@ export class DriverService {
async getDriver(driverId: string): Promise<GetDriverOutputDTO | null> {
this.logger.debug(`[DriverService] Fetching driver for driverId: ${driverId}`);
await this.driverRepository.findById(driverId);
const driver = await this.driverRepository.findById(driverId);
this.driverPresenter.present(Result.ok(driver));
return this.driverPresenter.getResponseModel();
}
async getDriverProfile(driverId: string): Promise<GetDriverProfileOutputDTO> {
this.logger.debug(`[DriverService] Fetching driver profile for driverId: ${driverId}`);
await this.getProfileOverviewUseCase.execute({ driverId });
const result = await this.getProfileOverviewUseCase.execute({ driverId });
if (result.isErr()) {
throw new Error(result.unwrapErr().details.message);
}
return this.driverProfilePresenter.getResponseModel();
}
}

View File

@@ -1,17 +1,10 @@
import { Result } from '@core/shared/application/Result';
import type { CompleteOnboardingOutputDTO } from '../dtos/CompleteOnboardingOutputDTO';
import type { CompleteDriverOnboardingResult } from '@core/racing/application/use-cases/CompleteDriverOnboardingUseCase';
export class CompleteOnboardingPresenter {
private responseModel: CompleteOnboardingOutputDTO | null = null;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
present(result: Result<any, any>): void {
if (result.isErr()) {
const error = result.unwrapErr();
throw new Error(error.details?.message ?? 'Failed to complete onboarding');
}
const data = result.unwrap();
present(data: CompleteDriverOnboardingResult): void {
this.responseModel = {
success: true,
driverId: data.driver.id,

View File

@@ -1,5 +1,4 @@
import { GetDriversLeaderboardResult } from '@core/racing/application/use-cases/GetDriversLeaderboardUseCase';
import { Result } from '@core/shared/application/Result';
import { beforeEach, describe, expect, it } from 'vitest';
import { DriversLeaderboardPresenter } from './DriversLeaderboardPresenter';
import type { Driver } from '@core/racing/domain/entities/Driver';
@@ -54,9 +53,7 @@ describe('DriversLeaderboardPresenter', () => {
activeCount: 2,
};
const result = Result.ok<GetDriversLeaderboardResult, never>(coreResult);
presenter.present(result);
presenter.present(coreResult);
const output = presenter.getResponseModel();

View File

@@ -1,21 +1,12 @@
import { DriversLeaderboardDTO } from '../dtos/DriversLeaderboardDTO';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type {
GetDriversLeaderboardResult,
GetDriversLeaderboardErrorCode,
} from '@core/racing/application/use-cases/GetDriversLeaderboardUseCase';
export class DriversLeaderboardPresenter {
private responseModel: DriversLeaderboardDTO | null = null;
present(result: Result<GetDriversLeaderboardResult, ApplicationErrorCode<GetDriversLeaderboardErrorCode, { message: string }>>): void {
if (result.isErr()) {
const error = result.unwrapErr();
throw new Error(error.details?.message ?? 'Failed to get drivers leaderboard');
}
const data = result.unwrap();
present(data: GetDriversLeaderboardResult): void {
this.responseModel = {
drivers: data.items.map(item => ({
id: item.driver.id,

View File

@@ -2,7 +2,7 @@ import type { IDriverRepository } from '../../domain/repositories/IDriverReposit
import { Driver } from '../../domain/entities/Driver';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { UseCase } from '@core/shared/application';
import type { UseCase, UseCaseOutputPort } from '@core/shared/application';
import type { Logger } from '@core/shared/application/Logger';
export interface CompleteDriverOnboardingInput {
@@ -30,15 +30,16 @@ export type CompleteDriverOnboardingApplicationError = ApplicationErrorCode<
/**
* Use Case for completing driver onboarding.
*/
export class CompleteDriverOnboardingUseCase implements UseCase<CompleteDriverOnboardingInput, CompleteDriverOnboardingResult, CompleteDriverOnboardingErrorCode> {
export class CompleteDriverOnboardingUseCase implements UseCase<CompleteDriverOnboardingInput, void, CompleteDriverOnboardingErrorCode> {
constructor(
private readonly driverRepository: IDriverRepository,
private readonly logger: Logger,
private readonly output: UseCaseOutputPort<CompleteDriverOnboardingResult>,
) {}
async execute(
input: CompleteDriverOnboardingInput,
): Promise<Result<CompleteDriverOnboardingResult, CompleteDriverOnboardingApplicationError>> {
): Promise<Result<void, CompleteDriverOnboardingApplicationError>> {
try {
const existing = await this.driverRepository.findById(input.userId);
if (existing) {
@@ -59,7 +60,8 @@ export class CompleteDriverOnboardingUseCase implements UseCase<CompleteDriverOn
await this.driverRepository.create(driver);
const result: CompleteDriverOnboardingResult = { driver };
return Result.ok(result);
this.output.present(result);
return Result.ok(void 0);
} catch (error) {
const err = error instanceof Error ? error : new Error('Unknown error');

View File

@@ -1,4 +1,4 @@
import type { Logger, UseCase } from '@core/shared/application';
import type { Logger, UseCase, UseCaseOutputPort } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { Driver } from '../../domain/entities/Driver';
@@ -42,20 +42,21 @@ export type GetDriversLeaderboardErrorCode =
* Use Case for retrieving driver leaderboard data.
* Returns a Result containing the domain leaderboard model.
*/
export class GetDriversLeaderboardUseCase implements UseCase<GetDriversLeaderboardInput, GetDriversLeaderboardResult, GetDriversLeaderboardErrorCode> {
export class GetDriversLeaderboardUseCase implements UseCase<GetDriversLeaderboardInput, void, GetDriversLeaderboardErrorCode> {
constructor(
private readonly driverRepository: IDriverRepository,
private readonly rankingService: IRankingService,
private readonly driverStatsService: IDriverStatsService,
private readonly getDriverAvatar: (driverId: string) => Promise<string | undefined>,
private readonly logger: Logger,
private readonly output: UseCaseOutputPort<GetDriversLeaderboardResult>,
) {}
async execute(
input: GetDriversLeaderboardInput,
): Promise<
Result<
GetDriversLeaderboardResult,
void,
ApplicationErrorCode<GetDriversLeaderboardErrorCode, { message: string }>
>
> {
@@ -105,7 +106,9 @@ export class GetDriversLeaderboardUseCase implements UseCase<GetDriversLeaderboa
this.logger.debug('Successfully computed drivers leaderboard');
return Result.ok(result);
this.output.present(result);
return Result.ok(void 0);
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));

View File

@@ -1,4 +1,4 @@
import type { UseCase } from '@core/shared/application';
import type { UseCase, UseCaseOutputPort } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { IDriverRepository } from '../../domain/repositories/IDriverRepository';
@@ -17,20 +17,23 @@ export type GetTotalDriversResult = {
export type GetTotalDriversErrorCode = 'REPOSITORY_ERROR';
export class GetTotalDriversUseCase implements UseCase<GetTotalDriversInput, GetTotalDriversResult, GetTotalDriversErrorCode> {
export class GetTotalDriversUseCase implements UseCase<GetTotalDriversInput, void, GetTotalDriversErrorCode> {
constructor(
private readonly driverRepository: IDriverRepository,
private readonly output: UseCaseOutputPort<GetTotalDriversResult>,
) {}
async execute(
_input: GetTotalDriversInput,
): Promise<Result<GetTotalDriversResult, ApplicationErrorCode<GetTotalDriversErrorCode, { message: string }>>> {
): Promise<Result<void, ApplicationErrorCode<GetTotalDriversErrorCode, { message: string }>>> {
void _input;
try {
const drivers = await this.driverRepository.findAll();
const result: GetTotalDriversResult = { totalDrivers: drivers.length };
return Result.ok(result);
this.output.present(result);
return Result.ok(void 0);
} catch (error) {
const message = (error as Error | undefined)?.message ?? 'Failed to compute total drivers';

View File

@@ -1,5 +1,5 @@
import type { IRaceRegistrationRepository } from '../../domain/repositories/IRaceRegistrationRepository';
import type { Logger, UseCase } from '@core/shared/application';
import type { Logger, UseCase, UseCaseOutputPort } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
@@ -26,20 +26,22 @@ export type IsDriverRegisteredForRaceResult = {
*
* Checks if a driver is registered for a specific race.
*/
export class IsDriverRegisteredForRaceUseCase implements UseCase<IsDriverRegisteredForRaceInput, IsDriverRegisteredForRaceResult, IsDriverRegisteredForRaceErrorCode> {
export class IsDriverRegisteredForRaceUseCase implements UseCase<IsDriverRegisteredForRaceInput, void, IsDriverRegisteredForRaceErrorCode> {
constructor(
private readonly registrationRepository: IRaceRegistrationRepository,
private readonly logger: Logger,
private readonly output: UseCaseOutputPort<IsDriverRegisteredForRaceResult>,
) {}
async execute(params: IsDriverRegisteredForRaceInput): Promise<Result<IsDriverRegisteredForRaceResult, IsDriverRegisteredForRaceApplicationError>> {
async execute(params: IsDriverRegisteredForRaceInput): Promise<Result<void, IsDriverRegisteredForRaceApplicationError>> {
this.logger.debug('IsDriverRegisteredForRaceUseCase:execute', { params });
const { raceId, driverId } = params;
try {
const isRegistered = await this.registrationRepository.isRegistered(raceId, driverId);
return Result.ok({ isRegistered, raceId, driverId });
this.output.present({ isRegistered, raceId, driverId });
return Result.ok(void 0);
} catch (error) {
this.logger.error(
'IsDriverRegisteredForRaceUseCase:execution error',