Create cart module and model

master
nicekid1 2 months ago
parent c7d27edc10
commit 199c2b35a2
  1. 2
      src/app.module.ts
  2. 8
      src/cart/cart.controller.ts
  3. 12
      src/cart/cart.module.ts
  4. 7
      src/cart/cart.service.ts
  5. 23
      src/cart/entities/cart.entity.ts
  6. 20
      src/products/products.service.ts

@ -6,6 +6,7 @@ import { SequelizeModule } from "@nestjs/sequelize";
import { databaseConfig } from "./config/database.config";
import { UsersModule } from './users/users.module';
import { ProductsModule } from './products/products.module';
import { CartModule } from './cart/cart.module';
@Module({
imports: [
@ -15,6 +16,7 @@ import { ProductsModule } from './products/products.module';
SequelizeModule.forRoot(databaseConfig),
UsersModule,
ProductsModule,
CartModule,
],
controllers: [AppController],
providers: [AppService],

@ -0,0 +1,8 @@
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { CartService } from './cart.service';
@Controller('cart')
export class CartController {
constructor(private readonly cartService: CartService) {}
}

@ -0,0 +1,12 @@
import { Module } from "@nestjs/common";
import { CartService } from "./cart.service";
import { CartController } from "./cart.controller";
import { Cart } from "./entities/cart.entity";
import { SequelizeModule } from "@nestjs/sequelize";
@Module({
imports: [SequelizeModule.forFeature([Cart])],
controllers: [CartController],
providers: [CartService],
})
export class CartModule {}

@ -0,0 +1,7 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class CartService {
}

@ -0,0 +1,23 @@
import { Model, Table, Column, ForeignKey, BelongsTo } from "sequelize-typescript";
import { User } from "../../users/entities/user.entity";
import { Product } from "../../products/entities/product.entity";
@Table
export class Cart extends Model<Cart> {
@ForeignKey(() => User)
@Column
userId: number;
@BelongsTo(() => User)
user: User;
@ForeignKey(() => Product)
@Column
productId: number;
@BelongsTo(() => Product)
product: Product;
@Column
quantity: number;
}

@ -94,26 +94,20 @@ export class ProductsService {
async remove(id: string): Promise<{ message: string }> {
try {
const product = await this.productModel.findByPk(id);
if (!product) {
throw new HttpException(
'Product not found with the given id.',
HttpStatus.NOT_FOUND
);
throw new HttpException("Product not found with the given id.", HttpStatus.NOT_FOUND);
}
await product.destroy();
return { message: 'Product deleted successfully.' };
return { message: "Product deleted successfully." };
} catch (error) {
if (error instanceof HttpException) {
throw error;
}
throw new HttpException(
'An error occurred while deleting the product.',
HttpStatus.INTERNAL_SERVER_ERROR
);
throw new HttpException("An error occurred while deleting the product.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

Loading…
Cancel
Save