let's say I have a REST API in express. For example this endpoint
async function getStoreController(req, res, next) {
try {
const { id } = req.params;
const storeData = await Stores.getStoreById(id);
if (!Object.keys(storeData).length) {
return next(
new OperationError(`There is no sotre with id ${id}`, 404, "error")
);
}
res.status(200).json({
status: "success",
data: storeData,
});
} catch (err) {
next(err);
}
}
I want to use the same data in my view in another endpoint and when I use the previous function as a middleware or even call it then render the view an error will occur because I finished the request already. Is there a solution ? and should I make a function that only compute and return the data so if there is an REST API or web application wants this data then both of them can call the same function but the first one return JSON and the second one render a view ?
I tried a solution which is sending a fetch request to the previous endpoint and get the data then render it in my view.
Edit
async function store(req, res, next) {
try {
// Get the data from that endpoint
const data = getStoreData(); // simulate calling that endpoint
res.render("store", data);
} catch (err) {
next(err);
}
}
for example that endpoint uses the same data but suppose the function must validate and some other logic so I don't wanna repeat myself