Reputation:
I have the route,
app.get("/employees", (req, res) => {
data.getAllEmployees().then((data) => {
res.json(data);
}).catch(function(err) {
console.log("An error was encountered: " + err);
});
});
And I need to support queries such as /employees?status=value
and /employees?department=value
I've created these functions in data-service.js
module.exports.getEmployeesByStatus = function(status) {
return new Promise((resolve, reject) => {
if (employees.length == 0) {
reject("No results");
} else {
resolve(employees.status == status);
}
});
}
module.exports.getEmployeesByDepartment = function(department) {
return new Promise((resolve, reject) => {
if (employees.length == 0) {
reject("No results");
} else {
resolve(employees.department == department);
}
});
}
How do I properly call these functions from within my GET/employees
route? Im not sure where I should be specifying those queries. I reckon there must be an IF/ELSE
statement somewhere, but my app.get
route specifies app.get("/employees", ...
. Where do I add the IF/ELSE
?
Upvotes: 0
Views: 82
Reputation: 361
I think you need to create another handler for the "employees" path and then, you would need to check if a query string is available by using request.query, that returns an object with params from query string, and check what action should be taken from there.
something similar to:
app.get("/employees", (req, res) => {
if(req.query.department)
getEmployeesByStatus(req.query.department);
else if(req.query.status)
//and so on
});
also, you could set up a function called filter for instance, pass req.query as parameter and filter accordingly.. something like:
app.get("/employees", (req, res) => {
if(!_.isEmpty(req.query))
myService.filter(req.query);
});
Upvotes: 1