public async Task <IActionResult> Create([FromBody] QuestViewModel quest) { ValidationResult validationResults = null; Quest newQuest; //Start by validating the data to ensure we have everything we need to add a new quest try { if (!ModelState.IsValid)//View Model Validation Failed { // TO DO throw new ValidationException("ViewModel Validation Failed"); } else // View Model validation was fine so check the actual model { newQuest = Mapper.Map <Quest>(quest); QuestValidator validator = new QuestValidator(); validationResults = validator.Validate(newQuest); if (!validationResults.IsValid) // Model validation failed { throw new ValidationException("Model validation failed"); } } } catch (ValidationException ex) //The quest the user is trying to add is invalid { MessageObject message = _messageService.BuildMessage("Error", "validationFailed", "Validation Failed", "Validation Failed. Please check the specified values and try again.", ex, validationResults); return(BadRequest(message)); } catch (Exception ex) // something unexepected went wrong so output a generic error message { MessageObject message = _messageService.BuildMessage("Error", "addError", "Process Error", "An unexpected error occurred while adding the quest", ex); return(BadRequest(message)); } //The validation was fine so add the quest to the database try { if (!newQuest.Active) { newQuest.Active = true; // default to active when created - the user can mark them as not active later if they like } _repository.CreateQuest(newQuest); await _repository.SaveChangesAsync(); ModelState.Clear(); //Quest was added successfully return(CreatedAtAction("Get", new { id = newQuest.Id }, Mapper.Map <QuestViewModel>(newQuest))); } catch (Exception ex)// Something went wrong while adding the record { MessageObject message = _messageService.BuildMessage("Error", "addError", "Process Error", "An error occurred while trying to add the record.", ex); return(BadRequest(message)); } }
public QuestController(IQuestRepository repository) { _repository = repository; _validator = new QuestValidator(); }