What is the best way to redirect multiple paths in Express.js and consolidate them into a single outcome?

I typically make several .get requests, such as the following for notesController

controller.get('/customers/', async (req, res, next) => {
    const customers = await Customer.find();
    res.status(200).send(customers);
  });

controller.get('/documents/', async (req, res, next) => {
    const orders = await Order.find();
    res.status(200).send(orders);
  });

Sometimes, I need to call both of them simultaneously like this:

controller.get('/version/', async (req, res, next) => {
  const ver = await Version.findById(req.headers.sub);
  if (req.headers.dbversion === ver.dbversion) {
     res.status(200).send({ versionMatch: true });
   } else {
     req.url = '/customers/';
     const custData = await controller.handle(req, res, next);
     req.url = '/orders/';
     const orders = await controller.handle(req, res, next);
     res.status(200).send({ customers: custData, docs: invoices });
     }
   });

Unfortunately, this approach does not work. Even though I can see from a console message that my .get('/customers') function is being called, it does not return any data. My goal is to be able to make one API call and receive both sets of data if certain conditions are met. How can I best achieve this?

Answer №1

If you're using express, achieving this may pose a challenge. The best approach would be to create separate standalone functions to handle the request. Once your conditions are satisfied, then call these functions to retrieve both data sets.

controller.get('/clients/', async (req, res, next) => {
    const clients = fetchClients(args);
    if (condition is fulfilled) {
      const projects = getProjects();
    }
    res.status(200).send({ clients, projects });
  });

controller.get('/files/', async (req, res, next) => {
    const projects = getProjects(args);
    res.status(200).send(projects);
  });

function fetchClients(args) {
  const clients = await Client.find();
  return clients;
}
function getProjects(args) {
  const projects = await Project.find();
  return projects
}

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

Streamline the process of sorting through 2 arrays

Is there a more concise and elegant way to achieve the same functionality as my current method? I am looking for a shorter solution to create an array of items that haven't been used in the form previously, which are then used to populate a select dro ...

Middleware is encountering a request with missing user information

I've run into an issue where req.user is empty whenever I use the checkAdmin middleware in my routes Trying to create a middleware that checks if the user's role is ADMIN to allow them to create a new user, but it's failing. When the middle ...

Utilizing the canvas context to place an HTML5 element onto the canvas

Here's a code example where I am attempting to draw an object using context. An error is being thrown in Firefox 15: TypeError: el is null [Break On This Error] Even though GetElementById has been properly fetched, it still results in an error. I h ...

Stop accidental clicking on objects in React-Fiber which are using Three.js

Check out this interactive cube made up of planes! An issue I've encountered is that clicking on a plane passes through to the ones behind it, rather than only registering a click on the plane directly under my mouse. Any suggestions for fixing this ...

Establishing a connection to MongoDB using JavaScript

Currently, I'm working on a fun little project revolving around a web calendar. For this project, I've decided to integrate mongoDB into it. Fortunately, I have successfully configured MongoDB and established a connection with PHP. However, I am ...

Vue js has a feature that enables users to input numbers with precision up to two decimal places

Currently facing an issue where I need to restrict input to no more than 2 decimal places. I came across a solution in a thread on Stack Overflow which addresses this using jQuery: JQuery allow only two numbers after decimal point. However, I am looking ...

Tips on how to retrieve the value of a number-type input within a custom attribute directive

I have successfully implemented this code in IE 11, but now we are looking to transition away from IE11 and address some of the issues that have arisen. <input type="number" evaluate-input="model.personalNumber" ng-model="model ...

What is the best way to ensure that two objects collide with one another?

Issue Description I am currently working on implementing collision detection for two objects. The goal is to determine if the objects are intersecting by calculating their bounding boxes with Box3 and using the .intersectsBox() function to obtain a boolea ...

Why won't my picture track the movement of the cursor?

I am trying to make my image follow the cursor using a specific code, but it doesn't seem to be working. I'm having trouble figuring out what's wrong with it. Here is the code snippet that I'm currently using: function followIt(e) ...

Having difficulty invoking a function from an external JavaScript file

Clicking on a button triggers the function showDiv(). The showDiv() function is defined in an external JavaScript file named script.js. When using an external script file, the showDiv() function does not get called. However, placing the script in the sam ...

Alas, an error has occurred with eslint npm. The elusive 404 Not Found reared its head once more when attempting to access the es

I'm currently in the process of organizing my JavaScript code and preparing to transition to TypeScript. I recently set up node.js, npm, and eslint on my Ubuntu 20.04 system. After doing so, I executed npm -init and eslint -init. $ npx eslist util.js ...

How can one determine the template engine utilized by a website?

As I delve into reverse engineering a couple of web applications, my main objective is to uncover the technologies they are built upon. This will allow me to determine which technology stack to focus on learning in order to develop my own web application. ...

The navigation bar is positioned with white space above it

Currently working on a website design and facing an issue with adding a clickable button to the Nav-bar. Noticed some white-space above the Nav-bar which is not desired. I had previously posted a similar question but unable to identify the CSS error causi ...

How can I make the droppable elements only drop within draggable elements in jQuery UI?

After reading several similar articles and questions, I am still struggling to get this working properly when there are multiple droppable elements with the same named class. Is there a way to ensure that the dragged element can only be dropped in a speci ...

Is there a way to access a header value using nodejs and express?

Is there a way to retrieve the x-api-key value sent in the header of my endpoint using the GET method? The code works fine on my localhost but it throws an error on the server. Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the ...

Can you explain the return value of array.find() in Typescript or Java script?

In my Typescript code, I have the following line: const addressFound: AddressPrimary = <AddressPrimary>(this.addressArray.find(addr => addr.id === id)); The AddressPrimary class contains various variables such as id: number, city: number, and oth ...

Failing to hide a div on hover: Hoverintent's shortcomings

When I hover over the div with the unique identifier id="navbar", it doesn't seem to trigger any actions. I have included the following script in my document head: <script type="text/javascript" src="https://ajax.googleapi ...

Steps for executing a Node script are as follows:

My task is to execute a node script that will remove an object from an external API. This can be achieved by running the following command: node server.js Customer55555 Upon execution, the specified object should be deleted successfully. To interact wit ...

Tips for Verifying Checkbox in Angular 5

When attempting to validate the checkboxes in a form with different fields, I encounter an issue. The HTML code for the form is as follows: <div class="form-group"> <label class="login_label">Courses</label> <span style="col ...

iOS Devices Experiencing HTTP 500 Error with JS Files and Libraries

I have encountered a puzzling issue with my web application. While it runs smoothly on PC devices without any errors, I am facing HTTP 500 errors when running it on iOS and inspecting it using Safari's Web Inspector. Specifically, I am seeing these er ...