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

Exploring the dynamic world through HTML5 canvas and animated objects

Today I am exploring HTML 5 canvas and experimenting with moving 3 circles on the canvas. Based on my research, it looks like I need to continuously redraw the circles (perhaps every 60 milliseconds) and clear out the old circle before rendering the new on ...

Updating the TextField in React Material UI based on the Slider value without affecting the Slider

Is there a way to update the value of a TextField based on the slider, while still allowing manual input in the TextField? I want the TextField to reflect changes from the slider but not vice versa. I attempted making the TextField a controlled component ...

Node.js Sequelize QueryExplore the power of Sequelize in Node.js

I'm looking to filter the "incomers" based on age, but all I have in the table is their date of birth. I want to find people within a specific age range, how can I accomplish this? router.post('/', function (req, res, next) { let parame ...

A method to verify the presence of a specific element within a list using JavaScript

I'm trying to validate if the list retrieved from the application contains the expected element. Can you please review my code and let me know where I might be making a mistake? this.verifyOptionsInDropdown = async function(){ var optionList = a ...

How can I form a query in mongoose and express to reference an attribute?

Can someone help me with querying Notes using the author's reference id? I've tried, but it's not giving me the results I need. noteModel https://i.stack.imgur.com/H29v9.png noteController https://i.stack.imgur.com/LPe5M.png noteRoute htt ...

Apigee Usergrid: Absence of bulk delete feature

Currently, I am utilizing usergrid for storage in a customer project. The data is divided into two collections: carShowrooms and cars. Thus far, everything has been running smoothly. However, there arises a situation where I need to refresh the masterdata ...

The Angular directive alters the scope, however, the template continues to display the unchanged value

I am working with a directive that looks like this: .directive('myDirective', function() { return { restrict: 'AE', replace: true, templateUrl: '/myDirective.html?v=' + window.buildNumber, ...

Smart method for repositioning multiple elements on the display

Imagine we have multiple divs displayed on a screen: https://i.stack.imgur.com/jCtOj.png ...and our goal is to move them collectively, either to the left: https://i.stack.imgur.com/KBfXC.png ...or to the right: https://i.stack.imgur.com/c1cUw.png An ...

Converting an array into an object using Typescript and Angular

I have a service that connects to a backend API and receives data in the form of comma-separated lines of text. These lines represent attributes in a TypeScript class I've defined called TopTalker: export class TopTalker { constructor( pu ...

Generating a request to API using Express and create-react-app

I have my create-react-app running on localhost:3000 with a proxy set up in package.json to point to my server running at localhost:3001. { "name": "my-app", "version": "0.1.0", "private": true, "dependencies": { "axios": "^0.18.0", "react ...

Is there a way to set up a local npm module directory without using symlinks

Here is a breakdown of the file structure in a simple way. /my-module ..package.json /my-app ..package.json I am trying to have my-app install my-module locally. This is what I have attempted: "dependencies": { "myModule": "../my-module" } The opti ...

What is the best way to clear radio button selections in a form using reactjs?

I designed a survey form with 4 radio buttons for a single question. I also included buttons to submit the form and clear input fields. However, when I click on "Clear Input," the checked radio buttons do not get cleared. How can I achieve this using the r ...

jQuery custom slider with advanced previous and next navigation capability for jumping multiple steps

I am currently learning jQuery and programming in general. Instead of using a pre-built plug-in, I decided to create my own image slider/cycle from scratch to keep the code concise and improve my skills. My function goes through each li item, adding a &ap ...

Best practices for securing passwords using Chrome DevTools in React development

React developer tool inspector Is there a way to prevent password values from appearing in the inspector as a state when handling form submissions in ReactJS, especially when using Chrome's React developer tool? ...

Tips for transferring a boolean value to a generic parameter in Java?

Looking to pass a boolean value to the Generic type in order to be utilized within a condition. This is the generic type interface OptionTypeBase { [key: string]: any; } type OptionsType<OptionType extends OptionTypeBase> = ReadonlyArray<Opt ...

Incorporating Firebase Auth with a third-party database

I am currently incorporating Firebase for user authentication in a React/Node application. In addition to this, I also need to store additional user data in my own database. To achieve this, I am storing the Firebase uid on each user. I would appreciate an ...

Moving React API calls to separate Express backend server

I have a React site that utilizes the Google API to fetch calendar data. To ensure the security of my API key, I am planning to move the call to an Express backend server. The site is built using react-router-dom, and I am seeking guidance on the best appr ...

Exploring the capabilities of Express.JS for integrating with an external API

const express = require('express'); const app = express(); const path = require('path'); const api = require('./api'); app.get('/', function(req, res){ res.sendFile(path.join(__dirname + '/index.html')); ...

GraphQL is not capable of fetching data directly from a mysql database

Trying to incorporate GraphQL with MySQL in a Node.js Express server has been my recent challenge. Unfortunately, every time I execute my query, an error surfaces. Here is the specific error message: { "errors": [ { "message&quo ...

Using Node.js and the Jade templating engine, display the value of a passed variable

Asking such a basic question makes me feel guilty. app.get('/skumanagement/:id', function (req, res){ var options = req.params.id; // req.params.id = itemidx database.skuGetDetail(options, function (error, data){ winston.log('inf ...