public async Task <PostInsertDto> AddPost(PostInsertDto postDto, int?currentUserId) { var post = _mapper.Map <PostInsertDto, Post>(postDto); post.AuthorId = currentUserId.Value; await _postsRepository.AddAsync(post); await _unitOfWork.CompleteAsync(); return(postDto); }
public async Task <ActionResult> AddPost([FromBody] PostInsertDto post) { try { var postAdded = await _postsService.AddPost(post, ClaimResolver.getUserIdFromToken(User)); return(Ok(postAdded)); } catch (Exception Ex) { return(BadRequest("The post cannot be added due to bad connection with the database" + Ex.Message)); } }
public async Task UpdatePost_Throw_PostNotFoundException() { //Arrange var postToUpdate = new PostInsertDto { Text = "Test text", Title = "Test title" }; var post = new Post { Text = "new text", Title = "new title", AuthorId = 3 }; _postRepositoryMock.Setup(p => p.GetByIdAsync(It.IsAny <int>())).ReturnsAsync((Post)null); //Act and Assert Assert.ThrowsAsync <PostNotFoundException>(() => _postService.UpdatePost(postToUpdate, 2, 3)); }
public async Task UpdatePost_Throw_UserHasNotPermissionException() { //Arrange var postToUpdate = new PostInsertDto { Text = "Test text", Title = "Test title" }; var post = new Post { Text = "new text", Title = "new title", AuthorId = 3, Id = 2 }; _postRepositoryMock.Setup(p => p.GetByIdAsync(post.Id)).ReturnsAsync(post); //Act and Assert Assert.ThrowsAsync <UserHasNotPermissionException>(() => _postService.UpdatePost(postToUpdate, post.Id, 2)); }
public async Task UpdatePost(PostInsertDto post, int id, int?currentUserId) { var postToUpdate = await _postsRepository.GetByIdAsync(id); if (postToUpdate == null) { throw new PostNotFoundException(id.ToString()); } if (!postToUpdate.AuthorId.Equals(currentUserId.Value)) { throw new UserHasNotPermissionException(); } postToUpdate.Text = post.Text ?? postToUpdate.Text; postToUpdate.Title = post.Title ?? postToUpdate.Title; _postsRepository.Update(postToUpdate); await _unitOfWork.CompleteAsync(); }
public async Task <ActionResult> UpdatePost([FromBody] PostInsertDto post, [FromRoute] int id) { try { await _postsService.UpdatePost(post, id, ClaimResolver.getUserIdFromToken(User)); return(Ok("The post was updated successfully")); } catch (PostNotFoundException ex) { return(NotFound(ex.Message)); } catch (UserHasNotPermissionException ex) { return(Unauthorized(ex.Message)); } catch (Exception ex) { return(BadRequest("The post cannot be updated due to bad connection with the database" + ex.Message)); } }