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