Adicionar src/app/api/cars/route.js

This commit is contained in:
2024-11-27 13:23:48 -08:00
parent 00fa8587e4
commit b2e219b0c6

58
src/app/api/cars/route.js Normal file
View File

@ -0,0 +1,58 @@
import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
// POST /api/cars - Criar novo carro
export async function POST(request) {
try {
const data = await request.json();
// Criar o carro na base de dados
const car = await prisma.car.create({
data: {
name: data.name,
year: parseInt(data.year),
price: parseFloat(data.price),
isSpecial: data.isSpecial,
specs: data.specs,
images: {
create: data.images.map((image, index) => ({
imageUrl: image.url,
isMain: image.isMain
}))
}
},
include: {
images: true
}
});
return NextResponse.json(car);
} catch (error) {
console.error('Error creating car:', error);
return NextResponse.json(
{ error: 'Failed to create car' },
{ status: 500 }
);
}
}
// GET /api/cars - Listar carros
export async function GET() {
try {
const cars = await prisma.car.findMany({
include: {
images: true
}
});
return NextResponse.json(cars);
} catch (error) {
console.error('Error fetching cars:', error);
return NextResponse.json(
{ error: 'Failed to fetch cars' },
{ status: 500 }
);
}
}