From 30eb685e9e86af7948a785afb798b9c9dc6a21b8 Mon Sep 17 00:00:00 2001 From: nicekid1 <86746988+nicekid1@users.noreply.github.com> Date: Tue, 31 Dec 2024 13:10:32 +0330 Subject: [PATCH] Implement product update functionality in product module --- src/products/products.controller.ts | 10 +++++++++- src/products/products.service.ts | 23 +++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/products/products.controller.ts b/src/products/products.controller.ts index 428b5c6..0965c47 100644 --- a/src/products/products.controller.ts +++ b/src/products/products.controller.ts @@ -1,4 +1,4 @@ -import { Controller, Get, Post, Body, Patch, Param, Delete, Res, Query } from "@nestjs/common"; +import { Controller, Get, Post, Body, Param, Delete, Query, Put } from "@nestjs/common"; import { ProductsService } from "./products.service"; import { Product } from "./entities/product.entity"; @@ -23,5 +23,13 @@ export class ProductsController { 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 { + const { name, description, price } = body; + return this.productsService.update(id, name, description, price); + } } diff --git a/src/products/products.service.ts b/src/products/products.service.ts index cf9eb55..47a5638 100644 --- a/src/products/products.service.ts +++ b/src/products/products.service.ts @@ -68,4 +68,27 @@ export class ProductsService { throw new HttpException("An error occurred while retrieving the product.", HttpStatus.INTERNAL_SERVER_ERROR); } } + async update(id: string, name?: string, description?: string, price?: number): Promise { + try { + const product = await this.productModel.findByPk(id); + + if (!product) { + throw new HttpException("Product not found.", HttpStatus.NOT_FOUND); + } + + if (name) product.name = name; + if (description) product.description = description; + if (price) product.price = price; + + await product.save(); + + return product; + } catch (error) { + if (error instanceof HttpException) { + throw error; + } + + throw new HttpException("An error occurred while updating the product.", HttpStatus.INTERNAL_SERVER_ERROR); + } + } }