Files
gridpilot.gg/core/racing/application/use-cases/UpdateDriverProfileUseCase.ts
2026-01-16 19:46:49 +01:00

82 lines
2.5 KiB
TypeScript

import type { UseCase } from '@core/shared/application/UseCase';
import type { Logger } from '@core/shared/domain/Logger';
import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { Driver } from '../../domain/entities/Driver';
import type { DriverRepository } from '../../domain/repositories/DriverRepository';
export type UpdateDriverProfileInput = {
driverId: string;
bio?: string;
country?: string;
};
export type UpdateDriverProfileResult = Driver;
export type UpdateDriverProfileErrorCode =
| 'DRIVER_NOT_FOUND'
| 'INVALID_PROFILE_DATA'
| 'REPOSITORY_ERROR';
/**
* Application use case responsible for updating basic driver profile details.
* Encapsulates domain entity mutation. Mapping to DTOs is handled by presenters
* in the presentation layer through the output port.
*/
export class UpdateDriverProfileUseCase
implements UseCase<UpdateDriverProfileInput, void, UpdateDriverProfileErrorCode>
{
constructor(private readonly driverRepository: DriverRepository,
private readonly logger: Logger) {}
async execute(
input: UpdateDriverProfileInput,
): Promise<
Result<void, ApplicationErrorCode<UpdateDriverProfileErrorCode, { message: string }>>
> {
const { driverId, bio, country } = input;
if ((bio !== undefined && bio.trim().length === 0) || (country !== undefined && country.trim().length === 0)) {
return Result.err({
code: 'INVALID_PROFILE_DATA',
details: {
message: 'Profile data is invalid',
},
});
}
try {
const existing = await this.driverRepository.findById(driverId);
if (!existing) {
return Result.err({
code: 'DRIVER_NOT_FOUND',
details: {
message: `Driver with id ${driverId} not found`,
},
});
}
const updated: Driver = existing.update({
...(bio !== undefined ? { bio } : {}),
...(country !== undefined ? { country } : {}),
});
await this.driverRepository.update(updated);
return Result.ok(undefined);
} catch (error) {
const message = error instanceof Error ? error.message : 'Failed to update driver profile';
this.logger.error('Failed to update driver profile', error instanceof Error ? error : undefined, {
driverId,
});
return Result.err({
code: 'REPOSITORY_ERROR',
details: {
message,
},
});
}
}
}