I recently created a new API route named route.ts, where I included two different routes. One route retrieves all users from the database, while the other retrieves a specific user based on their ID passed as a query parameter. However, when testing these routes using Postman, I discovered that the route for fetching a single user was returning all users instead of just the one with the specified ID. I utilized Prisma for querying purposes. How can I resolve this issue?
Code snippet for retrieving a single user:
import { NextResponse } from "next/server";
import prisma from '@/libs/prismadb'
import { NextApiRequest } from "next";
export async function GET(
req:NextApiRequest,
){
if(req.method!=='GET')
{
return NextResponse.json({"message":"something went wrong","status":400});
}
try {
const users = await prisma.user.findMany({
orderBy:{
createdAt:'desc'
}
})
return NextResponse.json({"message":users,"status":200});
} catch (error) {
console.log(error)
return NextResponse.json({"message":"something went wrong","status":400});
}
}
Code snippet for retrieving all users:
import { NextRequest, NextResponse } from "next/server";
import prisma from '@/libs/prismadb'
import { NextApiRequest, NextApiResponse } from "next";
export async function GET(
req:NextApiRequest,
res:NextApiResponse
)
{
try {
const {userId} = req.query
if(!userId || typeof userId!=='string')
{
throw new Error("Something Went Wrong")
}
const existingUser = await prisma.user.findUnique({
where:{
id:userId
}
})
NextResponse.json({"message":existingUser,"Status":200})
} catch (error) {
console.log(error)
NextResponse.json(error)
}
}