diff --git a/src/cart/cart.controller.ts b/src/cart/cart.controller.ts index b584f12..4e21939 100644 --- a/src/cart/cart.controller.ts +++ b/src/cart/cart.controller.ts @@ -1,8 +1,14 @@ -import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common'; -import { CartService } from './cart.service'; +import { Controller, Get, Post, Body, Patch, Param, Delete } from "@nestjs/common"; +import { CartService } from "./cart.service"; +import { Cart } from "./entities/cart.entity"; -@Controller('cart') +@Controller("cart") export class CartController { constructor(private readonly cartService: CartService) {} - + @Post() + async addToCart(@Body() body: { userId: number; productId: number; quantity: number }): Promise<{ message: string; cartItem: Cart }> { + const { userId, productId, quantity } = body; + const result = await this.cartService.addToCart(userId, productId, quantity); + return result; + } } diff --git a/src/cart/cart.module.ts b/src/cart/cart.module.ts index d9e45d5..9560b97 100644 --- a/src/cart/cart.module.ts +++ b/src/cart/cart.module.ts @@ -3,9 +3,11 @@ import { CartService } from "./cart.service"; import { CartController } from "./cart.controller"; import { Cart } from "./entities/cart.entity"; import { SequelizeModule } from "@nestjs/sequelize"; +import { User } from "src/users/entities/user.entity"; +import { Product } from "src/products/entities/product.entity"; @Module({ - imports: [SequelizeModule.forFeature([Cart])], + imports: [SequelizeModule.forFeature([Cart,User,Product])], controllers: [CartController], providers: [CartService], }) diff --git a/src/cart/cart.response.ts b/src/cart/cart.response.ts new file mode 100644 index 0000000..829790c --- /dev/null +++ b/src/cart/cart.response.ts @@ -0,0 +1,6 @@ +import { Cart } from "./entities/cart.entity"; + +export interface CartResponse { + message: string; + cartItem: Cart; +} diff --git a/src/cart/cart.service.ts b/src/cart/cart.service.ts index 8ca559e..6f8a12b 100644 --- a/src/cart/cart.service.ts +++ b/src/cart/cart.service.ts @@ -1,7 +1,60 @@ -import { Injectable } from '@nestjs/common'; - +import { Injectable } from "@nestjs/common"; +import { InjectModel } from "@nestjs/sequelize"; +import { Cart } from "./entities/cart.entity"; +import { HttpException, HttpStatus } from "@nestjs/common"; +import { CartResponse } from "./cart.response"; +import { User } from "src/users/entities/user.entity"; +import { Product } from "src/products/entities/product.entity"; @Injectable() 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, + ) {} + + async addToCart(userId: number, productId: number, quantity: number): Promise { + try { + if (!userId || !productId || !quantity) { + throw new HttpException("Missing required parameters: userId, productId, and quantity are required.", HttpStatus.BAD_REQUEST); + } + + const user = await this.userModel.findByPk(userId); + if (!user) { + throw new HttpException("User not found!", HttpStatus.NOT_FOUND); + } + + const product = await this.productModel.findByPk(productId); + if (!product) { + throw new HttpException("Product not found!", HttpStatus.NOT_FOUND); + } + + const existingCartItem = await this.cartModel.findOne({ + where: { userId, productId }, + }); + + if (existingCartItem) { + existingCartItem.quantity += Number(quantity); + await existingCartItem.save(); + return { + message: "Product quantity updated in cart successfully!", + cartItem: existingCartItem, + }; + } + + const newCartItem = await this.cartModel.create({ userId, productId, quantity }); + + return { + message: "Product added to cart successfully!", + cartItem: newCartItem, + }; + } catch (error) { + // Enhanced error handling + if (error instanceof HttpException) { + throw error; + } + throw new HttpException(`An error occurred while adding the product to the cart: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR); + } + } } diff --git a/src/cart/entities/cart.entity.ts b/src/cart/entities/cart.entity.ts index 87b14cb..6369839 100644 --- a/src/cart/entities/cart.entity.ts +++ b/src/cart/entities/cart.entity.ts @@ -1,4 +1,4 @@ -import { Model, Table, Column, ForeignKey, BelongsTo } from "sequelize-typescript"; +import { Model, Table, Column, ForeignKey, BelongsTo, DataType } from "sequelize-typescript"; import { User } from "../../users/entities/user.entity"; import { Product } from "../../products/entities/product.entity"; @@ -18,6 +18,9 @@ export class Cart extends Model { @BelongsTo(() => Product) product: Product; - @Column + @Column({ + type: DataType.INTEGER, + allowNull: false, + }) quantity: number; -} \ No newline at end of file +} diff --git a/src/users/users.module.ts b/src/users/users.module.ts index 32eeb2d..9d25f0d 100644 --- a/src/users/users.module.ts +++ b/src/users/users.module.ts @@ -9,6 +9,7 @@ import { JwtModule } from '@nestjs/jwt'; import { JwtAuthGuard } from 'src/guard/auth.guard'; + @Module({ imports: [SequelizeModule.forFeature([User]), PassportModule.register({ defaultStrategy: 'jwt' }),