diff --git a/src/products/products.controller.ts b/src/products/products.controller.ts index 0965c47..a050409 100644 --- a/src/products/products.controller.ts +++ b/src/products/products.controller.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 { + @Get(":id") + async findOne(@Param("id") id: string): Promise { return this.productsService.findOne(id); } - @Put(':id') - async update( - @Param('id') id: string, - @Body() body: { name?: string; description?: string; price?: number }, - ): Promise { + @Put(":id") + async update(@Param("id") id: string, @Body() body: { name?: string; description?: string; price?: number }): Promise { 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); + } } - diff --git a/src/products/products.service.ts b/src/products/products.service.ts index 47a5638..aed1e99 100644 --- a/src/products/products.service.ts +++ b/src/products/products.service.ts @@ -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 + ); + } + } }