feat: 지붕재 데이터 조회 기능 추가

This commit is contained in:
Daseul Kim 2025-04-28 16:51:01 +09:00
parent 0cdc3984b8
commit cc8ef6a7d3
7 changed files with 266 additions and 23 deletions

View File

@ -38,14 +38,31 @@ export interface Suitable {
}
export const suitableApi = {
getList: async (): Promise<Suitable[]> => {
const response = await axiosInstance.get<Suitable[]>('/api/suitable/list')
getList: async (category?: string, keyword?: string): Promise<Suitable[]> => {
let condition: any = {}
if (category) {
condition['category'] = category
}
if (keyword) {
condition['keyword'] = {
contains: keyword,
}
}
console.log('🚀 ~ getList: ~ condition:', condition)
const response = await axiosInstance.get<Suitable[]>('/api/suitable/list', { params: condition })
console.log('🚀 ~ getList: ~ response:', response)
return response.data
},
getCategory: async (): Promise<Suitable[]> => {
const response = await axiosInstance.get<Suitable[]>('/api/suitable/category')
console.log('🚀 ~ getCategory: ~ response:', response)
return response.data
},
getDetails: async (roofMaterial: string): Promise<Suitable[]> => {
const response = await axiosInstance.get<Suitable[]>(`/api/suitable/details?roof-material=${roofMaterial}`)
console.log('🚀 ~ getDetails: ~ response:', response)
return response.data
},

View File

@ -0,0 +1,16 @@
import { NextResponse } from 'next/server'
import { prisma } from '@/libs/prisma'
export async function GET() {
// @ts-ignore
const roofMaterialCategory = await prisma.MS_SUITABLE.findMany({
select: {
roof_material: true,
},
distinct: ['roof_material'],
orderBy: {
roof_material: 'asc',
},
})
return NextResponse.json(roofMaterialCategory)
}

View File

@ -1,8 +1,35 @@
import { NextResponse } from 'next/server'
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/libs/prisma'
export async function GET() {
// @ts-ignore
const suitables = await prisma.MS_SUITABLE.findMany()
return NextResponse.json(suitables)
export async function GET(request: NextRequest) {
try {
const searchParams = request.nextUrl.searchParams
const category = searchParams.get('category')
const keyword = searchParams.get('keyword')
let whereCondition: any = {}
if (category) {
whereCondition['roof_material'] = category
}
if (keyword) {
whereCondition['product_name'] = {
contains: keyword,
}
}
console.log('🚀 ~ /api/suitable/list: ~ prisma where condition:', whereCondition)
// @ts-ignore
const suitables = await prisma.MS_SUITABLE.findMany({
where: whereCondition,
orderBy: {
product_name: 'asc',
},
})
return NextResponse.json(suitables)
} catch (error) {
console.error('❌ 데이터 조회 중 오류가 발생했습니다:', error)
return NextResponse.json({ error: '데이터 조회 중 오류가 발생했습니다' }, { status: 500 })
}
}

View File

@ -1,16 +1,23 @@
'use client'
import { suitableApi } from '@/api/suitable'
import { useSuitableStore } from '@/store/useSuitableStore'
import { useQuery } from '@tanstack/react-query'
import { useRouter } from 'next/navigation'
import type { Suitable as SuitableType } from '@/api/suitable'
export default function Suitable() {
const router = useRouter()
const { data, error, isPending } = useQuery({
queryKey: ['suitable-list'],
queryFn: suitableApi.getList,
const { selectedItems, addSelectedItem } = useSuitableStore()
const { data: suitableList, isLoading } = useQuery<SuitableType[]>({
queryKey: ['suitables', 'search'],
enabled: false,
})
if (isLoading || !suitableList) {
return <div>Loading...</div>
}
return (
<>
<h1 className="text-4xl font-bold">Suitable</h1>
@ -22,9 +29,23 @@ export default function Suitable() {
>
HOME
</button>
{error && <div>Error: {error.message}</div>}
{isPending && <div>Loading...</div>}
{data && data.map((item) => <div key={item.id}>{item.product_name}</div>)}
<div>
<h2 className="text-lg font-semibold mb-2"> </h2>
{selectedItems.length > 0 ? selectedItems.map((item) => <div key={item.id}>{item.product_name}</div>) : <div> .</div>}
</div>
<br />
<div>
<h2 className="text-lg font-semibold mb-2"> </h2>
{suitableList ? (
suitableList.map((item: SuitableType) => (
<div key={item.id} className="p-2 border rounded cursor-pointer hover:bg-gray-100" onClick={() => addSelectedItem(item)}>
{item.product_name}
</div>
))
) : (
<div> .</div>
)}
</div>
</>
)
}

View File

@ -1,21 +1,85 @@
'use client'
import { useState } from 'react'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { useQuery } from '@tanstack/react-query'
import { useSuitable } from '@/hooks/useSuitable'
export default function SuitableSearch() {
const router = useRouter()
const [selectedValue, setSelectedValue] = useState('')
const [selectedCategory, setSelectedCategory] = useState<string>('')
const [searchValue, setSearchValue] = useState<string>('')
const { getCategories, getSuitables } = useSuitable()
const { data: categories } = useQuery({
queryKey: ['categories'],
queryFn: getCategories,
staleTime: 1000 * 60 * 60, // 60분
})
const { data: suitableList } = useQuery({
queryKey: ['suitables', 'list'],
queryFn: async () => await getSuitables(),
staleTime: 1000 * 60 * 10, // 10분
gcTime: 1000 * 60 * 10, // 10분
})
const { data: suitableSearch, refetch: refetchBySearch } = useQuery({
queryKey: ['suitables', 'search'],
queryFn: async () => {
// api를 호출하는 검색 방법
// return await updateSearchResults(selectedCategory || undefined, searchValue || undefined)
// useQuery 캐시 데이터를 사용하는 검색 방법
return (
suitableList?.filter((item) => {
const categoryMatch = !selectedCategory || item.roof_material === selectedCategory
const searchMatch = !searchValue || item.product_name.includes(searchValue)
return categoryMatch && searchMatch
}) ?? []
)
},
staleTime: 1000 * 60 * 10,
gcTime: 1000 * 60 * 10,
enabled: false,
})
// 초기 데이터 로딩된 후 검색 결과 없으면 검색 결과 로딩
useEffect(() => {
if (suitableList && (!suitableSearch || suitableSearch.length === 0)) {
refetchBySearch()
}
}, [suitableList, suitableSearch])
// 카테고리 선택 시 검색 결과 로딩
useEffect(() => {
refetchBySearch()
}, [selectedCategory])
const handleSearch = async () => {
if (!searchValue.trim()) {
alert('검색어를 입력하세요.')
return
}
refetchBySearch()
}
return (
<>
<select onChange={(e) => setSelectedValue(e.target.value)}>
<option value=""> </option>
<option value="瓦"></option>
<option value="スレート"></option>
<option value="アスファルトシングル"></option>
</select>
<button onClick={() => router.push(`/suitable/${selectedValue}`)}></button>
<div>
<select value={selectedCategory || ''} onChange={(e) => setSelectedCategory(e.target.value)}>
<option value=""> </option>
{categories?.map((category) => (
<option key={category.roof_material} value={category.roof_material}>
{category.roof_material}
</option>
))}
</select>
<button onClick={() => router.push(`/suitable/${selectedCategory}`)}> </button>
</div>
<div>
<input type="text" placeholder="검색어를 입력하세요" onChange={(e) => setSearchValue(e.target.value)} />
<button onClick={handleSearch}></button>
</div>
</>
)
}

30
src/hooks/useSuitable.ts Normal file
View File

@ -0,0 +1,30 @@
import { suitableApi } from '@/api/suitable'
export function useSuitable() {
const getCategories = async () => {
try {
return await suitableApi.getCategory()
} catch (error) {
console.error('카테고리 데이터 로드 실패:', error)
return []
}
}
const getSuitables = async () => {
try {
return await suitableApi.getList()
} catch (error) {
console.error('지붕재 데이터 로드 실패:', error)
}
}
const updateSearchResults = async (selectedCategory: string | undefined, searchValue: string | undefined) => {
try {
return await suitableApi.getList(selectedCategory, searchValue)
} catch (error) {
console.error('지붕재 데이터 검색 실패:', error)
}
}
return { getCategories, getSuitables, updateSearchResults }
}

View File

@ -0,0 +1,68 @@
import { create } from 'zustand'
import { Suitable, suitableApi } from '@/api/suitable'
interface SuitableState {
// // 검색 결과 리스트
// searchResults: Suitable[]
// // 초기 데이터 로드
// fetchInitializeData: () => Promise<void>
// // 검색 결과 설정
// setSearchResults: (results: Suitable[]) => void
// // 검색 결과 초기화
// resetSearchResults: () => void
// 선택된 아이템 리스트
selectedItems: Suitable[]
// 선택된 아이템 추가
addSelectedItem: (item: Suitable) => void
// 선택된 아이템 제거
removeSelectedItem: (itemId: number) => void
// 선택된 아이템 모두 제거
clearSelectedItems: () => void
}
export const useSuitableStore = create<SuitableState>((set) => ({
// // 초기 상태
// searchResults: [],
// // 초기 데이터 로드
// fetchInitializeData: async () => {
// const suitables = await fetchInitialSuitablee()
// set({ searchResults: suitables })
// },
// // 검색 결과 설정
// setSearchResults: (results) => set({ searchResults: results }),
// // 검색 결과 초기화
// resetSearchResults: () => set({ searchResults: [] }),
// 초기 상태
selectedItems: [],
// 선택된 아이템 추가 (중복 방지)
addSelectedItem: (item) =>
set((state) => ({
selectedItems: state.selectedItems.some((i) => i.id === item.id) ? state.selectedItems : [...state.selectedItems, item],
})),
// 선택된 아이템 제거
removeSelectedItem: (itemId) =>
set((state) => ({
selectedItems: state.selectedItems.filter((item) => item.id !== itemId),
})),
// 선택된 아이템 모두 제거
clearSelectedItems: () => set({ selectedItems: [] }),
}))
// // 전체 데이터 초기화 함수
// async function fetchInitialSuitablee() {
// try {
// const suitable = await suitableApi.getList()
// return suitable
// } catch (error) {
// console.error('초기 데이터 로드 실패:', error)
// return []
// }
// }