|
| 1 | +import { Injectable, NotFoundException } from '@nestjs/common'; |
| 2 | +import { InjectRepository } from '@nestjs/typeorm'; |
| 3 | +import { Repository } from 'typeorm'; |
| 4 | +import { CreateProductDto } from './dto/create-product.dto'; |
| 5 | +import { UpdateProductDto } from './dto/update-product.dto'; |
| 6 | +import { Product } from './entities/product.entity'; |
| 7 | + |
| 8 | +@Injectable() |
| 9 | +export class ProductService { |
| 10 | + constructor( |
| 11 | + @InjectRepository(Product) |
| 12 | + private productRepository: Repository<Product>, |
| 13 | + ) {} |
| 14 | + |
| 15 | + async create(createProductDto: CreateProductDto): Promise<Product> { |
| 16 | + const product = this.productRepository.create(createProductDto); |
| 17 | + return await this.productRepository.save(product); |
| 18 | + } |
| 19 | + |
| 20 | + async findAll(page = 1, limit = 10): Promise<{ items: Product[]; total: number }> { |
| 21 | + const [items, total] = await this.productRepository.findAndCount({ |
| 22 | + order: { createdAt: 'DESC' }, |
| 23 | + skip: (page - 1) * limit, |
| 24 | + take: limit, |
| 25 | + }); |
| 26 | + |
| 27 | + return { items, total }; |
| 28 | + } |
| 29 | + |
| 30 | + async findAllActive(page = 1, limit = 10): Promise<{ items: Product[]; total: number }> { |
| 31 | + const [items, total] = await this.productRepository.findAndCount({ |
| 32 | + where: { status: 1 }, |
| 33 | + order: { createdAt: 'DESC' }, |
| 34 | + skip: (page - 1) * limit, |
| 35 | + take: limit, |
| 36 | + }); |
| 37 | + |
| 38 | + return { items, total }; |
| 39 | + } |
| 40 | + |
| 41 | + async findOne(id: number): Promise<Product> { |
| 42 | + const product = await this.productRepository.findOne({ where: { id } }); |
| 43 | + if (!product) { |
| 44 | + throw new NotFoundException(`Product with ID ${id} not found`); |
| 45 | + } |
| 46 | + return product; |
| 47 | + } |
| 48 | + |
| 49 | + async update(id: number, updateProductDto: UpdateProductDto): Promise<Product> { |
| 50 | + const product = await this.findOne(id); |
| 51 | + this.productRepository.merge(product, updateProductDto); |
| 52 | + return await this.productRepository.save(product); |
| 53 | + } |
| 54 | + |
| 55 | + async remove(id: number): Promise<void> { |
| 56 | + const result = await this.productRepository.delete(id); |
| 57 | + if (result.affected === 0) { |
| 58 | + throw new NotFoundException(`Product with ID ${id} not found`); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments