I'm trying to create a dynamic route for messages based on the senderId
, but I don't seem to be doing it correctly, this API is simply returning all messages from the database, instead of only returning messages from a specific senderId (http://localhost:3000/api/messages?senderId=29)
. I'm using Next.js 13 with the App Route directory. This is the dynamic route that I created api/messages/[messageId]/route.ts
in this case the api to retrieve my messages through senderId
is present inside [messageId]
. Below is my API and my model
model Message {
id Int @id @default(autoincrement())
senderId Int
content String
imageUrl String?
createdAt DateTime @default(now())
sender User @relation(fields: [senderId], references: [id])
}
import { db as prisma } from "@/lib/db";
export async function GET(
request: Request,
context: { params: { senderId: number } }
) {
try {
const senderId = Number(context.params.senderId);
const userMessages = await prisma.message.findMany({
where: {
senderId: {
equals: senderId,
},
},
});
if (!userMessages || userMessages.length === 0) {
return new Response(
JSON.stringify({ message: "Mensagens não encontradas" }),
{ status: 400 }
);
}
return new Response(JSON.stringify(userMessages), { status: 200 });
} catch (error) {
console.error("Erro ao buscar mensagens:", error);
return new Response(
JSON.stringify({ message: "Erro ao buscar mensagens" }),
{
status: 500,
}
);
} finally {
await prisma.$disconnect();
}
}
I replicated what the doc said, but it was unsuccessful