Implement functionality to find a user's cart in cart module

master
nicekid1 2 months ago
parent 729a5a040b
commit 81d2629d05
  1. 4
      src/cart/cart.controller.ts
  2. 19
      src/cart/cart.service.ts

@ -11,4 +11,8 @@ export class CartController {
const result = await this.cartService.addToCart(userId, productId, quantity); const result = await this.cartService.addToCart(userId, productId, quantity);
return result; return result;
} }
@Get(':userId')
async getUserCart(@Param('userId') userId: number) {
return this.cartService.getUserCart(userId);
}
} }

@ -57,4 +57,23 @@ export class CartService {
throw new HttpException(`An error occurred while adding the product to the cart: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR); throw new HttpException(`An error occurred while adding the product to the cart: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR);
} }
} }
async getUserCart(userId: number): Promise<Cart[]> {
try {
const cartItems = await this.cartModel.findAll({
where: { userId },
include: ["product"],
});
if (!cartItems || cartItems.length === 0) {
throw new HttpException("No cart items found for the specified user.", HttpStatus.NOT_FOUND);
}
return cartItems;
} catch (error) {
if (error instanceof HttpException) {
throw error;
}
throw new HttpException("An error occurred while retrieving the cart.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
} }

Loading…
Cancel
Save