From cfd85e729b6a9ae88007aaffaeacae25de7eb650 Mon Sep 17 00:00:00 2001 From: nicekid1 <86746988+nicekid1@users.noreply.github.com> Date: Tue, 31 Dec 2024 12:54:06 +0330 Subject: [PATCH] Implement product listing with search functionality by name, min price, and max price in product module --- src/products/products.controller.ts | 7 +++++- src/products/products.service.ts | 34 +++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/products/products.controller.ts b/src/products/products.controller.ts index a558183..bc51fa5 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 } from "@nestjs/common"; +import { Controller, Get, Post, Body, Patch, Param, Delete, Res, Query } from "@nestjs/common"; import { ProductsService } from "./products.service"; import { Product } from "./entities/product.entity"; @@ -14,5 +14,10 @@ export class ProductsController { product }; } + @Get() + async findAll(@Query() query: { search?: string; priceMin?: number; priceMax?: number }){ + const { search, priceMin, priceMax } = query; + return this.productsService.findAll(search, priceMin, priceMax); + } } diff --git a/src/products/products.service.ts b/src/products/products.service.ts index a50a6e7..22c446e 100644 --- a/src/products/products.service.ts +++ b/src/products/products.service.ts @@ -1,6 +1,8 @@ import { Injectable } from "@nestjs/common"; import { InjectModel } from "@nestjs/sequelize"; import { Product } from "./entities/product.entity"; +import { Op } from "sequelize"; +import { HttpException, HttpStatus } from "@nestjs/common"; @Injectable() export class ProductsService { constructor(@InjectModel(Product) private readonly productModel: typeof Product) {} @@ -16,4 +18,36 @@ export class ProductsService { throw new Error("Error creating product"); } } + + async findAll(search?: string, priceMin?: number, priceMax?: number): Promise { + const where: any = {}; + + try { + if (search) { + where.name = { + [Op.like]: `%${search}%`, + }; + } + + if (priceMin || priceMax) { + where.price = {}; + if (priceMin) where.price[Op.gte] = priceMin; + if (priceMax) where.price[Op.lte] = priceMax; + } + + const products = await this.productModel.findAll({ where }); + + if (!products || products.length === 0) { + throw new HttpException("No products found matching the given criteria.", HttpStatus.NOT_FOUND); + } + + return products; + } catch (error) { + if (error instanceof HttpException) { + throw error; + } + + throw new HttpException("An error occurred while retrieving products.", HttpStatus.INTERNAL_SERVER_ERROR); + } + } }