Adicionar src/app/api/cars/route.js
This commit is contained in:
58
src/app/api/cars/route.js
Normal file
58
src/app/api/cars/route.js
Normal 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 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user