Dealing with intricate query parameters in Express.Js

Currently, I am working on developing REST APIs using Express.js. One particular express route that I have set up is as follows:

/api/customer

I have incorporated multiple query parameters into this route, such as:

/api/customer?name=jake
/api/customer?country=america
/api/customer?name=jake&country=america 
/api/customer?name=jake&limit=10

While handling these queries in my controllers, I find myself utilizing conditional statements excessively. This method may not be scalable given the increasing number of cases to consider. Is there a more efficient approach to manage this situation?

The following code snippet demonstrates how I handle these requests in my controller using Sequelize for database querying:

async function getAllCustomer(queryLimit, page) {  
  const customers = await Customer.findAll({
    limit: queryLimit ? parseInt(queryLimit) : null,
    offset: page ? parseInt(queryLimit) * parseInt(page) : null
  });
  
  return customers;
}

// Other controller functions omitted for brevity

function getCustomer(req, res) {
  const page = req.query.page;
  const queryLimit = req.query.limit;
  const name = req.query.name;
  const address = req.query.address;
  
  let customers;

  if (name && !address) {
    // Logic for finding customer by first names
  } else if (!name && address) {
    // Logic for finding customer by addresses
  } else if (name && address) {
    // Logic for finding customer by both names and addresses
  } else if (!name && !address) {
    // Default logic for fetching all customers
  }
}

Answer №1

If you're looking for a solution, consider implementing the following code snippet:

async function fetchCustomer(req, res) {
  const page = req.query.page;
  const queryLimit = req.query.limit;
  const name = req.query.name;
  const address = req.query.address;
  
  let query = { };
  if(name) {
    query.firstName = name;
  }
  
  if(address) {
    query.address = address;
  }
  
  let customers = await retrieveCustomers(query, queryLimit, page);
  res.status(200).send(customers)
  return;
}

async function retrieveCustomers(query, queryLimit, page) {  
  const customersList = await Customer.findAll({
    where: query,
    limit: queryLimit ? parseInt(queryLimit) : null,
    offset: page ? parseInt(queryLimit) * parseInt(page) : null
  });
  
  return customersList;
}

By the way, in your current implementation, the functions fetchCustomerByFirstName, fetchCustomerByAddress, and fetchCustomerByNameAddress require string parameters like name and address. However, you are passing arrays like names and addresses, which could potentially cause errors...

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

Tips for successfully executing child_process.exec within an ajax request

On a server that I have access to but not ownership of, there is a node js / express application running on port 3000. Various scripts are typically executed manually from the terminal or via cron job. My goal is to have a button on the client-side that tr ...

Enhancing Win8 apps with AppendTo/jquery-win8

Recently, I've been intrigued by the ToDoMVC samples and decided to try porting them into a Windows 8 JS app. I thought it would be as simple as copying and pasting the code while making sure to reference the necessary WinJS libraries. However, I soo ...

The command 'npm install -g bigcommerce-stencil/stencil-cli' failed to run properly in the Windows command prompt

Having successfully completed all installations on my Windows 7 SP1 PC, I attempted to run the following command: npm install -g bigcommerce-stencil/stencil-cli Unfortunately, I encountered an error as shown in the screenshot below: error screen For mo ...

Display previous messages in React JS chat when scrolling upwards

I am currently working on a chat application, as depicted in the image. Once the chat is initiated, it automatically scrolls down to display the most recent messages. My goal is to implement a feature where when a user scrolls up to reach the oldest mess ...

Filtering input based on its occurrence rate (enable/disable debounce)

Utilizing node on a raspberry pi and the module onoff to capture input. I am interested in running function B only if function A is triggered twice within one minute. var gpio = require('onoff').Gpio; var sensor = new gpio(7, 'in', &ap ...

Convert a prototype code to jQuery using AJAX syntax

Seeking advice on my code syntax as I transition from Prototype to jQuery. I currently have both frameworks running simultaneously and aim to streamline all scripts into jQuery for improved page load efficiency and speed. Migrating from Prototype to jQue ...

Javascript functions correctly when the HTML file is opened locally, however, it encounters issues when accessed through an http-server

My HTML file includes an embedded web widget from tradingview.com with the following code: <!-- TradingView Widget BEGIN --> <span id="tradingview-copyright"><a ref="nofollow noopener" target="_blank" href="http://www.tradingview.com" style ...

When the child of li is clicked instead

Below is a list I have: <ul id="orderlist"> <li id="2"> <span class="pull-right value">Ready</span> <img src="" class="img-responsive"> Filet Mignon <small>2 servings</small> <small ...

Setting up craco for jsx in your project

I am currently utilizing craco and grappling with how to configure jsx. I keep encountering the error below: Support for the experimental syntax 'jsx' isn't currently enabled (4:17): The suggestion is to add `babel/preset-react or utilize ...

Error message in Node.js with Multer: The function '.array' is not recognized

I've spent the last two days searching for a solution to this issue, but the only reference I could find was an unresolved problem reported on version 1.1.0: https://github.com/expressjs/multer/issues/338 I am using the Node.js SDK and Express framew ...

Troubleshooting the issue of post-initialization store updates not functioning in AlpineJS

When setting up a store, I initially use: document.addEventListener('alpine:init', () => { Alpine.store('selectedInput', 0) }) However, when attempting to update selectedInput within a function later on, it doesn't reflect th ...

Can you explain the contrast between window.performance and PerformanceObserver?

As I delve into exploring the performance APIs, I have come across window.performance and PerformanceObserver. These two functionalities seem to serve similar purposes. For instance, if I need to obtain the FCP time, I can retrieve it from performance.getE ...

Transfer data from an HTML form -> call the ajax load() function

My Current HTML Form Situation Currently, I have an HTML form set up with a text input field and a submit button. When the button is clicked, I want the output results to display in only a specific part of the page without refreshing the entire page. Ste ...

What is the best way to run a PHP program as a string within node.js?

From the frontend, I receive a PHP string that I need to execute and capture both the stdout and stderr. I attempted the following approach: const runner = require('child_process'); runner.exec('php ' + phpString, (err, stdout, stderr ...

The middleware in Expressjs is failing to override the response

My goal is to alter the response body before it's returned, and I attempted a solution from this answer Unfortunately, the solution didn't work as expected. Here's the code I used: app.js function modify(req, res, next) { var json = res ...

Showing changes in state in real-time using ReactJS: A quick guide

Hello, I am currently facing an issue while trying to add a comment and display it immediately on the DOM. Whenever I type any word in the form box, it does not appear in the box. Additionally, pressing the enter key does not trigger a POST request. Could ...

Adding a Timepicker to a Datepicker on a jsp webpage with javascript

I am working on a JSP page that includes a date picker. I want to enhance this datepicker by adding a start time and end time within the calendar itself. How can I achieve this? Additionally, I need to implement validation ensuring that the start time is a ...

Leverage Jasmine for testing a jQuery plugin

I'm currently utilizing the angular-minicolors library () within an angular controller: angular.element("myelement").minicolors({ position: 'top left', change: function() { //custom code to run upon color change } }) Wh ...

Is it advisable to run this function asynchronously on the server?

I have limited experience with node js, but I am working on a project similar to how Uber shows their cars in real time on a map. Currently, I have an SQL database containing data for numerous cars along with their GPS locations. The client sends their GP ...

Is there a way to identify and retrieve both the initial and final elements in React?

Having an issue with logging in and need to retrieve the first and last element: Below is my array of objects: 0: pointAmountMax: 99999 pointAmountMin: 1075 rateCode: ['INAINOW'] roomPoolCode: "ZZAO" [[Prototype]]: Object 1: pointAmoun ...