import { EntityRepository , Repository , Like , FindOperator , Not } from 'typeorm' ; import ProductEntity from '@/entity/product' ; import CategoryEntity from '@/entity/category' ; @ EntityRepository ( ProductEntity ) class ProductRepository extends Repository < ProductEntity > { async findByIdx ( idx ) { const product = await this . findOne ( { where : { idx } } ) ; return product ; } async findProductsByFilter ( querys ) { const subWhere = { } ; const subOrder = { } ; const subLimit = querys . limit ? Number ( querys . limit ) : 20 ; const subOffset = querys . page ? ( Number ( querys . page ) - 1 ) * subLimit : 0 ; if ( querys . search ) { subWhere . title = Like ( `%${ querys . search }%` ) ; } if ( querys . category ) { subWhere . category = { idx : querys . category } ; } if ( querys . order ) { if ( querys . order === 'price-low' ) { subOrder . discountedPrice = 'ASC' ; } if ( querys . order === 'price-high' ) { subOrder . discountedPrice = 'DESC' ; } if ( querys . order === 'recent' ) { subOrder . createdAt = 'DESC' ; } } const products = await this . find ( { select : [ 'idx' , 'thumbnail' , 'title' , 'discountedPrice' , 'originPrice' , 'createdAt' , 'updatedAt' , ] , where : subWhere , order : subOrder , skip : subOffset , take : subLimit , } ) ; return products ; } async saveItem ( currentCategory , title , thumbnail , originPrice , discountedPrice , rank , mandatoryInfo , shipInfo ) { const product = new ProductEntity ( ) ; product . category = currentCategory ; product . title = title ; product . thumbnail = thumbnail ; product . originPrice = originPrice ; product . discountedPrice = discountedPrice ; product . rank = rank ; product . mandatoryInfo = mandatoryInfo ; product . shipInfo = shipInfo ; const newProduct = await this . save ( product ) ; return newProduct ; } async findCategoryByIdx ( idx ) { const product = await this . findOne ( { where : { idx } , relations : [ 'category' ] , } ) ; return product ; } async findTopRankByCategory ( categoryIdx , productIdx ) { const recommend = await this . find ( { select : [ 'idx' , 'thumbnail' ] , where : { category : categoryIdx , idx : Not ( productIdx ) , } , order : { rank : 'ASC' , } , take : 4 , } ) ; return recommend ; } } export default ProductRepository ;