프로젝트
Instagram, Facebook 같은 앱에서도 사용하는 일반적인 패턴인 페이지네이션이란?
달모드
2024. 12. 10. 21:01
// 2-1. 챌린지 이미지 조회 API
const getChallengeImages = async (req, res) => {
const { challengeId } = req.params;
const { page = 1, limit = 20 } = req.query; // 페이지네이션 적용
try {
const images = await ChallengeImage.findAndCountAll({
where: { challenge_id: challengeId },
include: [{
model: User,
attributes: ["nickname", "profile_picture"]
}],
order: [["createdAt", "DESC"]],
limit: parseInt(limit),
offset: (page - 1) * limit
});
res.json({
images: images.rows,
total: images.count,
currentPage: parseInt(page),
totalPages: Math.ceil(images.count / limit)
});
} catch (error) {
console.error("Error fetching challenge images:", error);
res.status(500).json({ message: "서버 오류가 발생했습니다." });
}
};
페이지네이션은 데이터를 일정 단위로 나눠서 필요할 때마다 로드하는 방식이다.
스크롤할 때마다 추가 데이터를 로드하는 것을 "무한 스크롤(Infinite Scroll)"이라고 하는데, SwiftUI에서도 구현해놓았다.
이렇게 구현하면:
- 처음에 20개의 이미지만 로드
- 스크롤이 끝에 가까워지면 자동으로 다음 20개를 로드
- 더 이상 데이터가 없을 때까지 반복
을 하게 되고, 이렇게 하게 되면
- 초기 로딩 시간 감소
- 메모리 사용량 최적화
- 네트워크 트래픽 최적화
라는 이점이 있다.