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. 25
      src/cart/cart.service.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);
}
}

@ -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<CartResponse> {
@ -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<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