Web Project/market (server)
Get Products By Category
hmmmmmmmmmmmm
2025. 3. 30. 17:02
src > routes > product.ts
const productRouter = Router();
productRouter.get("/by-category/:category", getProductsByCategory); // 특정 카테고리에 속한 상품 조회
export default productRouter;
src > controllers > product.ts
// 카테고리 상품 조회
export const getProductsByCategory: RequestHandler = async (req, res) => {
// 1. URL 파라미터에서 카테고리 추출 및 쿼리 파라미터에서 페이지 정보 추출
const { category } = req.params;
const { pageNo = "1", limit = "10" } = req.query as {
pageNo: string;
limit: string;
};
if (!categories.includes(category)) return sendErrorRes(res, "Invalid category!", 422);
// 2. 카테고리별 상품 검색 및 페이징 처리
const products = await ProductModel.find({ category })
.sort("-createdAt") // 최신순 정렬 (내림차순)
.skip((+ pageNo - 1) * + limit) // 페이지 건너뛰기 (페이지네이션) -> 현재 페이지 번호에 따라 이전 페이지의 모든 항목을 건너뛰고 현재 페이지에 해당하는 항목만 가져오기
.limit(+ limit); // 한 페이지당 상품 수 제한
// 3. 클라이언트에 응답할 데이터 구조화
const listings = products.map((p) => {
return {
id: p._id,
name: p.name,
thumbnail: p.thumbnail,
category: p.category,
price: p.price,
};
});
// 4. 성공 응답 반환
res.json({ products: listings });
}
- 요청 유형: GET
- URL: http://localhost:8000/product/by-category/{category}
- URL 파라미터:
- category: Electronics (조회할 상품 카테고리)
- 쿼리 파라미터:
- pageNo: (선택, 기본값=1) 페이지 번호
- limit: (선택, 기본값=10) 페이지당 상품 수
- 요청 예시:
- 기본 요청: http://localhost:8000/product/by-category/Electronics
- 페이지 지정: http://localhost:8000/product/by-category/Electronics?pageNo=2&limit=5
- 설명
- 지정된 카테고리에 속하는 상품 목록을 페이지네이션하여 반환
- 최신순으로 정렬
- 각 상품의 기본 정보만 포함
Electronics에 속한 상품 목록 조회 처리