2025-06-22 11:34:32 +08:00

111 lines
2.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const typeId = searchParams.get('type')
const brand = searchParams.get('brand')
const minPrice = searchParams.get('minPrice')
const maxPrice = searchParams.get('maxPrice')
const search = searchParams.get('search')
const page = parseInt(searchParams.get('page') || '1')
const limit = parseInt(searchParams.get('limit') || '12')
const where: any = {}
if (typeId) {
where.componentTypeId = typeId
}
if (brand) {
where.brand = {
contains: brand,
mode: 'insensitive'
}
}
if (minPrice || maxPrice) {
where.price = {}
if (minPrice) where.price.gte = parseFloat(minPrice)
if (maxPrice) where.price.lte = parseFloat(maxPrice)
}
if (search) {
where.OR = [
{ name: { contains: search, mode: 'insensitive' } },
{ brand: { contains: search, mode: 'insensitive' } },
{ model: { contains: search, mode: 'insensitive' } },
{ description: { contains: search, mode: 'insensitive' } }
]
}
const [components, total] = await Promise.all([
prisma.component.findMany({
where,
include: {
componentType: true
},
orderBy: {
createdAt: 'desc'
},
skip: (page - 1) * limit,
take: limit
}),
prisma.component.count({ where })
])
const totalPages = Math.ceil(total / limit)
return NextResponse.json({
components,
pagination: {
page,
limit,
total,
totalPages,
hasNext: page < totalPages,
hasPrev: page > 1
}
})
} catch (error) {
console.error('Components fetch error:', error)
return NextResponse.json(
{ message: '获取配件列表失败' },
{ status: 500 }
)
}
}
export async function POST(request: NextRequest) {
try {
// 这个API需要管理员权限暂时简化处理
const data = await request.json()
const component = await prisma.component.create({
data: {
name: data.name,
brand: data.brand,
model: data.model,
price: parseFloat(data.price),
description: data.description,
imageUrl: data.imageUrl,
stock: parseInt(data.stock),
specifications: data.specifications,
componentTypeId: data.componentTypeId
},
include: {
componentType: true
}
})
return NextResponse.json(component, { status: 201 })
} catch (error) {
console.error('Component create error:', error)
return NextResponse.json(
{ message: '创建配件失败' },
{ status: 500 }
)
}
}