feat: 지붕재 데이터 조회 기능 추가
This commit is contained in:
parent
0cdc3984b8
commit
cc8ef6a7d3
@ -38,14 +38,31 @@ export interface Suitable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const suitableApi = {
|
export const suitableApi = {
|
||||||
getList: async (): Promise<Suitable[]> => {
|
getList: async (category?: string, keyword?: string): Promise<Suitable[]> => {
|
||||||
const response = await axiosInstance.get<Suitable[]>('/api/suitable/list')
|
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)
|
console.log('🚀 ~ getList: ~ response:', response)
|
||||||
return response.data
|
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[]> => {
|
getDetails: async (roofMaterial: string): Promise<Suitable[]> => {
|
||||||
const response = await axiosInstance.get<Suitable[]>(`/api/suitable/details?roof-material=${roofMaterial}`)
|
const response = await axiosInstance.get<Suitable[]>(`/api/suitable/details?roof-material=${roofMaterial}`)
|
||||||
|
console.log('🚀 ~ getDetails: ~ response:', response)
|
||||||
return response.data
|
return response.data
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
16
src/app/api/suitable/category/route.ts
Normal file
16
src/app/api/suitable/category/route.ts
Normal 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)
|
||||||
|
}
|
||||||
@ -1,8 +1,35 @@
|
|||||||
import { NextResponse } from 'next/server'
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
import { prisma } from '@/libs/prisma'
|
import { prisma } from '@/libs/prisma'
|
||||||
|
|
||||||
export async function GET() {
|
|
||||||
// @ts-ignore
|
export async function GET(request: NextRequest) {
|
||||||
const suitables = await prisma.MS_SUITABLE.findMany()
|
try {
|
||||||
return NextResponse.json(suitables)
|
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 })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,16 +1,23 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { suitableApi } from '@/api/suitable'
|
import { useSuitableStore } from '@/store/useSuitableStore'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { useRouter } from 'next/navigation'
|
import { useRouter } from 'next/navigation'
|
||||||
|
import type { Suitable as SuitableType } from '@/api/suitable'
|
||||||
|
|
||||||
export default function Suitable() {
|
export default function Suitable() {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const { data, error, isPending } = useQuery({
|
const { selectedItems, addSelectedItem } = useSuitableStore()
|
||||||
queryKey: ['suitable-list'],
|
|
||||||
queryFn: suitableApi.getList,
|
const { data: suitableList, isLoading } = useQuery<SuitableType[]>({
|
||||||
|
queryKey: ['suitables', 'search'],
|
||||||
|
enabled: false,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
if (isLoading || !suitableList) {
|
||||||
|
return <div>Loading...</div>
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<h1 className="text-4xl font-bold">Suitable</h1>
|
<h1 className="text-4xl font-bold">Suitable</h1>
|
||||||
@ -22,9 +29,23 @@ export default function Suitable() {
|
|||||||
>
|
>
|
||||||
HOME
|
HOME
|
||||||
</button>
|
</button>
|
||||||
{error && <div>Error: {error.message}</div>}
|
<div>
|
||||||
{isPending && <div>Loading...</div>}
|
<h2 className="text-lg font-semibold mb-2">선택된 아이템</h2>
|
||||||
{data && data.map((item) => <div key={item.id}>{item.product_name}</div>)}
|
{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>
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,21 +1,85 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { useRouter } from 'next/navigation'
|
import { useRouter } from 'next/navigation'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { useSuitable } from '@/hooks/useSuitable'
|
||||||
|
|
||||||
export default function SuitableSearch() {
|
export default function SuitableSearch() {
|
||||||
const router = useRouter()
|
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 (
|
return (
|
||||||
<>
|
<>
|
||||||
<select onChange={(e) => setSelectedValue(e.target.value)}>
|
<div>
|
||||||
<option value="">선택 고고</option>
|
<select value={selectedCategory || ''} onChange={(e) => setSelectedCategory(e.target.value)}>
|
||||||
<option value="瓦">瓦</option>
|
<option value="">지붕재 카테고리 선택 고고</option>
|
||||||
<option value="スレート">スレート</option>
|
{categories?.map((category) => (
|
||||||
<option value="アスファルトシングル">アスファルトシングル</option>
|
<option key={category.roof_material} value={category.roof_material}>
|
||||||
</select>
|
{category.roof_material}
|
||||||
<button onClick={() => router.push(`/suitable/${selectedValue}`)}>검색</button>
|
</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
30
src/hooks/useSuitable.ts
Normal 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 }
|
||||||
|
}
|
||||||
68
src/store/useSuitableStore.ts
Normal file
68
src/store/useSuitableStore.ts
Normal 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 []
|
||||||
|
// }
|
||||||
|
// }
|
||||||
Loading…
x
Reference in New Issue
Block a user