103 lines
2.5 KiB
TypeScript
103 lines
2.5 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { prisma } from '@/lib/prisma'
|
|
import { requireAdmin } from '@/lib/admin-auth'
|
|
|
|
// 获取所有组件
|
|
export async function GET(request: NextRequest) {
|
|
try {
|
|
await requireAdmin(request)
|
|
|
|
const { searchParams } = new URL(request.url)
|
|
const page = parseInt(searchParams.get('page') || '1')
|
|
const limit = parseInt(searchParams.get('limit') || '20')
|
|
const type = searchParams.get('type')
|
|
const search = searchParams.get('search')
|
|
|
|
const where: any = {}
|
|
if (type) {
|
|
where.componentType = {
|
|
name: type
|
|
}
|
|
}
|
|
if (search) {
|
|
where.OR = [
|
|
{ name: { contains: search, mode: 'insensitive' } },
|
|
{ brand: { 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 })
|
|
])
|
|
|
|
return NextResponse.json({
|
|
components,
|
|
pagination: {
|
|
page,
|
|
limit,
|
|
total,
|
|
pages: Math.ceil(total / limit)
|
|
}
|
|
})
|
|
|
|
} catch (error: any) {
|
|
return NextResponse.json(
|
|
{ message: error.message || '获取组件列表失败' },
|
|
{ status: error.message === '权限不足' ? 403 : 500 }
|
|
)
|
|
}
|
|
}
|
|
|
|
// 创建新组件
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
await requireAdmin(request)
|
|
|
|
const body = await request.json()
|
|
const { name, brand, model, price, description, imageUrl, stock, specifications, componentTypeId } = body
|
|
|
|
if (!name || !brand || !model || !price || !componentTypeId) {
|
|
return NextResponse.json(
|
|
{ message: '请填写所有必填字段' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
const component = await prisma.component.create({
|
|
data: {
|
|
name,
|
|
brand,
|
|
model,
|
|
price: parseFloat(price),
|
|
description,
|
|
imageUrl,
|
|
stock: parseInt(stock) || 0,
|
|
specifications: specifications ? JSON.stringify(specifications) : null,
|
|
componentTypeId
|
|
},
|
|
include: {
|
|
componentType: true
|
|
}
|
|
})
|
|
|
|
return NextResponse.json(component, { status: 201 })
|
|
|
|
} catch (error: any) {
|
|
return NextResponse.json(
|
|
{ message: error.message || '创建组件失败' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|