Compare commits

...

2 Commits

  1. 14
      src/products/products.controller.ts
  2. 41
      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";
@ -19,5 +19,17 @@ export class ProductsController {
const { search, priceMin, priceMax } = query;
return this.productsService.findAll(search, priceMin, priceMax);
}
@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> {
const { name, description, price } = body;
return this.productsService.update(id, name, description, price);
}
}

@ -50,4 +50,45 @@ export class ProductsService {
throw new HttpException("An error occurred while retrieving products.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
async findOne(id: string): Promise<Product> {
try {
const product = await this.productModel.findByPk(id);
if (!product) {
throw new HttpException("Product not found with the given id.", HttpStatus.NOT_FOUND);
}
return product;
} catch (error) {
if (error instanceof HttpException) {
throw error;
}
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