Implement product listing with search functionality by name, min price, and max price in product module

master
nicekid1 2 months ago
parent 780fb8bc1f
commit cfd85e729b
  1. 7
      src/products/products.controller.ts
  2. 34
      src/products/products.service.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 { ProductsService } from "./products.service";
import { Product } from "./entities/product.entity"; import { Product } from "./entities/product.entity";
@ -14,5 +14,10 @@ export class ProductsController {
product product
}; };
} }
@Get()
async findAll(@Query() query: { search?: string; priceMin?: number; priceMax?: number }){
const { search, priceMin, priceMax } = query;
return this.productsService.findAll(search, priceMin, priceMax);
}
} }

@ -1,6 +1,8 @@
import { Injectable } from "@nestjs/common"; import { Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/sequelize"; import { InjectModel } from "@nestjs/sequelize";
import { Product } from "./entities/product.entity"; import { Product } from "./entities/product.entity";
import { Op } from "sequelize";
import { HttpException, HttpStatus } from "@nestjs/common";
@Injectable() @Injectable()
export class ProductsService { export class ProductsService {
constructor(@InjectModel(Product) private readonly productModel: typeof Product) {} constructor(@InjectModel(Product) private readonly productModel: typeof Product) {}
@ -16,4 +18,36 @@ export class ProductsService {
throw new Error("Error creating product"); throw new Error("Error creating product");
} }
} }
async findAll(search?: string, priceMin?: number, priceMax?: number): Promise<Product[]> {
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);
}
}
} }

Loading…
Cancel
Save