개발일지

[NestJS] 투표 글 조회 구현 본문

NestJS, Node.js/#01 Project - 투표 커뮤니티

[NestJS] 투표 글 조회 구현

lyjin 2022. 11. 7.

투표글 조회

  • 생성된 투표글 목록 조회
    • 투표 제목, 전체 투표수, 좋아요 수
  • 세부 내용 조회
    • 투표 제목, 전체 투표수, 좋아요 수, 선택지, 선택지별 투표수
    • 좋아요를 누를 수 있습니다.

 


투표글 목록 조회

// 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

includeVote 와 연결된 데이터들을 포함한 값을 보여줍니다. 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 구조가 복잡하다고 느꼈다. 어떻게 개선할 지 생각 중