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

Are Next.js API directory and files secure for saving sensitive information like API keys, secret words, and more?

I am in the process of creating a straightforward Next.js route specifically designed for managing payments. Within this route's handler, I am communicating with a third-party service using fetch to facilitate payment processing. To ensure security, o ...

Can you detail the process of storing the prerendered HTML of dynamically generated pages using incremental static generation (ISR) in Next.js, such as saving it to AWS S3?

Imagine having a multi-user blog platform similar to Medium, where users can create new blog pages from the website's UI. What if you could have the HTML of these newly created pages statically prerendered and served from a cache under dynamic routes ...

Integrating Prometheus with your next.js application

I am looking to integrate prom-client into my nextjs app, but I am struggling to find examples or guidance on how to do so. Specifically, I want to incorporate Prometheus with prom-client and use a histogram in the getServerSideProps function. Below is m ...

Developing a React-based UI library that combines both client-side and server-side components: A step-by-step

I'm working on developing a library that will export both server components and client components. The goal is to have it compatible with the Next.js app router, but I've run into a problem. It seems like when I build the library, the client comp ...

An error occurred with the datepicker: Unable to connect to 'bsValue' as it is not recognized as a property of 'input'

Despite importing DatepickerModule.forRoot() in my Angular unit test, I am encountering the following error: Error: Template parse errors: Can't bind to 'bsConfig' since it isn't a known property of 'input'. (" ...

Can SystemJS, JetBrains IntelliJ, and modules be combined effectively?

Looking for some clarification on the functionality of module includes and systemJS within an Angular2 app structure. I have set up a basic Angular2 app with the following layout: -app |-lib (contains shims and node libraries) |-components |-app |-app. ...

Exploring the wonders of upgrading to Storybook 7.* with NextJS: a comprehensive guide on transp

I am encountering difficulties while attempting to upgrade to the latest version of Storybook (7.*), specifically with transpiling modules. Unfortunately, the documentation provided by Storybook does not offer much assistance on this matter. Any help wou ...

The value binding for input elements in Angular 4 remains static and does not reflect changes in the UI

Struggling with binding input to a value in angular 4? Take for example [value]="inputFrom". Sometimes it updates when I change inputFrom, other times it doesn't. How can I ensure the input always changes whenever inputFrom changes, not sporadically? ...

Is it possible to restrict optionality in Typescript interfaces based on a boolean value?

Currently, I am working on an interface where I need to implement the following structure: export interface Passenger { id: number, name: string, checkedIn: boolean, checkedInDate?: Date // <- Is it possible to make this f ...

Angular Typescript subscription value is null even though the template still receives the data

As a newcomer to Angular and Typescript, I've encountered a peculiar issue. When trying to populate a mat-table with values retrieved from a backend API, the data appears empty in my component but suddenly shows up when rendering the template. Here&a ...

Updating NPM packages versions is currently restricted

I'm in the process of creating a Next.JS application using create-next-app. However, I've noticed that in the package.json file it lists the following dependencies: "eslint": "8.43.0", "eslint-config-next": &quo ...

What is the best way to display values from a Localstorage array in a tabular format using a looping structure

I have set up a local storage key 'fsubs' to store form submissions as an array. Here is how I am doing it: var fsubs = JSON.parse(localStorage.getItem('fsubs') || "[]"); var fcodes = {"barcodeno" : this.form.value.barcode, "reelno" : ...

Please click twice in order to log in to Angular 16

Whenever I attempt to log in, I face the issue of having to click twice. The first click does not work, but the second one does. Additionally, an error message pops up: TypeError: Cannot read properties of undefined (reading 'name'). I am unsure ...

How to seamlessly incorporate Polymer Web Components into a Typescript-based React application?

Struggling to implement a Polymer Web Components tooltip feature into a React App coded in TypeScript. Encountering an error during compilation: Error: Property 'paper-tooltip' does not exist on type 'JSX.IntrinsicElements' To resolve ...

The abundance of information presented in the "object" type, specifically "[object Object]," prevents serialization as JSON. It is advised to exclusively provide data types that are JSON

Utilizing NextJS, I initially made internal calls to a /api route using fetch(). However, for production, it was evident that internal api calls within getServerSideProps are not allowed. Consequently, I am attempting to directly access my MongoDB database ...

error - Uncaught ReferenceError: Unable to use 'auth' before initializing

I am currently following an online tutorial on building a WhatsApp clone and I encountered a problem. import "../styles/globals.css"; import { useAuthState } from "react-firebase-hooks/auth"; import { auth, db } from "../f ...

The most recent iteration of Next.js 9 in action features a flash of unstyled content when using Material-UI

Check out this live example: After loading, the styling flashes briefly but then the white font disappears on the buttons Here's where you can find the code for this issue: https://github.com/fillipvt/nodeco-web What could be causing this problem? ...

Optimizing File Transfers and Streaming Using Next.js and CDN Integration

As I work on developing a download system for large files on my website using Next.js and hosting the files on a CDN, I face the challenge of downloading multiple files from the CDN, creating a zip archive, and sending it to the client. Currently, I have i ...

MasterNG - Submitting form details and uploading files with a button press

Our Angular project involves a form with various form fields along with PrimeNG FileUpload, and our goal is to send the form data along with the selected files in one go. Despite researching the documentation and numerous examples online, we couldn't ...

performing resolver when needed in angular version 5

I have been working on a project using Angular and recently updated it from version 4.2 to Angular 5. Although I haven't utilized any new features introduced in Angular 5 yet. My current task involves executing a resolver on a specific route when a c ...