Skip to content

Conversation

@twalla26
Copy link
Collaborator

Note

  • 작성자: 송수민
  • 작성 날짜: 2024.11.27

✅ 체크리스트

  • 코드가 정상적으로 작동하는지 확인했습니다.
  • 주요 변경사항에 대한 설명을 작성했습니다.
  • 코드 스타일 가이드에 따라 코드를 작성했습니다.

🧩 작업 내용

  • nestjs-paginate 라이브러리 설치
  • 질문지들을 조회하는 기능에 pagination 구현
    • 전체 질문지 조회 기능
    • 카테고리별 질문지 조회 기능
    • 내가 만든 질문지 조회 기능
    • 내가 스크랩한 질문지 조회 기능

📝 작업 상세 내역

nestjs-paginate 라이브러리 설치

  • 'pagination을 처음부터 모두 구현할까?' 하다가 pagination을 공부하고 직접 구현하는게 이번 프로젝트 목표와는 거리가 먼 것 같다는 생각이 들었습니다.
  • 'pagination을 쉽게 만들어둔 라이브러리가 없을까?'라는 생각으로 라이브러리를 검색했고, nestjs-paginate을 선택했습니다.
  • 사실 nestjs-typeorm-paginate라는 라이브러리도 있었지만, typeorm에 종속되는 라이브러리이며 비교적 사용 방법이 복잡해서 nestjs-paginate을 선택했습니다.
  • 두 라이브러리를 자세히 비교한 정보는 다음 링크에서 확인하실 수 있습니다.

pagination 구현

  • 전체 질문지 조회 기능 코드
    // question-list.service.ts
    async getAllQuestionLists(query: PaginateQuery) { // paginate query는 page와 limit 등을 포함함.
        const allQuestionLists: GetAllQuestionListDto[] = [];
    
        const publicQuestionLists = await this.questionListRepository.findPublicQuestionLists(); // 쿼리 빌더를 반환
        const result = await paginate(query, publicQuestionLists, { // paginate(): 라이브러리에서 제공하는 함수
            sortableColumns: ["usage"], 
            defaultSortBy: [["usage", "DESC"]], // 디폴트로 사용량이 많은 순으로 반환하게 구현함.
        });
    
        for (const publicQuestionList of result.data) {
            const { id, title, usage } = publicQuestionList;
            const categoryNames: string[] =
                await this.questionListRepository.findCategoryNamesByQuestionListId(id);
    
            const questionCount =
                await this.questionListRepository.getQuestionCountByQuestionListId(id);
    
            const questionList: GetAllQuestionListDto = {
                id,
                title,
                categoryNames,
                usage,
                questionCount,
            };
            allQuestionLists.push(questionList);
        }
        return { allQuestionLists, meta: result.meta }; // 메타데이터도 받아서 함께 전달해줌.
    }
    • 클라이언트에게 전달되는 meta 데이터는 다음 형태를 띕니다.
      "meta": {
          "itemsPerPage": 5,
          "totalItems": 16,
          "currentPage": "1",
          "totalPages": 4,
          "sortBy": [
              [
                  "usage",
                  "DESC"
              ]
          ]
      }

📌 테스트 및 검증 결과

  • postman으로 시험한 결과
    image

💬 다음 작업 또는 논의 사항

  • 질문지 수정 기능 구현

📎 참고 자료

Copy link
Member

@yiseungyun yiseungyun left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

맞아요. 시간이 부족할 땐 일단 라이브러리를 사용하는게 좋은 선택 같습니다!
나중에 라이브러리가 불편하거나 안 좋은 점이 있다면 바꿔도 되니까요.
수고하셨습니당. 수민뭼. 👍

Copy link
Collaborator

@blu3fishez blu3fishez left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pagination 적용하신게 대부분이고, 리팩토링도 잘 되어가시는 것 같아서 보기 좋습니다!

끝까지 화이팅입니다~!

Comment on lines +22 to +25
return this.dataSource
.getRepository(QuestionList)
.createQueryBuilder("question_list")
.where("question_list.is_public = :isPublic", { isPublic: true });
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 코드 보면서 느끼는건데, ORM 쓰길 엄청 잘했다고 생각듭니다 ㅋㅋ 코드가 엄청 깔끔하네요

Comment on lines -36 to +43
return this.dataSource.getRepository(QuestionList).find({
where: {
isPublic: true,
categories: { id: categoryId },
},
relations: ["categories"],
});
return this.dataSource
.getRepository(QuestionList)
.createQueryBuilder("question_list")
.innerJoin("question_list.categories", "category")
.where("question_list.is_public = :isPublic", { isPublic: true })
.andWhere("category.id = :categoryId", { categoryId });
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

깔끔하게 리팩토링 된 것 같아서 좋습니다! 쿼리빌더 이제 잘 활용하시는 것 같아서� 같은 백엔드 개발자로써 뿌듯하네용 ㅎㅎㅎ

Comment on lines +24 to +27
const result = await paginate(query, publicQuestionLists, {
sortableColumns: ["usage"],
defaultSortBy: [["usage", "DESC"]],
});
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sort 기준과 기본 sort 기준까지.. 괜찮네요! 이부분 나중에 enum으로 리팩토링 해보시겠다고 하셨는데 이쪽에서도 활용해보시면 괜찮을 것 같네요!

Copy link
Member

@ShipFriend0516 ShipFriend0516 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

페이지네이션 어려운 부분이었을텐데 고생하셨습니다

6주 끝나고 바꿔보는 것도..?ㅎㅎㅎ

@ShipFriend0516 ShipFriend0516 merged commit cb8dcb7 into boostcampwm-2024:dev Nov 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants