개발일지
[NestJS] 투표 글 조회 구현 본문
투표글 조회
- 생성된 투표글 목록 조회
- 투표 제목, 전체 투표수, 좋아요 수
- 세부 내용 조회
- 투표 제목, 전체 투표수, 좋아요 수, 선택지, 선택지별 투표수
- 좋아요를 누를 수 있습니다.
투표글 목록 조회
// votes/votes.controller.ts
@Get()
async listVotes(): Promise<ListVotes> {
return { votes: await this.votesRepository.getAllVotes() };
}
// votes/votes.repository.ts
async getAllVotes(): Promise<Votes[]> {
return await this.prisma.votes.findMany({
include: {
voteChoices: {
select: {
id: true,
title: true,
},
},
_count: {
select: {
votedUsers: true,
likedUsers: true,
},
},
},
});
}
include
include
는 Vote
와 연결된 데이터들을 포함한 값을 보여줍니다. include 안에서도 원하는 필드들만 select
해줄 수 있습니다. 🔗prisma-nested read
_count
3.0.1 버전부터 _count
를 제공해줍니다. 연결된 레코드 수를 계산할 수 있습니다. 투표 수(votedUsers) 와 좋아요 수(likedUsers)를 계산 하기 위해 사용했습니다.
세부 내용 조회
// votes/votes.controller.ts
@Get(':voteId')
async getVote(
@Param('voteId', ParseIntPipe) voteId: number,
): Promise<GetVote> {
return { vote: await this.votesRepository.getVoteById(voteId) };
}
param으로 받아온 voteId
로 해당하는 vote만 불러옵니다. getAllVotes()
와 비슷하나 각 선택지 별 투표수를 보여주기 위한 _count
추가합니다.
// votes/votes.repository.ts'
async getVoteById(voteId: number): Promise<Votes> {
return await this.prisma.votes.findFirst({
where: {
id: voteId,
},
include: {
voteChoices: {
include: {
_count: {
select: {
votedUsers: true,
},
},
},
},
_count: {
select: {
votedUsers: true,
likedUsers: true,
},
},
},
});
}
개선할 점
include, select
와 _count
를 혼합해서 사용하다보니 response 구조가 복잡하다고 느꼈다. 어떻게 개선할 지 생각 중
'NestJS, Node.js > #01 Project - 투표 커뮤니티' 카테고리의 다른 글
[NestJS] 댓글 작성 구현 (0) | 2022.11.09 |
---|---|
[NestJS] 투표 글 수정 및 삭제 구현 - Utility Types (0) | 2022.11.09 |
[NestJS] 투표 글 좋아요 및 취소 구현 (0) | 2022.11.07 |
[NestJS] 투표 하기 구현 (0) | 2022.11.03 |
[NestJS] 투표 글 생성하기 구현 (0) | 2022.11.03 |