Spring Instagram clone (Feed, Likes)

Hyeonseop-Noh·2022년 4월 11일
0

Feed

In ImageRepository, add the native query to select images from following users. Get the image from toUserId and show in the fromUserId's feed.

public interface ImageRepository extends JpaRepository<Image, Integer> {

    @Query(value = "SELECT * FROM image WHERE userId IN (SELECT toUserId FROM subscribe WHERE fromUserId = :principalId) ORDER BY id DESC", nativeQuery = true)
    Page<Image> mStory(int principalId, Pageable pageable);

}

In ImageService, import images from ImageRepository

public Page<Image> imageStory(int principalId, Pageable pageable) {
    Page<Image> images = imageRepository.mStory(principalId, pageable);
    return images;
}

Use ImageApiController and call the imageService. (There are 5 images in one page by default)

public class ImageApiController {

    private final ImageService imageService;

    @GetMapping("/api/image")
    public ResponseEntity<?> imageStory(@AuthenticationPrincipal PrincipalDetails principalDetails,
                                        @PageableDefault(size = 5) Pageable pageable) {
        Page<Image> images = imageService.imageStory(principalDetails.getUser().getId(), pageable);
        return new ResponseEntity<>(new CMRespDto<>(1, "Success", images), HttpStatus.OK);
    }

}

Likes

Model

Get imageId from Image class by using native query.
Below code is interface

public interface LikesRepository extends JpaRepository<Likes, Integer> {

    @Modifying
    @Query(value = "INSERT INTO likes(imageId, userId, createDate) VALUES(:imageId, :principalId, now())", nativeQuery = true)
    int mLikes(int imageId, int principalId);

    @Modifying
    @Query(value = "DELETE FROM likes WHERE imageId = :imageId AND userId = :principalId", nativeQuery = true)
    int mUnLikes(int imageId, int principalId);

}

Controller

Make controller in ImageApiController. 'likes', 'unlikes' and each mapping -> PostMapping, DeleteMapping. add below

@PostMapping("/api/image/{imageId}/likes")
public ResponseEntity<?> likes(@PathVariable int imageId, @AuthenticationPrincipal PrincipalDetails principalDetails) {
    likesService.like(imageId, principalDetails.getUser().getId());
    return new ResponseEntity<>(new CMRespDto<>(1, "Like Success", null), HttpStatus.CREATED);
}

@DeleteMapping("/api/image/{imageId}/likes")
public ResponseEntity<?> unLikes(@PathVariable int imageId, @AuthenticationPrincipal PrincipalDetails principalDetails) {
    likesService.unLike(imageId, principalDetails.getUser().getId());
    return new ResponseEntity<>(new CMRespDto<>(1, "Unlike success", null), HttpStatus.CREATED);
}

Service

Get mLikes(imageId, principalId), mUnLikes(imageId, principalId) from LikesRepository.

Bug fix

In Likes model, import User -> Images -> User, Likes ...
Therefore, add under code to the private User in Likes.

@JsonIgnoreProperties({"images"})

profile
PlanBy Developer

0개의 댓글