0

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?

3
  • Are you asking how do you read the querystring parameters? Commented Feb 23, 2018 at 17:56
  • It seems so, I found this resource just now: stackoverflow.com/questions/6912584/… Commented Feb 23, 2018 at 18:06
  • But how do I modify my already-existing /employees route to support this functionality? Commented Feb 23, 2018 at 18:06

1 Answer 1

1

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);    
});
Sign up to request clarification or add additional context in comments.

3 Comments

My getEmployeesByManager() for reference: pastebin.com/4UDW5PLS
it says your link has been removed
Apologies: pastebin.com/0MGjDzAJ (disregard the err || on lines 25 and 34)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.