39 lines
1.4 KiB
C#
39 lines
1.4 KiB
C#
using Heimdall.Application.Common;
|
|||
|
|
using Heimdall.Application.Common.Persistence;
|
||
|
|
using Heimdall.Application.DTOs;
|
||
|
|
using Heimdall.Domain.Entities;
|
||
|
|
using MediatR;
|
||
|
|
using Microsoft.AspNetCore.Identity;
|
||
|
|
|
||
|
|
namespace Heimdall.Application.Users.Commands.UpdateUser;
|
||
|
|
|
||
|
|
public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, ServiceResult<UserResponse>>
|
||
|
|
{
|
||
|
|
private readonly UserManager<AppUser> _userManager;
|
||
|
|
private readonly IUserRepository _repository;
|
||
|
|
|
||
|
|
public UpdateUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||
|
|
{
|
||
|
|
_userManager = userManager;
|
||
|
|
_repository = repository;
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<ServiceResult<UserResponse>> Handle(UpdateUserCommand command, CancellationToken ct)
|
||
|
|
{
|
||
|
|
var user = await _userManager.FindByIdAsync(command.Id.ToString());
|
||
|
|
if (user is null)
|
||
|
|
return ServiceResult<UserResponse>.NotFound("User not found");
|
||
|
|
|
||
|
|
user.DisplayName = command.DisplayName ?? user.DisplayName;
|
||
|
|
user.Theme = command.Theme ?? user.Theme;
|
||
|
|
user.Language = command.Language ?? user.Language;
|
||
|
|
|
||
|
|
var result = await _userManager.UpdateAsync(user);
|
||
|
|
if (!result.Succeeded)
|
||
|
|
return ServiceResult<UserResponse>.Failure(
|
||
|
|
string.Join(", ", result.Errors.Select(e => e.Description)));
|
||
|
|
|
||
|
|
var response = await _repository.GetByIdAsync(user.Id, ct);
|
||
|
|
return ServiceResult<UserResponse>.Success(response!);
|
||
|
|
}
|
||
|
|
}
|