Skip to content

Commit

Permalink
Add Delete Upvote Endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
Cgtycolak committed May 11, 2024
1 parent 039fec5 commit 7b58925
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -98,5 +98,19 @@ public ResponseEntity<?> getBookmarks(@PathVariable Integer recipeId) {
return ResponseEntity.ok().body(whoBookmarked);
}

@DeleteMapping("/recipes/{recipeId}/comments/{commentId}/upvote")
public ResponseEntity<?> deleteUpvote(@PathVariable Integer commentId) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || authentication.getPrincipal().equals("anonymousUser")) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Authentication required.");
}
String username = authentication.getName();
boolean success = recipeService.deleteUpvote(commentId, username);
if (success) {
return ResponseEntity.ok().body("Upvote removed successfully.");
} else {
return ResponseEntity.badRequest().body("Failed to remove upvote.");
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UpvoteRepository extends JpaRepository<Upvote,Integer> {
public interface UpvoteRepository extends JpaRepository<Upvote, Integer> {
Optional<Upvote> findByCommentIdAndUserId(Integer commentId, Integer userId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ public class RecipeService {
private RatingRepository ratingRepository;
@Autowired
private BookmarkRepository bookmarkRepository;
@Autowired
private UpvoteRepository upvoteRepository;

@Transactional
public RecipeDetailDto createRecipe(NewRecipeDto newRecipe, String username) throws Exception {
Expand Down Expand Up @@ -145,4 +147,19 @@ public List<User> getWhoBookmarked(Integer recipeId) {
return bookmarkRepository.findByRecipeId(recipeId).stream().map(Bookmark::getUser).toList();
}

@Transactional
public boolean deleteUpvote(Integer commentId, String username) {
User user = userRepository.findByUsername(username).orElse(null);
if (user == null) {
return false;
}
Optional<Upvote> upvote = upvoteRepository.findByCommentIdAndUserId(commentId, user.getId());
if (upvote.isPresent()) {
upvoteRepository.delete(upvote.get());
return true;
}
return false;
}


}

0 comments on commit 7b58925

Please sign in to comment.