fix error handling of product endpoints

master
aliMohtarami 1 month ago
parent cc98768a90
commit 725412c59c
  1. 19
      src/products/products.controller.ts
  2. 10
      src/products/products.service.ts

@ -9,6 +9,8 @@ import { RoleGuard } from "src/guard/role.guard";
export class ProductsController {
constructor(private readonly productsService: ProductsService) {}
////////////////////////////////////////products////////////////////////////////////////
//create a new product (admin)
@UseGuards(RoleGuard)
@Post()
async create(@Body() createProductDto: CreateProductDto) {
@ -18,28 +20,35 @@ export class ProductsController {
product,
};
}
//list of all product
@Get()
async findAll(@Query() query: { search?: string; priceMin?: number; priceMax?: number }) {
const { search, priceMin, priceMax } = query;
return this.productsService.findAll(search, priceMin, priceMax);
}
//get a product detail
@Get(":id")
async findOne(@Param("id") id: string): Promise<Product> {
async findOne(@Param("id") id: string){
return this.productsService.findOne(id);
}
//edit a product info (admin)
@UseGuards(RoleGuard)
@Put(":id")
async update(
@Param("id") id: string,
@Body() updateProductDto: UpdateProductDto
): Promise<Product> {
return this.productsService.update(id, updateProductDto);
){
const product = await this.productsService.update(id, updateProductDto);
return {
message : 'product updated successful',
product
}
}
//delete a product (admin)
@UseGuards(RoleGuard)
@Delete(':id')
async remove(@Param('id') id: string): Promise<{ message: string }> {
return this.productsService.remove(id);
}
}

@ -26,6 +26,9 @@ export class ProductsService {
const newProduct = await this.productModel.create(createProductDto);
return newProduct;
} catch (error) {
if(error instanceof HttpException){
throw error
}
throw new HttpException("An error occurred while creating or updating the product.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@ -80,6 +83,7 @@ export class ProductsService {
where,
limit,
offset,
attributes: { exclude: ["description", "quantity", "createdAt", "updatedAt", "tags"] },
});
const totalPages = Math.ceil(total / limit);
@ -111,7 +115,7 @@ export class ProductsService {
try {
const { name, description, price, imageUrl, tags, quantity, brand, color, category } = updateProductDto;
let updated = false; // متغیر برای بررسی تغییرات
let updated = false;
if (name && name !== product.name) {
product.name = name;
@ -156,6 +160,9 @@ export class ProductsService {
return product;
} catch (error) {
if(error instanceof HttpException){
throw error
}
throw new HttpException("An error occurred while updating the product.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@ -177,7 +184,6 @@ export class ProductsService {
if (error instanceof HttpException) {
throw error;
}
throw new HttpException("An unexpected error occurred while deleting the product.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}

Loading…
Cancel
Save