11import ShoppingCart from '../Models/shopinCartModel.js' ;
2-
2+ import { NotFoundError } from '../helpers/errorHandler.js' ;
3+ import userService from '../View/usersViews.js' ;
34const 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+
1121async 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
2044async function getUserCart ( userId ) {
45+ await userService . getUser ( userId ) ;
2146 return await ShoppingCart . findOne ( { userId } ) ;
2247}
2348
2449async 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
3460async function deleteCart ( cartId ) {
61+ await findCartById ( cartId ) ;
3562 return await ShoppingCart . findByIdAndDelete ( cartId ) ;
3663}
3764
0 commit comments