public override async Task <CreateUserResponse> Handle(CreateUserRequest message) { var user = _mapper.Map <User>(message); if (user.UserKey == default) { return(Error(ErrorType.InvalidKey)); } var isEmailAddressUniqueHandler = new UserEmailExistsRequestHandler(_context); var request = new UserEmailExistsRequest { CurrentUserKey = message.UserKey, EmailAddress = message.EmailAddress }; var response = await isEmailAddressUniqueHandler.Handle(request); if (response.EmailExists) { return(Error(ErrorType.EmailExists)); } _context.Users.Add(user); if (!await _context.TrySaveChangesAsync()) { return(new CreateUserResponse()); } var userCreatedEvent = _mapper.Map <UserCreatedEvent>(user); await _bus.PublishAsync(userCreatedEvent); return(Success()); }
public override async Task <UpdateUserResponse> Handle(UpdateUserRequest message) { var existingUser = await _context.Users.FirstOrDefaultAsync(u => u.UserKey == message.UserKey); if (existingUser == null) { return(Error(ErrorType.NotFound)); } var isEmailAddressUniqueHandler = new UserEmailExistsRequestHandler(_context); var request = new UserEmailExistsRequest { CurrentUserKey = message.UserKey, EmailAddress = message.EmailAddress }; var response = await isEmailAddressUniqueHandler.Handle(request); if (response.EmailExists) { return(Error(ErrorType.EmailExists)); } _context.Entry(existingUser).CurrentValues.SetValues(message); if (!await _context.TrySaveChangesAsync()) { return(new UpdateUserResponse()); } var userUpdatedEvent = _mapper.Map <UserUpdatedEvent>(existingUser); await _bus.PublishAsync(userUpdatedEvent); return(Success()); }