#24 simple sns: 좋아요 개수 api
This commit is contained in:
@@ -61,4 +61,9 @@ public class PostController {
|
||||
return Response.success();
|
||||
}
|
||||
|
||||
@GetMapping("/{postId}/likes")
|
||||
public Response<Integer> likeCount(@PathVariable Integer postId, Authentication authentication) {
|
||||
return Response.success(postService.likeCount(postId));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -4,12 +4,20 @@ import com.example.sns.model.entity.LikeEntity;
|
||||
import com.example.sns.model.entity.PostEntity;
|
||||
import com.example.sns.model.entity.UserEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface LikeEntityRepository extends JpaRepository<LikeEntity, Integer> {
|
||||
|
||||
Optional<LikeEntity> findByUserAndPost(UserEntity user, PostEntity post);
|
||||
|
||||
@Query(value = "SELECT COUNT(*) FROM LikeEntity entity WHERE entity.post =:post")
|
||||
Integer countByPost(@Param("post") PostEntity post);
|
||||
|
||||
List<LikeEntity> findAllByPost(PostEntity post);
|
||||
}
|
||||
|
||||
@@ -141,4 +141,17 @@ public class PostService {
|
||||
// save like
|
||||
likeEntityRepository.save(LikeEntity.of(userEntity, postEntity));
|
||||
}
|
||||
|
||||
public int likeCount(Integer postId) {
|
||||
PostEntity postEntity = postEntityRepository.findById(postId)
|
||||
.orElseThrow(
|
||||
() -> new SnsApplicationException(
|
||||
POST_NOT_FOUND,
|
||||
String.format("%s not founded", postId)
|
||||
)
|
||||
);
|
||||
|
||||
// count like
|
||||
return likeEntityRepository.countByPost(postEntity);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user