Skip to content

Commit

Permalink
add bookmarking a recipe functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
atakanyasar committed May 10, 2024
1 parent f3ff820 commit 50d8d6e
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,21 @@ public ResponseEntity<?> rateRecipe(@PathVariable Integer recipeId, @RequestBody
}
}

@PostMapping("/recipes/{recipeId}/bookmarks")
public ResponseEntity<?> bookmarkRecipe(@PathVariable Integer recipeId) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || authentication.getPrincipal().equals("anonymousUser")) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Authentication required.");
}

String username = authentication.getName(); // Assuming the username can be obtained like this
boolean success = recipeService.bookmarkRecipe(recipeId, username);

if (success) {
return ResponseEntity.ok().body("Recipe bookmarked successfully");
} else {
return ResponseEntity.badRequest().body("Failed to bookmark recipe");
}
}

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

import java.util.List;
import java.util.Optional;

@Repository
public interface BookmarkRepository extends JpaRepository<Bookmark,Integer> {
List<Bookmark> findByUserId(Integer userId);
List<Bookmark> findByRecipeId(Integer recipeId);
Optional<Bookmark> findByUserIdAndRecipeId(Integer userId, Integer recipeId);

}


Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ public class RecipeService {
private UserRepository userRepository;
@Autowired
private RatingRepository ratingRepository;
@Autowired
private BookmarkRepository bookmarkRepository;

@Transactional
public RecipeDetailDto createRecipe(NewRecipeDto newRecipe, String username) throws Exception {
Expand Down Expand Up @@ -115,4 +117,27 @@ public boolean rateRecipe(Integer recipeId, String username, Integer ratingValue
}
return false;
}

public boolean bookmarkRecipe(Integer recipeId, String username) {
User user = userRepository.findByUsername(username).orElse(null);
if (user == null){
return false;
}
Recipe recipe = recipeRepository.findById(recipeId).orElse(null);
if (recipe == null){
return false;
}
if (bookmarkRepository.findByUserIdAndRecipeId(user.getId(), recipeId).isPresent()){
return false;
}

Bookmark bookmark = Bookmark.builder()
.user(user)
.recipe(recipe)
.build();
bookmarkRepository.save(bookmark);

return true;
}

}

0 comments on commit 50d8d6e

Please sign in to comment.