public async Task <IActionResult> GetUsersVoteFromPost(string id, string postId) { var userId = User.FindFirst(ClaimTypes.Name)?.Value; var post = _postService.Get(postId); if (post == null) { return(NotFound(new { message = "Post was not found" })); } var vote = await _voteService.FindByUserAndResponseId(userId, postId); if (vote == null) { // Return null for frontend to handle return(Ok(null)); } return(Ok(new VoteResponseDTO { UserVote = Enum.GetName(typeof(VoteType), vote.UserVote), NumVotes = post.NumVotes })); }
public async Task <IActionResult> VoteOnPost(string id, [Required] string voteType) { var userId = User.FindFirst(ClaimTypes.Name)?.Value; // Check if the request sent a valid vote if (!Enum.IsDefined(typeof(VoteType), voteType)) { return(BadRequest(new { message = "Invalid vote" })); } // Create var with enum value Enum.TryParse(voteType, out VoteType vote); var post = _postService.Get(id); if (post == null) { return(NotFound(new { message = "Post was not found" })); } // Used to determine if a vote should be cancelled or reversed if it exists var foundVote = await _voteService.FindByUserAndResponseId(userId, post.Id); if (foundVote == null) { // No vote has been registered, so create one and add to tally post = _postService.VoteOnPost(post, vote); await _voteService.Add(new Vote { UserVote = vote, UserId = userId, ResponseId = post.Id }); } else if (foundVote.UserVote == vote) { // Clear vote if same vote was selected // Set to opposite vote to negate user's vote var negatingVote = vote == VoteType.Up ? VoteType.Down : VoteType.Up; post = _postService.VoteOnPost(post, negatingVote); await _voteService.Remove(foundVote.Id); } else { // Can be implied at this point that the user changed their vote // to the opposite // Since they chose the opposite vote, offset is set to two post = _postService.VoteOnPost(post, vote, 2); // Set vote document to the opposite vote foundVote.UserVote = vote; await _voteService.Update(foundVote); } return(Ok(new VoteResponseDTO { UserVote = Enum.GetName(typeof(VoteType), vote), NumVotes = post.NumVotes })); }