티스토리 뷰

팀프로젝트 - 페이지네이션 구현

limit과 offset을 이용해서 간단히 페이지네이션을 구현할 수 있었다. 아래는 3계층 구조로 구현한 전체 상품 조회 기능이다. repository 계층에서 평소에 사용하던 findAll()이 아닌 findAndCountAll을 통해서 전체 데이터 수까지 이용할 수 있도록 했다.

 

controller

  adminGetAllProducts = async (req, res, next) => {
    try {
      let limit = 3;
      let offset = 0 + (req.query.page - 1) * limit;
      const productsInfo = await this.productService.adminFindAllProducts(
        limit,
        offset
      );
      return res.status(200).json({
        totalPage: Math.ceil(productsInfo.count / limit),
        data: productsInfo.rows,
      });
    } catch (error) {
      return res.status(400).json({
        errorMessage: '회원 정보 조회에 실패하였습니다.',
      });
    }
  };

service

  adminFindAllProducts = async (limit, offset) => {
    const products = await this.ProductRepository.adminFindAllProducts(limit, offset);
    return products
  };

repository

  adminFindAllProducts = async (limit, offset) => {
    const products = await this.productModel.findAndCountAll({
      raw: true,
      offset: offset,
      limit: limit,
      order: [['updatedAt', 'ASC']],
  });

 

커서 페이지네이션도 시간이 나면 구현해보고 싶다. sequelize-cursor-pagination 모듈을 이용하여 구현해보고자 하였으나 쉽지 않았다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함