Description
Hi there, I have faced an error while creating a project. This is a file in the route.js. I am using prisma database to connect. I have checked all those npx prisma migrate and they still came out with this error.
Here is my code:
`import db from "@/lib/db";
import { NextResponse } from "next/server";
export async function POST(request) {
try {
// Read and parse request body
let body;
try {
body = await request.json();
} catch (err) {
console.error("Invalid JSON received:", err);
return NextResponse.json(
{ message: "Invalid JSON format" },
{ status: 400 }
);
}
if (!body || Object.keys(body).length === 0) {
return NextResponse.json(
{ message: "Request body cannot be empty" },
{ status: 400 }
);
}
// Validate required fields
const requiredFields = ["name", "quantity", "sellingPrice", "buyingPrice"];
for (const field of requiredFields) {
if (!body[field]) {
return NextResponse.json(
{ message: `Missing required field: ${field}` },
{ status: 400 }
);
}
}
// Log request body for debugging
console.log("Received body:", body);
// Extract fields with safe default values
const {
name,
description = "",
categoryId = null,
sku = "",
barcode = "",
quantity,
unitId = null,
brandId = null,
sellingPrice,
buyingPrice,
supplierId = null,
reOrderPoint = null,
location = "",
imageURL = "",
weight = null,
dimensions = "",
taxRate = null,
notes = "",
} = body;
// Convert numeric fields safely
const numericFields = {
quantity: isNaN(parseInt(quantity, 10)) ? 0 : parseInt(quantity, 10),
sellingPrice: isNaN(parseFloat(sellingPrice))
? 0
: parseFloat(sellingPrice),
buyingPrice: isNaN(parseFloat(buyingPrice)) ? 0 : parseFloat(buyingPrice),
weight: weight ? parseFloat(weight) : null,
taxRate: taxRate ? parseFloat(taxRate) : null,
reOrderPoint: reOrderPoint ? parseInt(reOrderPoint, 10) : null,
};
// Insert into the database
const newItem = await db.item.create({
data: {
name,
description,
categoryId,
sku,
barcode,
unitId,
brandId,
supplierId,
location: location || null,
imageURL: imageURL || null,
dimensions,
notes,
...numericFields,
},
});
console.log("Created item:", newItem);
if (!newItem) {
throw new Error("Database returned null, possible insertion failure");
}
return NextResponse.json(newItem, { status: 201 });
} catch (error) {
console.error("Error creating item:", error);
return NextResponse.json(
{ message: "Failed to create item", error: error.message },
{ status: 500 }
);
}
}
export async function GET(request) {
try {
const items = await db.item.findMany({
orderBy: { createdAt: "desc" },
});
return NextResponse.json(items);
} catch (error) {
console.error("Error fetching items:", error);
return NextResponse.json(
{ message: "Failed to fetch items", error: error.message },
{ status: 400 }
);
}
}
`Please help me ASAP. Thank you everyone!