Add functionality to delete a product in product module

master
nicekid1 2 months ago
parent 30eb685e9e
commit c7d27edc10
  1. 22
      src/products/products.controller.ts
  2. 25
      src/products/products.service.ts

@ -10,26 +10,26 @@ export class ProductsController {
const { name, description, price } = body;
const product = await this.productsService.create(name, description, price);
return {
message: 'Product created successfully!',
product
message: "Product created successfully!",
product,
};
}
@Get()
async findAll(@Query() query: { search?: string; priceMin?: number; priceMax?: number }){
async findAll(@Query() query: { search?: string; priceMin?: number; priceMax?: number }) {
const { search, priceMin, priceMax } = query;
return this.productsService.findAll(search, priceMin, priceMax);
}
@Get(':id')
async findOne(@Param('id') id: string): Promise<Product> {
@Get(":id")
async findOne(@Param("id") id: string): Promise<Product> {
return this.productsService.findOne(id);
}
@Put(':id')
async update(
@Param('id') id: string,
@Body() body: { name?: string; description?: string; price?: number },
): Promise<Product> {
@Put(":id")
async update(@Param("id") id: string, @Body() body: { name?: string; description?: string; price?: number }): Promise<Product> {
const { name, description, price } = body;
return this.productsService.update(id, name, description, price);
}
@Delete(':id')
async remove(@Param('id') id: string): Promise<{ message: string }> {
return this.productsService.remove(id);
}
}

@ -91,4 +91,29 @@ export class ProductsService {
throw new HttpException("An error occurred while updating the product.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
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
);
}
await product.destroy();
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
);
}
}
}

Loading…
Cancel
Save