Skip to content

Commit c82131e

Browse files
committed
pagination added to carts
1 parent e79731e commit c82131e

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

server/Controllers/shopingCartController.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ function createCart(req, res, next) {
2020

2121
function getAll(req, res, next) {
2222
cartService
23-
.getAll()
23+
.getAll(req.query.page, req.query.size)
2424
.then((cart) => res.json(cart))
2525
.catch((error) => next(error));
2626
}

server/View/shopingCartView.js

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import ShoppingCart from '../Models/shopinCartModel.js';
2-
2+
import { NotFoundError } from '../helpers/errorHandler.js';
3+
import userService from '../View/usersViews.js';
34
const cartService = {
45
createCart,
56
editCart,
@@ -8,20 +9,45 @@ const cartService = {
89
getAll,
910
};
1011

12+
async function findCartById(id) {
13+
const cart = await ShoppingCart.findById(id);
14+
if (cart) {
15+
return cart;
16+
} else {
17+
return new NotFoundError(`Cart Not Found`);
18+
}
19+
}
20+
1121
async function createCart(products, userId) {
1222
const newCart = new ShoppingCart({ products, userId });
1323
return await newCart.save();
1424
}
1525

16-
async function getAll() {
17-
return await ShoppingCart.find();
26+
async function getAll(page, size) {
27+
// Pagination for products
28+
const actualPage = parseInt(page) || 1;
29+
const pageSize = parseInt(size) || 8;
30+
const skipCount = (actualPage - 1) * pageSize;
31+
32+
const totalCount = await ShoppingCart.countDocuments();
33+
const totalPages = Math.ceil(totalCount / pageSize);
34+
35+
const carts = await ShoppingCart.aggregate([
36+
{ $sample: { size: totalCount } },
37+
{ $skip: skipCount },
38+
{ $limit: pageSize },
39+
]);
40+
41+
return { carts, totalPages };
1842
}
1943

2044
async function getUserCart(userId) {
45+
await userService.getUser(userId);
2146
return await ShoppingCart.findOne({ userId });
2247
}
2348

2449
async function editCart(body, cartId) {
50+
await findCartById(cartId);
2551
return await ShoppingCart.findByIdAndUpdate(
2652
cartId,
2753
{
@@ -32,6 +58,7 @@ async function editCart(body, cartId) {
3258
}
3359

3460
async function deleteCart(cartId) {
61+
await findCartById(cartId);
3562
return await ShoppingCart.findByIdAndDelete(cartId);
3663
}
3764

0 commit comments

Comments
 (0)