Bringing in API Routes

Can you assist me in converting this into a function? I am currently developing a tool with Next.JS and using their API endpoint to connect with MongoDB. According to the instructions on the NextJS website:

Note: Avoid using fetch() to call an API route within your application. Instead, directly import the API route and call its function. You might need to make some adjustments to your code following this method. However, fetching from an external API is perfectly acceptable!

What steps should I take to modify my code to align with this approach?

import handler from '../../middleware/common_middleware';


handler.get(async (req, res) => {
    try {
        let query = req.query;
        let queryName = Object.values(query)[0];
        let doc = await req.db.collection("Volunteers").find({"_id": queryName}).toArray();
        res.status(201).json(doc);
    }
    catch {
        res.status(400).send("The profile doesn't exist.");
    }
});

export default handler;

Answer №1

After reviewing the NextJS documentation at the following links:

https://nextjs.org/docs/api-routes/introduction
https://github.com/vercel/next.js/blob/canary/examples/api-routes-rest/pages/api/users.js

It appears that a structure similar to this might be suitable:

export default async (req, res) => {
    try {
        let query = req.query;
        let queryName = Object.values(query)[0];
        // Adjust with appropriate module for database queries
        let doc = await req.db.collection("Volunteers").find({"_id": queryName}).toArray();
        res.statusCode = 201;
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify({status:'success', data: doc});
    }
    catch {
        res.statusCode = 400
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify({status: 'error', data: 'The profile doesn't exist.' }))
    }

}

I haven't tested this code yet, but I hope it provides some guidance.

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

Order the Javascript array based on the frequency of each element's occurrence

Seeking assistance with Jquery sorting based on the number of occurrences in an array as I am new to Jquery and Javascript. Numerous sorting methods have been attempted without success. The current array in Javascript is allTypesArray = ["4", "4","2", "2 ...

Dealing with Prisma update complications in NextJS route handlers

How can I update a single record in the database using Prisma and Next.js Route Handlers API? import prisma from "../../../../lib/prisma"; import { NextResponse } from "next/server"; export async function POST(req) { try { const ...

Capture a snapshot with Protractor using the Jasmine2 Screenshot Reporter

The Protractor configuration file includes 2 custom reporting options: one for logging and the other is the protractor-jasmine2-screenshot-reporter. However, only a blank white screen is displayed when generating a screenshot png. Below is the code snippet ...

The Firebase signInWithPopup functionality suddenly shuts down in a Next.js project

Incorporating the signInWithPopup function for signing in has been successful during the development stage on my local server. const firebaseAuth = getAuth(app); const provider = new GoogleAuthProvider(); const [{ user, cartShow, cartItems }, dispatc ...

"Troubleshooting ng-submit in AngularJS: How to Fix a Function That

I've encountered an issue with my angular-promise where a http method is not being called when a form is submitted using ng-submit. There are no errors, but it seems like the function is never executed. Here's the JavaScript code snippet: myapp. ...

Modify background image upon hovering using AngularJS

I cannot seem to make the background images of my divs change. Despite trying various options, none of them have been successful. Here's an example of my code: <div ng-controller="mainController" class="main"> <div ng-repeat="land in lan ...

What methods can be used to accomplish this effect using CSS and/or Javascript?

Is there a way to achieve the desired effect using just a single line of text and CSS, instead of multiple heading tags and a CSS class like shown in the image below? Current Code : <h2 class="heading">Hi guys, How can i achieve this effect using j ...

Is it possible to make changes to a JavaScript file and then update it using an npm command?

I'm facing a challenge where I need to update an object value using an npm command in my React project. Here's an example of the code: const GLOBAL_CONSTANTS = { mobileIdNumber: '0', FOOTER_TEXT_LOGIN: 'v.3.8.215', DEFA ...

mongojs implementation that allows for asynchronous query execution without blocking

Forgive me for asking what may seem like a silly question, but I am struggling to make this work. Currently, as part of my learning journey with node.js and mongojs, I have encountered the following issue: Below is my server.js file server.get("/", funct ...

Is it possible for Angular to automatically update an `ng-model` within a <tfoot> element?

I am currently working on an angular table filter. Initially, I attempted to include it in the header, but encountered issues with the icon appearing in the wrong position and the sorting changing when focusing on the text box. After moving the box to the ...

Is there a way to decrease a field in a MongoDB database on a daily basis?

In the process of constructing an Angular2 application using MEAN stack architecture, I have a field called Remaining Days in my MongoDB database. I am interested in having this field automatically decrement by 1 each day. Do you know if this is possible ...

Most effective method for including and excluding items from an array using personalized checkboxes

Is there a way to dynamically add and remove objects from an array based on the selection of custom checkboxes, along with a trigger or flag indicating if the checkbox is checked? Using the onClick function const handleFilterValues = (meta_name, meta_valu ...

Navigating focus to an overlay using Selenium

I am facing an issue with an overlay displaying terms on top of the main window. The scrollbars are not behaving as expected: https://i.sstatic.net/nzaUa.png The new window does not register as a separate 'window' or tab, so traditional methods ...

A method of submitting by simply pressing the enter key alongside clicking on a Bootstrap button

Here is the HTML code I am using to input prompts into a chatbot: <div class="input-group mb-3"> <input type="text" class="form-control" id="chat-input"> <div class="input-group-append ...

Including a contact number on a smartphone's non-native app for iPhones and Androids

Looking to automate the process of adding a number to my contact list on both iPhone and Android devices. I am coding in Java, as well as using javascript and HTML5. Most solutions I have come across are for native apps. Does anyone know of a solution that ...

Stopping the parent from triggering jQuery

I am currently working on enabling the folding and unfolding of a nested list by clicking either the li element or the adjacent input type=[checkbox]. However, when checking the checkbox, it triggers the parent li to fold along with the container li. You ...

How does SWR affect React state changes and component re-rendering?

I am currently utilizing SWR for data fetching as outlined in the documentation: function App () { const [pageIndex, setPageIndex] = useState(0); // The API URL incorporates the page index, which is a React state. const { data } = useSWR(`/api/data? ...

Updating the request body in Next 13 with middleware.ts: A step-by-step guide

I am looking for a way to modify the request body in NEXT 13 using a middleware function: import { NextRequest, NextResponse } from 'next/server'; enum MiddlewareRoutes { ACCESS = '/api/access', } const middlewareHandler = async ( ...

Delete the item if the link uses Javascript: void(0)

<a class="slicknav_item" href="home">Home<span></span></a> <a class="slicknav_item" href="about">About<span></span></a> <a class="slicknav_item" href="javascript: void(0)">Services<span></span& ...

What is the best way to integrate a Svelte component into a vanilla JS project without including Svelte as a dependency in the main project?

Is there a way to import a Svelte component into a project that does not have Svelte as a dependency? Imagine creating an npm package with a Svelte component and installing it in different projects without needing to add Svelte as a dependency. The package ...