Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

5/31 배포 작업 #55

Merged
merged 1 commit into from
May 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,14 @@ interface MacbookRepository: JpaRepository<Macbook, Long>, MacbookRepositoryCust
"""
)
fun findAllFetchByProductCategory(@Param("category") crawlTargetCategory: ProductCategory): List<Macbook>

@Query(
"""
select m
from Macbook m
join fetch m.prices
where m.id = :id
"""
)
fun findAllPricesByMacbookId(@Param("id") id: Long)
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,19 @@ package backend.itracker.crawl.macbook.domain.repository
import backend.itracker.crawl.common.ProductCategory
import backend.itracker.crawl.macbook.domain.Macbook
import backend.itracker.crawl.macbook.service.dto.MacbookFilterCondition
import org.springframework.data.domain.PageImpl
import org.springframework.data.domain.Pageable

interface MacbookRepositoryCustom {

fun findAllByFilterCondition(
productCategory: ProductCategory,
filterCondition: MacbookFilterCondition
): List<Macbook>

fun findAllProductsByFilter(
category: ProductCategory,
filterCondition: MacbookFilterCondition,
pageable: Pageable
): PageImpl<Macbook>
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import backend.itracker.crawl.macbook.domain.QMacbook.macbook
import backend.itracker.crawl.macbook.service.dto.MacbookFilterCondition
import com.querydsl.core.types.Predicate
import com.querydsl.jpa.impl.JPAQueryFactory
import org.springframework.data.domain.PageImpl
import org.springframework.data.domain.Pageable

class MacbookRepositoryImpl(
private val jpaQueryFactory: JPAQueryFactory
Expand All @@ -27,6 +29,38 @@ class MacbookRepositoryImpl(
).fetch()
}

override fun findAllProductsByFilter(
category: ProductCategory,
filterCondition: MacbookFilterCondition,
pageable: Pageable
): PageImpl<Macbook> {
val contents = jpaQueryFactory.selectFrom(macbook)
.where(
equalSize(filterCondition.size),
equalColor(filterCondition.color),
equalChip(filterCondition.processor),
equalStorage(filterCondition.storage),
equalMemory(filterCondition.memory),
equalCategory(category)
).offset(pageable.offset)
.limit(pageable.pageSize.toLong())
.fetch()

val total = jpaQueryFactory.selectFrom(macbook)
.where(
equalSize(filterCondition.size),
equalColor(filterCondition.color),
equalChip(filterCondition.processor),
equalStorage(filterCondition.storage),
equalMemory(filterCondition.memory),
equalCategory(category)
).fetch()
.count()
.toLong()

return PageImpl(contents, pageable, total)
}

private fun equalSize(
size: Int?
): Predicate? {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import backend.itracker.crawl.common.ProductCategory
import backend.itracker.crawl.macbook.domain.Macbook
import backend.itracker.crawl.macbook.domain.repository.MacbookRepository
import backend.itracker.crawl.macbook.service.dto.MacbookFilterCondition
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

Expand Down Expand Up @@ -38,4 +40,17 @@ class MacbookService(
): List<Macbook> {
return macbookRepository.findAllByFilterCondition(productCategory, filterCondition)
}

@Transactional(readOnly = true)
fun findAllProductsByFilter(
category: ProductCategory,
macbookFilterCondition: MacbookFilterCondition,
pageable: Pageable
): Page<Macbook> {
val pageMacbooks =
macbookRepository.findAllProductsByFilter(category, macbookFilterCondition, pageable)
pageMacbooks.forEach { macbookRepository.findAllPricesByMacbookId(it.id) }

return pageMacbooks
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package backend.itracker.logging

import org.springframework.beans.BeanInstantiationException
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
Expand All @@ -8,6 +9,21 @@ import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExcep
@RestControllerAdvice
class GlobalRestControllerAdvice : ResponseEntityExceptionHandler() {

@ExceptionHandler(BeanInstantiationException::class)
fun handleBeanInstantiationException(e: BeanInstantiationException): ResponseEntity<String> {
return when (val ex = e.cause) {
is IllegalArgumentException -> {
logger.info("사용자 입력 예외입니다. message : ", ex)
ResponseEntity.badRequest().body("message = ${ex.message}")
}

else -> {
logger.error("예상치 못한 예외입니다. message : ", ex)
ResponseEntity.internalServerError().body("message = ${ex?.message}")
}
}
}

@ExceptionHandler(IllegalArgumentException::class)
fun handleIllealArgumentException(e: IllegalArgumentException): ResponseEntity<String> {
logger.info("사용자 입력 예외입니다. message : ", e)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package backend.itracker.tracker.controller

import backend.itracker.crawl.common.ProductCategory
import backend.itracker.tracker.controller.request.PageParams
import backend.itracker.tracker.controller.response.CategoryResponses
import backend.itracker.tracker.controller.response.Pages
import backend.itracker.tracker.controller.response.SinglePage
Expand All @@ -9,8 +10,10 @@ import backend.itracker.tracker.service.response.filter.CommonFilterModel
import backend.itracker.tracker.service.response.product.CommonProductModel
import backend.itracker.tracker.service.vo.Limit
import backend.itracker.tracker.service.vo.ProductFilter
import org.springframework.data.domain.PageRequest
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
Expand Down Expand Up @@ -44,4 +47,16 @@ class ProductController(
val filter = productService.findFilter(category, ProductFilter(filterConditon))
return ResponseEntity.ok(SinglePage(filter))
}

@GetMapping("/api/v1/products/{category}/search")
fun findFilterdMacbookAir(
@PathVariable category: ProductCategory,
@RequestParam filterCondition: Map<String, String>,
@ModelAttribute pageParams: PageParams,
): ResponseEntity<Pages<CommonProductModel>> {
val pageProducts =
productService.findFilteredProducts(category, ProductFilter(filterCondition), PageRequest.of(pageParams.offset, pageParams.limit))

return ResponseEntity.ok(Pages.withPagination(pageProducts))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package backend.itracker.tracker.controller.request

class PageParams(
private var page: Int = 1,
var limit: Int = 8
) {

init {
require(page >= 1) { throw IllegalArgumentException("page는 1이상 입력해주세요. page=$page") }
require(limit >= 1) { throw IllegalArgumentException("limit는 1이상 입력해주세요. limit=$limit") }
}

val offset: Int
get() = page - 1
}



Original file line number Diff line number Diff line change
@@ -1,9 +1,38 @@
package backend.itracker.tracker.controller.response

import org.springframework.data.domain.Page

private const val DEFAULT_PAGE_OFFSET = 1

data class Pages<T>(
val data: List<T>
)
val data: List<T>,
val pageInfo: PageInfo = PageInfo()
) {

companion object {
fun <T> withPagination(pagesData: Page<T>) = Pages(
data = pagesData.content,
pageInfo = PageInfo.from(pagesData)
)
}

}

data class SinglePage<T>(
val data: T
)

data class PageInfo(
val currentPage: Int = 0,
val lastPage: Int = 0,
val elementSize: Int = 0
) {

companion object {
fun <T> from(pagesData: Page<T>) = PageInfo(
currentPage = pagesData.number + DEFAULT_PAGE_OFFSET,
lastPage = pagesData.totalPages,
elementSize = pagesData.numberOfElements
)
}
}
13 changes: 13 additions & 0 deletions src/main/kotlin/backend/itracker/tracker/service/ProductService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import backend.itracker.tracker.service.response.filter.CommonFilterModel
import backend.itracker.tracker.service.response.product.CommonProductModel
import backend.itracker.tracker.service.vo.Limit
import backend.itracker.tracker.service.vo.ProductFilter
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.stereotype.Service

@Service
Expand All @@ -32,4 +34,15 @@ class ProductService(

return productHandler.findFilter(productCategory, productFilter)
}

fun findFilteredProducts(
category: ProductCategory,
productFilter: ProductFilter,
pageable: PageRequest
): Page<CommonProductModel> {
val productHandler = productHandlers.find { it.supports(category) }
?: throw IllegalArgumentException("핸들러가 지원하지 않는 카테고리 입니다. category: $category")

return productHandler.findFilteredProductsOrderByDiscountRate(category, productFilter, pageable)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import backend.itracker.tracker.service.response.filter.MacbookFilterResponse
import backend.itracker.tracker.service.response.product.CommonProductModel
import backend.itracker.tracker.service.response.product.MacbookResponse
import backend.itracker.tracker.service.vo.ProductFilter
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageImpl
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Component


Expand All @@ -26,30 +29,8 @@ class MacbookHandler(
limit: Int
): List<CommonProductModel> {
val macbooks = macbookService.findAllFetchByProductCategory(productCategory)
return macbooks.map {
val koreanCategory = when (it.category) {
ProductCategory.MACBOOK_AIR -> "맥북 에어"
ProductCategory.MACBOOK_PRO -> "맥북 프로"
else -> ""
}
MacbookResponse(
id = it.id,
title = "${it.company} ${it.releaseYear} $koreanCategory ${it.size}",
category = it.category.name.lowercase(),
size = it.size,
discountPercentage = it.findDiscountPercentage(),
chip = it.chip,
cpu = "${it.cpu} CPU",
gpu = "${it.gpu} GPU",
storage = "${it.storage} SSD 저장 장치",
memory = "${it.memory} 통합 메모리",
color = it.color,
currentPrice = it.findCurrentPrice(),
label = "역대최저가",
imageUrl = it.thumbnail,
isOutOfStock = it.isOutOfStock()
)
}.sortedBy { it.discountPercentage }
return macbooks.map { MacbookResponse.of(it) }
.sortedBy { it.discountPercentage }
.take(limit)
}

Expand All @@ -61,4 +42,21 @@ class MacbookHandler(

return MacbookFilterResponse.from(macbooks)
}

override fun findFilteredProductsOrderByDiscountRate(
category: ProductCategory,
filter: ProductFilter,
pageable: Pageable,
): Page<CommonProductModel> {
val pageMacbooks = macbookService.findAllProductsByFilter(
category,
MacbookFilterCondition(filter.value),
pageable
)

val contents = pageMacbooks.content.map { MacbookResponse.of(it) }
.sortedBy { it.discountPercentage }

return PageImpl(contents, pageMacbooks.pageable, pageMacbooks.totalElements)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import backend.itracker.crawl.common.ProductCategory
import backend.itracker.tracker.service.response.filter.CommonFilterModel
import backend.itracker.tracker.service.response.product.CommonProductModel
import backend.itracker.tracker.service.vo.ProductFilter
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable


interface ProductHandler {
Expand All @@ -13,4 +15,10 @@ interface ProductHandler {
fun findTopDiscountPercentageProducts(productCategory: ProductCategory, limit: Int): List<CommonProductModel>

fun findFilter(productCategory: ProductCategory, filterCondition: ProductFilter): CommonFilterModel

fun findFilteredProductsOrderByDiscountRate(
category: ProductCategory,
filter: ProductFilter,
pageable: Pageable,
): Page<CommonProductModel>
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package backend.itracker.tracker.service.response.product

import backend.itracker.crawl.common.ProductCategory
import backend.itracker.crawl.macbook.domain.Macbook
import java.math.BigDecimal

data class MacbookResponse(
Expand All @@ -18,5 +20,34 @@ data class MacbookResponse(
val label: String,
val imageUrl: String,
val isOutOfStock: Boolean
) : CommonProductModel
) : CommonProductModel {

companion object {
fun of(macbook: Macbook): MacbookResponse {
val koreanCategory = when (macbook.category) {
ProductCategory.MACBOOK_AIR -> "맥북 에어"
ProductCategory.MACBOOK_PRO -> "맥북 프로"
else -> ""
}

return MacbookResponse(
id = macbook.id,
title = "${macbook.company} ${macbook.releaseYear} $koreanCategory ${macbook.size}",
category = macbook.category.name.lowercase(),
size = macbook.size,
discountPercentage = macbook.findDiscountPercentage(),
chip = macbook.chip,
cpu = "${macbook.cpu} CPU",
gpu = "${macbook.gpu} GPU",
storage = "${macbook.storage} SSD 저장 장치",
memory = "${macbook.memory} 통합 메모리",
color = macbook.color,
currentPrice = macbook.findCurrentPrice(),
label = "역대최저가",
imageUrl = macbook.thumbnail,
isOutOfStock = macbook.isOutOfStock()
)
}
}
}

2 changes: 1 addition & 1 deletion src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ spring:
name: itracker
jpa:
hibernate:
ddl-auto: create
ddl-auto: validate
properties:
hibernate:
default_batch_fetch_size: 100
Expand Down
Loading