티스토리 뷰

728x90
반응형

목차

     

     

    이 글은 지난 글에 합쳐서 쓰려다 분량이 애매해서 분리한 글이다.

     

    내용은 그렇게 많지 않은데 코드가 갈수록 길어지니까 괜히 양이 부풀어 보여서.

     

    그렇다고 레포지토리를 공유하기엔 현재 글과 버전이 맞지 않아 크게 의미가 없을 것 같기도 해서

     

    일단 고민 중이다.

     

    이 글에선 간단하게 피드와 코멘트에 대한 페이지네이션을 구현하겠다.

     

    구현 후 프로젝트 구성은 아래와 같다.

     

     

    /src/interface

     

    인터페이스를 위한 폴더를 새로 만들었다. 앞으로 얼마나 사용하게 될지는 모르겠지만

     

    코드의 내용이 미들웨어도 아니고 유틸도 아닌 것 같아 따로 분리시켜 보았다.

     

    /PagenatedRequest.ts

     

    import { Request } from 'express';
    
    export interface PaginatedRequest extends Request {
      query: {
        page?: string;
        limit?: string;
      };
    }

     

     

    /src/controllers

     

    /feedController.ts

     

    const getAllFeeds = asyncHandler(async (req: PaginatedRequest, res: Response) => {
      const page = parseInt(req.query.page || '1', 10);
      const limit = parseInt(req.query.limit || '10', 10);
      const skip = (page - 1) * limit;
    
      const total = await Feed.countDocuments();
      const feeds = await Feed.find({}).sort({ createdAt: -1 }).skip(skip).limit(limit).populate('comments');
      const feedsWithCommentsCount = feeds.map((feed) => {
        const commentsCount = feed.comments.length;
        return { ...feed.toObject(), commentsCount };
      });
    
      const isLastPage = page * limit >= total;
      const currentPageDocumentCount = feeds.length;
    
      res.json({
        total,
        pages: Math.ceil(total / limit),
        curruentPage: page,
        isLastPage,
        currentPageDocumentCount,
        feedsWithCommentsCount,
      });
    });

     

     

    commentController.ts

     

    const getCommentsByFeedSeq = asyncHandler(async (req: PaginatedRequest, res: Response) => {
      const feedSeq = Number(req.params.feedSeq);
    
      const page = parseInt(req.query.page || '1', 10);
      const limit = parseInt(req.query.limit || '10', 10);
      const skip = (page - 1) * limit;
    
      const total = await Comment.countDocuments({ feedSeq: feedSeq });
      const comments = await Comment.find({ feedSeq: feedSeq }).sort({ createdAt: -1 }).skip(skip);
    
      if (!comments) {
        res.status(204).json(comments);
        return;
      }
    
      const currentPageDocumentCount = comments.length;
      const isLastPage = page >= Math.ceil(total / limit);
    
      res.status(200).json({
        total,
        pages: Math.ceil(total / limit),
        currentPage: page,
        isLastPage,
        currentPageDocumentCount,
        comments,
      });
    });
    반응형
    댓글
    공지사항
    최근에 올라온 글
    최근에 달린 댓글
    Total
    Today
    Yesterday
    링크
    «   2024/06   »
    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
    글 보관함