I need to retrieve the orders from the database using Prisma based on the user's email (authenticated via Google Provider). Here is the repository - https://github.com/Jayesh-kahnani/Snatch
Here is the API.
// src/app/api/order/route.ts
import { NextApiRequest, NextApiResponse } from "next";
import prisma from "../../../../lib/prisma";
import { getSession } from "next-auth/react";
export default async function (req: NextApiRequest, res: NextApiResponse) {
try {
const session = await getSession({ req });
if (!session) {
return res.status(401).json({ error: "Unauthorized" });
}
if (req.method !== "GET") {
return res.status(405).json({ error: "Method Not Allowed" });
}
const userId = session.user?.email;
if (!userId) {
return res.status(400).json({ error: "User ID not found in session" });
}
const orders = await prisma.post.findMany({
where: {
author: { email: userId },
published: true,
},
include: {
author: { select: { name: true } },
},
});
res.status(200).json({ orders });
} catch (error) {
console.error("Error fetching orders:", error);
res.status(500).json({ error: "Internal Server Error" });
}
}
This is the Page Component:
// src/app/user-orders/page.tsx
"use client"
import { useState, useEffect } from "react";
import Post from "../ui/order-list";
interface Order {
id: string;
title: string;
content: string;
authorName: string;
}
export default function Page() {
const [orders, setOrders] = useState<Order[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
async function fetchOrders() {
try {
const response = await fetch("/api/order/route");
if (!response.ok) {
throw new Error("Failed to fetch orders");
}
const data = await response.json();
setOrders(data.orders);
setLoading(false);
} catch (error) {
console.error("Error fetching orders:", error);
setError("Failed to fetch orders. Please try again later.");
setLoading(false);
}
}
fetchOrders();
}, []);
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>{error}</div>;
}
return (
<div className="container mx-auto mt-8 px-4 sm:px-0 text-gray-600">
<h1 className="text-2xl font-bold text-gray-900 mb-4">Your Orders</h1>
{orders.length === 0 ? (
<div>No orders found.</div>
) : (
<div className="flex flex-wrap">
{orders.map((order) => (
<Post
key={order.id}
title={order.title}
content={order.content}
authorName={order.authorName || "Unknown"}
/>
))}
</div>
)}
</div>
);
}
However, I am facing an error during deployment:
▲ Next.js 14.0.4
- Environments: .env
Creating an optimized production build ...
✓ Compiled successfully
Linting and checking validity of types ...
Failed to compile.
src/app/api/orders/route.ts
Type error: Route "src/app/api/orders/route.ts" does not match the required types of a Next.js Route.
"default" is not a valid Route export field.
Error: Command "npx prisma generate && next build" exited with 1
or refer to this image https://github.com/vercel/next.js/assets/120279764/e6112b7f-a9d1-410e-b8f1-ac7ceced4695
this is my src/app/api/auth/[...nextauth]/route.ts
import { PrismaClient } from "@prisma/client";
import NextAuth, { User as NextAuthUser } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
interface MyUser extends NextAuthUser {
email: string;
name?: string;
}
const prisma = new PrismaClient();
const handler = NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
],
callbacks: {
async signIn(params) {
const { user } = params as { user: MyUser };
try {
const existingUser = await prisma.user.findUnique({
where: { email: user.email },
});
if (!existingUser) {
await prisma.user.create({
data: {
email: user.email,
name: user.name || "",
},
});
}
return true;
} catch (error) {
console.error("Error during sign-in:", error);
return false;
}
},
},
});
export { handler as GET, handler as POST };
Please assist. I am struggling to understand the issue and how to resolve it. I am new to Next.js and TypeScript.
I was expecting to display the list of orders placed by the logged-in user.