#24 simple sns: 좋아요 개수 api

This commit is contained in:
haerong22
2022-11-22 02:21:42 +09:00
parent fc328f92b8
commit 02fd021a07
3 changed files with 26 additions and 0 deletions

View File

@@ -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));
}
}

View File

@@ -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);
}

View File

@@ -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);
}
}