From 81d2629d0539c0a5999cc945a94fb71e57c3237d Mon Sep 17 00:00:00 2001 From: nicekid1 <86746988+nicekid1@users.noreply.github.com> Date: Tue, 31 Dec 2024 15:03:13 +0330 Subject: [PATCH] Implement functionality to find a user's cart in cart module --- src/cart/cart.controller.ts | 4 ++++ src/cart/cart.service.ts | 25 ++++++++++++++++++++++--- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/cart/cart.controller.ts b/src/cart/cart.controller.ts index 4e21939..3c4395f 100644 --- a/src/cart/cart.controller.ts +++ b/src/cart/cart.controller.ts @@ -11,4 +11,8 @@ export class CartController { const result = await this.cartService.addToCart(userId, productId, quantity); return result; } + @Get(':userId') + async getUserCart(@Param('userId') userId: number) { + return this.cartService.getUserCart(userId); + } } diff --git a/src/cart/cart.service.ts b/src/cart/cart.service.ts index 6f8a12b..2c3168d 100644 --- a/src/cart/cart.service.ts +++ b/src/cart/cart.service.ts @@ -11,7 +11,7 @@ export class CartService { constructor( @InjectModel(Cart) private readonly cartModel: typeof Cart, @InjectModel(User) private readonly userModel: typeof User, - @InjectModel(Product) private readonly productModel: typeof Product, + @InjectModel(Product) private readonly productModel: typeof Product, ) {} async addToCart(userId: number, productId: number, quantity: number): Promise { @@ -24,8 +24,8 @@ export class CartService { if (!user) { throw new HttpException("User not found!", HttpStatus.NOT_FOUND); } - - const product = await this.productModel.findByPk(productId); + + const product = await this.productModel.findByPk(productId); if (!product) { throw new HttpException("Product not found!", HttpStatus.NOT_FOUND); } @@ -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); } } + async getUserCart(userId: number): Promise { + 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); + } + } }