How to Fetch Data from an Api Handler from Another Api Handler in Nextjs?
Using Nextjs, I Am Struggling with Fetching Data from an Api Handler in Another Api Handler. /Api/Batch. Js Handler Retrieves Some Data from a Mongodb: Import...
Using Nextjs, I am struggling with fetching data from an API handler in another API handler.
/api/batch.js handler retrieves some data from a MongoDB:
import middleware from '../../libs/mongodb';
import nextConnect from 'next-connect';
const handler = nextConnect();
handler.use(middleware);
handler.get(async (req, res) => {
const {batch_uuid} = req.query
const batch_stats = await req.db.collection('stats').find({
'batch.uuid': uuid
}).toArray()
res.json(batch_stats)
})
export default (req, res) => handler.apply(req, res)
/api/stats.js handler retrieves some data from MySQL and, based on that and on data from Mongo, it builds a payload.
A dirty fix works as below in stats.js:
const response = await fetch(')
const data = await response.json()
// use data and build another payload
However, this requires doing an http call and it does not make sense to do it for an internal endpoint.
I tried calling the batch handler dirrectly, but getting undefined
const getBatch = require('./batch');
module.exports = async (req, res) => {
const accounts = await getBatch()
res.status(200).json({accounts})
}
What am I missing?
1 Answer
You could extract fetching data from the database to a separate module and import this module in both API handlers. Instead of one API endpoint making request to another API endpoint, API handlers would just use the same module that fetches data from MongoDB.