encountered an issue when testing a dynamic route in Next.js with postman

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)
    }

}

Answer №1

Utilizing the findMany function to fetch a single user may be confusing, as it actually retrieves all users. Conversely, the code intended for fetching all users appears tailored for obtaining a single user by their ID.

Below is the code snippet for retrieving all users:

import { NextResponse } from "next/server";
import prisma from '@/libs/prismadb';

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 });
  }
}

Furthermore, here's the extract for fetching a singular user:

import { 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: parseInt(userId),
      },
    });

    res.json({ "message": existingUser, "Status": 200 });
  } catch (error) {
    console.log(error);
    res.json(error);
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I have come across this building error, what do you think is the cause of it?

My attempt to launch my company's React.js project, downloaded from Tortoise SVN, is encountering an issue. PS C:\Projects\Old EHR> yarn start yarn run v1.22.19 $ next start ready - started server on 0.0.0.0:3000, url: http://localhost:30 ...

What is the method for obtaining the union type of interface values (including string enums)?

How can I achieve the following ? Given : enum FooEnum1 { Foo = "foo", }; enum FooEnum2 { Foo = 1, }; interface FooInterface { foo1 : FooEnum1, foo2 : FooEnum2, foo3 : string, foo4 : number, }; I am interested in cre ...

The functionality of Angular 5 reactive form valueChanges is not functioning correctly

I am currently working with a form inside a service: this.settingsForm = this.formBuilder.group({ names: this.formBuilder.array([]), globalIDs: this.formBuilder.array([]), topics: this.formBuilder.array([]), emails: thi ...

Issue with implementing MUI Style Tag in conjunction with styled-components and Typescript

I have created a custom SelectType component using Styled Components, which looks like this: import Select from '@mui/material/Select'; export const SelectType = styled(Select)` width:100%; border:2px solid #eaeaef; border-radius:8px ...

What is the right way to configure an Axios Interceptor in a ReactJS app using TypeScript?

While I typically use JS with React, I decided to switch to Typescript. However, I've been encountering an error when trying to initialize a request interceptor instance: src/utils/services/axios.service.ts:16:8 TS2322: Type '{ 'Content-Type ...

The error message is: "Cannot access property 'up' of an undefined object within the material UI library using theme.breakpoints."

I am encountering difficulties with the export of makeStyles. Below you can find my code and configuration: import SearchField from "../SearchField"; import { TextField, Select, useMediaQuery, Grid, Button, Box, Fade } from '@material-ui/core&ap ...

Encountering a TSLint interface error when adding a value to a nested array

Currently, I am transforming responses into an array of Months and Days, with each Day containing an array of numbers. The logic itself is functioning properly, however, I am encountering a tslint error specifically when attempting to push a value into the ...

What is the best way to send props to a child component in JSX with TypeScript?

While passing props to the child, I encountered an error message stating "Property 'isClicked' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes". I defined "isClicked?: boolean" in my code. What additional steps sho ...

Combining redirection and adding query parameters using Next.js useRouter

Goal: Redirect to /user?id=123 from any page in NextJS. Redirecting to any page can be done with: const router = useRouter(); router.push("/user"); To add parameters to the URL, use the following code: const router = useRouter(); router.query.i ...

It is possible that the object may be null, as indicated by TS2531 error

I was interested in using QrReader to scan a file based on [https://github.com/Musawirkhann/react_qrcode_generation_scanner This code is written in react, but I wanted to use it with tsx. However, when attempting to implement it, I encountered an error: ...

A step-by-step guide on injecting a model within the root app module of a Nest JS application

Hello, I encountered an error in my Nest app and here is a screenshot of the error: https://i.stack.imgur.com/zY1io.png Below is the code snippet for the AppModule: @Module({ imports: [AppModule,CrudModule,MongooseModule.forRoot("mongodb://localhost:2 ...

Having trouble triggering a change event within a React component?

I'm working on a straightforward react-component that consists of a form. Within this form, the user can search for other users. To ensure the form is valid, there needs to be between 3 and 6 users added. To achieve this, I've included a hidden ...

Is it possible to pass a variable to a text constant in Angular?

In my constant file, I keep track of all global values. Here is the content of the file: module.exports = { PORT: process.env.PORT || 4000, SERVER: "http://localhost:4200", FAIL_RESULT: "NOK", SUCCESSFUL_RESULT: "OK ...

Unable to retrieve property from NextRequest

Currently, I am attempting to utilize MiddleWare in conjunction with Next.js's Middleware and JWT. Upon logging cookies and the typeof cookies variable, this is what I see on my console: { token: 'token='myToken'; Path=/' } obj ...

After deploying a Next.js project on an Ubuntu server, dynamic pages are returning a 404 error

I've been putting in a substantial amount of time on this project. I'm encountering some 404 errors on my dynamic pages, even though they work perfectly fine on localhost. I've tried using revalidate and playing around with fallback: true an ...

Issue encountered when deploying on Vercel after integrating next-i18next

Latest Update: The issue at hand may be related to changes made in this PR where assets were removed as a dependency. Previous Update: Successfully obtained a reverse shell into the serverless function and it seems that the public folder is no longer pre ...

Having trouble passing the theme in Next.js when using Styled Components?

I'm facing an issue with passing my theme object to styled-components in my Next.js project as it fails to receive it as props. Here is my _document.tsx: import { getInitialProps } from "@expo/next-adapter/document"; import Document, { DocumentConte ...

What is the best way to refresh a page after rotating the web page?

Struggling with a challenge in Next JS - can't seem to figure out how to automatically refresh the page when it rotates const app () => { useEffect(()=>{ window.addEventListener("orientationchange", function() { window.locati ...

React application experiencing incorrect hexadecimal hash value output in crypto function

In my Reactjs app rendered by Nextjs, I am confused about why I am receiving different hash values in the web browser when using this code: crypto.createHash('sha256').update("12345678").digest("hex"); The expected hash value from the sha256 on ...

What sets index.js apart from page.js in next.js?

https://nextjs.org/docs/pages/building-your-application/routing/pages-and-layouts While reading through the next.js documentation, I came across an interesting point. The documentation mentions that index.js serves as the root of the directory. This mean ...