Implement functionality to create a cart in cart module

master
nicekid1 2 months ago
parent 199c2b35a2
commit 729a5a040b
  1. 14
      src/cart/cart.controller.ts
  2. 4
      src/cart/cart.module.ts
  3. 6
      src/cart/cart.response.ts
  4. 59
      src/cart/cart.service.ts
  5. 9
      src/cart/entities/cart.entity.ts
  6. 1
      src/users/users.module.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;
}
}

@ -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],
})

@ -0,0 +1,6 @@
import { Cart } from "./entities/cart.entity";
export interface CartResponse {
message: string;
cartItem: Cart;
}

@ -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<CartResponse> {
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);
}
}
}

@ -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<Cart> {
@BelongsTo(() => Product)
product: Product;
@Column
@Column({
type: DataType.INTEGER,
allowNull: false,
})
quantity: number;
}
}

@ -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' }),

Loading…
Cancel
Save