public async Task <Unit> Handle(UpdatePersonCommand request, CancellationToken cancellationToken)
        {
            var personToUpdate = await _personRepository.GetByIdAsync(request.PersonId);

            if (personToUpdate == null)
            {
                _logger.LogError($"Update person: Not found exception raised. Person Id: {request.PersonId}");
                throw new NotFoundException(nameof(Person), request.PersonId);
            }

            var validator        = new UpdatePersonCommandValidator();
            var validationResult = await validator.ValidateAsync(request);

            if (validationResult.Errors.Count > 0)
            {
                throw new ValidationException(validationResult);
            }

            _mapper.Map(request, personToUpdate, typeof(UpdatePersonCommand), typeof(Person));

            try
            {
                await _personRepository.UpdateAsync(personToUpdate);

                _cachedPersonsService.DeleteCachedPersons();
            }
            catch (Exception ex)
            {
                _logger.LogError($"Update person failed due to an error. {ex.Message}");
                throw new BadRequestException(nameof(Person));
            }

            return(Unit.Value);
        }
Esempio n. 2
0
        public async Task <CreatePersonCommandResponse> Handle(CreatePersonCommand request, CancellationToken cancellationToken)
        {
            var personCommandResponse = new CreatePersonCommandResponse();

            var validator        = new CreatePersonCommandValidator();
            var validationResult = await validator.ValidateAsync(request);

            if (validationResult.Errors.Count > 0)
            {
                personCommandResponse.Success          = false;
                personCommandResponse.ValidationErrors = new List <string>();
                foreach (var error in validationResult.Errors)
                {
                    personCommandResponse.ValidationErrors.Add(error.ErrorMessage);
                }
            }

            if (personCommandResponse.Success)
            {
                var person = _mapper.Map <Person>(request);
                try
                {
                    person = await _personRepository.AddAsync(person);

                    _cachedPersonsService.DeleteCachedPersons();
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Create person failed due to an error. {ex.Message}");
                    throw new Exception(nameof(Person));
                }

                personCommandResponse.Person = _mapper.Map <PersonDto>(person);
            }


            return(personCommandResponse);
        }