import { InjectRepository } from "@nestjs/typeorm" ; import { Injectable , NotFoundException } from "@nestjs/common" ; import { Repository } from "typeorm" ; import { RpcException } from "@nestjs/microservices" ; import { ProductEntity } from "./product.entity" ; @ Injectable ( ) export class ProductService { constructor ( @ InjectRepository ( ProductEntity ) private readonly products ) { } get ( data = undefined ) { return this . products . find ( data ) ; } fetchProductsByIds ( ids ) { return this . products . createQueryBuilder ( "products" ) . where ( `products.id IN (:...ids)` , { ids } ) . getMany ( ) ; } store ( data ) { return this . products . save ( data ) ; } async update ( id , data , user_id ) { const product = await this . products . findOneOrFail ( { id } ) ; if ( product . user_id === user_id ) { await this . products . update ( { id } , data ) ; return this . products . findOneOrFail ( { id } ) ; } throw new RpcException ( new NotFoundException ( "You cannot update what you don't own..." ) ) ; } async show ( id ) { return this . products . findOneOrFail ( { id } ) ; } async destroy ( id , user_id ) { const product = await this . products . findOneOrFail ( { id } ) ; if ( product . user_id === user_id ) { await this . products . delete ( { id } ) ; return product ; } throw new RpcException ( new NotFoundException ( "You cannot update what you don't own..." ) ) ; } async decrementProductsStock ( products ) { products . forEach ( product => { this . products . decrement ( { id : product . id } , "quantity" , product . quantity ) ; } ) ; } async incrementProductsStock ( products ) { products . forEach ( product => { this . products . increment ( { id : product . id } , "quantity" , product . quantity ) ; } ) ; } }