How to use Express app's API routes as part of main application

I have a website that will use EJS templating to display data from my database. Instead of creating a second API just to do this, I would like to use the pre-existing API that other developers can use. Is there a way to get data from my API in the most meta way possible.

main app route

app.get("/facts/random", async (req, res) => {
  /* Make request to /api/random here and get JSON data */
});

API route

app.get("/api/random/", async (req, res) => {
  let results = await Fact.find();
  const randomResult = Math.floor(Math.random() * results.length);
  return res.json(results[randomResult]);
})

I want to make a request from the first route to the second route using the most meta way possible.


Solution 1:

Usually, you don't have your own http server make a request to itself. Usually, you just factor out the functionality the other API is using into an exported function and you call the function directly.

It's definitely more efficient that way since there's really no reason to package it up into an http request, go through the network stack, parse it as an http request in your server, process it, create an http response, send that back through the network stack, parse the response, then process it when you could avoid 6 of those 8 steps by just calling a common function you factored out.

app.get("/facts/random", async (req, res) => {
  let randomResult = await apiRandom();
  ...
});

async function apiRandom() {
  let results = await Fact.find();
  const randomResult = Math.floor(Math.random() * results.length);
  return results[randomResult];
}

app.get("/api/random/", async (req, res) => {
  let randomResult = await apiRandom();
  res.json(randomResult);
});

If, for some reason, you do want to make requests to your own http server, then get a library like got() or axios() that makes that easy.

Solution 2:

If /api/random is in another microservice then you can use Axios to make an http call, but if it is in the same Express App then refactor the code and turn it into a function and call that function in both the controllers.