Yashvi
Yashvi

Reputation: 55

Importing API Routes

How should I rewrite this as a function? I'm building a tool using Next.JS and using their API endpoint to interact with MongoDB. The NextJS website says:

Note: You should not use fetch() to call an API route in your application. Instead, directly import the API route and call its function yourself. You may need to slightly refactor your code for this approach. Fetching from an external API is fine!

How should I refactor my code to adjust to 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;

Upvotes: 1

Views: 746

Answers (1)

Pierfrancesco
Pierfrancesco

Reputation: 528

Looking at NextJS doc here:

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

you probably should have a structure like this:

export default async (req, res) => {
    try {
        let query = req.query;
        let queryName = Object.values(query)[0];
        // modify with the module to make query to db
        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.' }))
    }

}

Didn't try it but hope it gives an idea.

Upvotes: 1

Related Questions