Skip to content

Commit

Permalink
GET users/{userId} endpoint implemented.(User Profile & bookmark reci…
Browse files Browse the repository at this point in the history
…pe related infos.)
  • Loading branch information
EnesBaserr committed May 13, 2024
1 parent 83e1d60 commit 6e2d31d
Show file tree
Hide file tree
Showing 7 changed files with 171 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
package com.group1.cuisines.controllers;

import com.group1.cuisines.dao.response.ErrorResponse;
import com.group1.cuisines.dao.response.SuccessResponse;
import com.group1.cuisines.dto.UserDto;
import com.group1.cuisines.dto.UserProfileDto;
import com.group1.cuisines.entities.User;
import com.group1.cuisines.repositories.UserRepository;
import com.group1.cuisines.services.UserService;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
Expand All @@ -25,6 +30,18 @@ public class UserController {
private final UserService userService;
private final UserRepository userRepository;


@GetMapping("/{userId}")
public ResponseEntity<?> getUserById(@PathVariable Integer userId, Authentication authentication) {
String currentUsername = authentication != null ? authentication.getName() : null;
try {
UserProfileDto userProfile = userService.getUserProfileById(userId, currentUsername);
return ResponseEntity.ok(new SuccessResponse<>(userProfile, "User profile fetched successfully"));
} catch (EntityNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ErrorResponse("User not found"));
}
}

@GetMapping("/me")
public ResponseEntity<?> getUserDetails(@AuthenticationPrincipal UserDetails userDetails) {
if (userDetails instanceof com.group1.cuisines.entities.User) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.group1.cuisines.dao.response;
import lombok.*;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class ErrorResponse {
private String message;
}
21 changes: 21 additions & 0 deletions backend/src/main/java/com/group1/cuisines/dto/BookmarkDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.group1.cuisines.dto;
import lombok.*;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BookmarkDto {

private Integer id;
private String name;
private String instructions;
private List<IngredientsDto> ingredients;
private int servingSize;
private Integer cookTime;
//private List<String> images;
private CuisineDto cuisine;
private DishDto dish;
private Double avgRating;

private AuthorDto author;
}
24 changes: 24 additions & 0 deletions backend/src/main/java/com/group1/cuisines/dto/UserProfileDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.group1.cuisines.dto;
import lombok.*;

import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor


public class UserProfileDto {
private Integer id;
private String username;
private String name;
private String bio;
private Integer followersCount;
private Integer followingCount;
//private String gender;
// private String profilePicture;
// private List<String> diets;
private Integer recipeCount;
private List<BookmarkDto> bookmarks;
private List<RecipeDetailsDto> recipes;
}
2 changes: 2 additions & 0 deletions backend/src/main/java/com/group1/cuisines/entities/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ public class User implements UserDetails {
private int recipeCount = 0;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Recipe> recipes = new HashSet<>();
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Bookmark> bookmarks = new HashSet<>();



Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ public List<User> getWhoBookmarked(Integer recipeId) {
return bookmarkRepository.findByRecipeId(recipeId).stream().map(Bookmark::getUser).toList();
}


public List<CommentsDto> getCommentsByRecipeId(Integer recipeId) {
return commentRepository.findByRecipeId(recipeId).stream()
.map(comment -> CommentsDto.builder()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package com.group1.cuisines.services;

import com.group1.cuisines.dto.*;
import com.group1.cuisines.entities.Bookmark;
import com.group1.cuisines.entities.Recipe;
import com.group1.cuisines.entities.User;
import com.group1.cuisines.repositories.UserRepository;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
Expand All @@ -14,6 +18,7 @@
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
Expand Down Expand Up @@ -108,4 +113,94 @@ public Set<User> getUserFollower(Integer userId) {
}
return Collections.emptySet();
}

public UserProfileDto getUserProfileById(Integer userId, String currentUsername) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new EntityNotFoundException("User not found"));

boolean isSelf = user.getUsername().equals(currentUsername);

UserProfileDto profile = new UserProfileDto();
profile.setId(user.getId());
profile.setUsername(user.getUsername());
profile.setName(user.getFirstName() + " " + user.getLastName());
profile.setBio(user.getBio());
profile.setFollowersCount(user.getFollowers().size());
profile.setFollowingCount(user.getFollowing().size());
profile.setRecipeCount(user.getRecipes().size());
profile.setRecipes(user.getRecipes().stream()
.map(this::convertToRecipeDetailsDto)
.collect(Collectors.toList()));

if (isSelf) {
profile.setBookmarks(user.getBookmarks().stream()
.map(this::convertToBookmarkDto)
.collect(Collectors.toList()));
} else {
profile.setBookmarks(Collections.emptyList());
}

return profile;
}

private RecipeDetailsDto convertToRecipeDetailsDto(Recipe recipe) {
CuisineDto cuisineDto = new CuisineDto();
if (recipe.getDish() != null && !recipe.getDish().getCuisines().isEmpty()) {

cuisineDto.setId(recipe.getDish().getCuisines().get(0).getId());
cuisineDto.setName(recipe.getDish().getCuisines().get(0).getName());

}
else if(recipe.getDish() != null && recipe.getDish().getCuisines().isEmpty()){
cuisineDto.setId("No cuisine Id from wikidata");
cuisineDto.setName("No cuisine name from wikidata");
}
return new RecipeDetailsDto(
recipe.getId(),
recipe.getTitle(),
recipe.getInstructions(),
recipe.getIngredients().stream()
.map(ingredient -> new IngredientsDto(ingredient.getName()))
.collect(Collectors.toList()),
recipe.getCookingTime(),
recipe.getServingSize(),
cuisineDto,
new DishDto(recipe.getDish().getId(), recipe.getDish().getName(), recipe.getDish().getImage()),
recipe.getAverageRating(),
new AuthorDto(recipe.getUser().getId(), recipe.getUser().getUsername(), recipe.getUser().getFirstName(),
recipe.getUser().getFollowerCount(),recipe.getUser().getRecipeCount())
);
}

private BookmarkDto convertToBookmarkDto(Bookmark bookmark) {

Recipe recipe = bookmark.getRecipe();
CuisineDto cuisineDto = new CuisineDto();
if (recipe.getDish() != null && !recipe.getDish().getCuisines().isEmpty()) {

cuisineDto.setId(recipe.getDish().getCuisines().get(0).getId());
cuisineDto.setName(recipe.getDish().getCuisines().get(0).getName());

}
else if(recipe.getDish() != null && recipe.getDish().getCuisines().isEmpty()){
cuisineDto.setId("No cuisine Id from wikidata");
cuisineDto.setName("No cuisine name from wikidata");
}
return new BookmarkDto(
recipe.getId(),
recipe.getTitle(),
recipe.getInstructions(),
recipe.getIngredients().stream()
.map(ingredient -> new IngredientsDto(ingredient.getName()))
.collect(Collectors.toList()),
recipe.getServingSize(),
recipe.getCookingTime(),
//recipe.getImages(),
cuisineDto,
new DishDto(recipe.getDish().getId(), recipe.getDish().getName(), recipe.getDish().getImage()),
recipe.getAverageRating(),
new AuthorDto(recipe.getUser().getId(), recipe.getUser().getUsername(), recipe.getUser().getFirstName(),
recipe.getUser().getFollowerCount(),recipe.getUser().getRecipeCount())
);
}
}

0 comments on commit 6e2d31d

Please sign in to comment.