Implement product update functionality in product module

master
nicekid1 2 months ago
parent e058e82e6d
commit 30eb685e9e
  1. 10
      src/products/products.controller.ts
  2. 23
      src/products/products.service.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<Product> {
return this.productsService.findOne(id);
}
@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);
}
}

@ -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<Product> {
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);
}
}
}

Loading…
Cancel
Save