public async Task <IActionResult> Post([FromBody] Eager.Post post) { var postMapped = _mapper.Map <Models.Post>(post); var validationErrors = PostValidator.OnPostCreateValidation(postMapped); if (!_userRepository.Exists(postMapped.Author.Id)) { validationErrors.Append(CommonResponseMessages.AuthorDoesNotExists); } if (!postMapped.PostCategories.All(pc => _categoryRepository.Exists(pc.CategoryId))) { validationErrors.Append(CommonResponseMessages.OneOfCategoriesDoesNotExists); } if (validationErrors.Any()) { return(BadRequest(validationErrors)); } else { postMapped.Visits = 0; postMapped.CreatedOn = DateTime.Now; postMapped.ModifiedOn = null; postMapped.Slug = GenerateSlug(postMapped.Title); var createdPost = await _postRepository.Create(postMapped); return(Created($"{this.Request.Scheme}://{this.Request.Host}/api/Posts/{postMapped.Slug}", null)); } }
public async Task <IActionResult> Put([FromBody] Eager.Post post) { if (!post.Id.HasValue || post.Id.Value.Equals(Guid.Empty)) { return(BadRequest(CommonResponseMessages.NoId)); } else if (!_postRepository.Exists(post.Id.Value)) { return(NoContent()); } var postMapped = _mapper.Map <Models.Post>(post); var validationErrors = PostValidator.OnPostCreateValidation(postMapped); if (!_userRepository.Exists(postMapped.Author.Id)) { validationErrors.Append(CommonResponseMessages.AuthorDoesNotExists); } if (!postMapped.PostCategories.All(pc => _categoryRepository.Exists(pc.CategoryId))) { validationErrors.Append(CommonResponseMessages.OneOfCategoriesDoesNotExists); } if (validationErrors.Any()) { return(BadRequest(validationErrors)); } else { var dbPost = await _postRepository.GetPostsById(postMapped.Id); foreach (var relation in dbPost.PostCategories.ToList()) { if (!postMapped.PostCategories.Any(pc => pc.PostId.Equals(relation.PostId) && pc.CategoryId.Equals(relation.CategoryId))) { await _postRepository.RemoveRelation(relation); } } foreach (var relation in postMapped.PostCategories) { if (!dbPost.PostCategories.Any(pc => pc.PostId.Equals(relation.PostId) && pc.CategoryId.Equals(relation.CategoryId))) { await _postRepository.CreateRelation(relation); } } postMapped.Visits = dbPost.Visits; postMapped.CreatedOn = dbPost.CreatedOn; postMapped.ModifiedOn = DateTime.Now; postMapped.Slug = GenerateSlug(postMapped.Title); var postUpdated = await _postRepository.Update(postMapped); return(Ok()); } }