85 lines
2.5 KiB
TypeScript
85 lines
2.5 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';
|
|
import { AvatarId } from '../../domain/value-objects/AvatarId';
|
|
|
|
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 = AvatarId.create(uuidv4());
|
|
const newAvatar = Avatar.create({
|
|
id: avatarId.toString(),
|
|
driverId: input.driverId,
|
|
mediaUrl: input.mediaUrl,
|
|
});
|
|
|
|
await this.avatarRepo.save(newAvatar);
|
|
|
|
this.output.present({
|
|
avatarId: avatarId.toString(),
|
|
driverId: input.driverId,
|
|
});
|
|
|
|
this.logger.info('[UpdateAvatarUseCase] Avatar updated successfully', {
|
|
driverId: input.driverId,
|
|
avatarId: avatarId.toString(),
|
|
});
|
|
|
|
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' },
|
|
});
|
|
}
|
|
}
|
|
} |