Files
gridpilot.gg/core/media/application/use-cases/UpdateAvatarUseCase.ts
2025-12-21 01:20:27 +01:00

84 lines
2.4 KiB
TypeScript

/**
* Use Case: UpdateAvatarUseCase
*
* Handles the business logic for updating a driver's avatar.
*/
import type { Logger, UseCaseOutputPort } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { v4 as uuidv4 } from 'uuid';
import { Avatar } from '../../domain/entities/Avatar';
import type { IAvatarRepository } from '../../domain/repositories/IAvatarRepository';
export interface UpdateAvatarInput {
driverId: string;
mediaUrl: string;
}
export interface UpdateAvatarResult {
avatarId: string;
driverId: string;
}
export type UpdateAvatarErrorCode = 'REPOSITORY_ERROR';
export type UpdateAvatarApplicationError = ApplicationErrorCode<
UpdateAvatarErrorCode,
{ message: string }
>;
export class UpdateAvatarUseCase {
constructor(
private readonly avatarRepo: IAvatarRepository,
private readonly output: UseCaseOutputPort<UpdateAvatarResult>,
private readonly logger: Logger,
) {}
async execute(input: UpdateAvatarInput): Promise<Result<void, UpdateAvatarApplicationError>> {
this.logger.info('[UpdateAvatarUseCase] Updating avatar', {
driverId: input.driverId,
mediaUrl: input.mediaUrl,
});
try {
const currentAvatar = await this.avatarRepo.findActiveByDriverId(input.driverId);
if (currentAvatar) {
currentAvatar.deactivate();
await this.avatarRepo.save(currentAvatar);
}
const avatarId = uuidv4(); // TODO this ID should be a value object
const newAvatar = Avatar.create({
id: avatarId,
driverId: input.driverId,
mediaUrl: input.mediaUrl,
});
await this.avatarRepo.save(newAvatar);
this.output.present({
avatarId,
driverId: input.driverId,
});
this.logger.info('[UpdateAvatarUseCase] Avatar updated successfully', {
driverId: input.driverId,
avatarId,
});
return Result.ok(undefined);
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
this.logger.error('[UpdateAvatarUseCase] Error updating avatar', err, {
driverId: input.driverId,
});
return Result.err({
code: 'REPOSITORY_ERROR',
details: { message: err.message ?? 'Internal error occurred while updating avatar' },
});
}
}
}