Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { checkAdminAuth } from '@/lib/auth-check'
import { validatePrice, validateStock, validateRequired, ValidationError } from '@/lib/validation'
// POST /api/admin/products - Create a new product (Admin only)
export async function POST(request: Request) {
const authError = await checkAdminAuth()
Iif (authError) return authError
try {
const body = await request.json()
// Validate required fields
validateRequired(body.name, 'Product name')
validateRequired(body.category, 'Category')
validateRequired(body.shortDescription, 'Short description')
validateRequired(body.description, 'Description')
// Validate price and stock
const price = validatePrice(body.price)
const salePrice = body.salePrice ? validatePrice(body.salePrice) : null
const stock = validateStock(body.stock)
// Validate sale price is less than regular price
Iif (salePrice !== null && salePrice >= price) {
throw new ValidationError('Sale price must be less than regular price')
}
const product = await prisma.product.create({
data: {
name: body.name,
price,
salePrice,
category: body.category,
subcategory: body.subcategory || '',
shortDescription: body.shortDescription,
description: body.description,
images: body.images || [],
isNew: body.isNew || false,
isUsed: body.isUsed || false,
condition: body.condition || null,
stock,
brand: body.brand || null,
specs: body.specs || null,
colors: body.colors || null,
sizes: body.sizes || null,
},
})
return NextResponse.json(product, { status: 201 })
} catch (error) {
console.error('Error creating product:', error)
if (error instanceof ValidationError) {
return NextResponse.json({ error: error.message }, { status: 400 })
}
return NextResponse.json({ error: 'Failed to create product' }, { status: 500 })
}
}
|