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
}
}