What I Learned/SpartaCodingClub
[내일배움캠프] 2023-02-02 TIL
Interrobang
2023. 2. 2. 20:39
팀프로젝트 - 페이지네이션 구현
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 모듈을 이용하여 구현해보고자 하였으나 쉽지 않았다.