修改查询字符串以支持参数

时间:2018-02-23 17:49:51

标签: javascript node.js express

我有路线,

app.get("/employees", (req, res) => {
    data.getAllEmployees().then((data) => {
        res.json(data);
    }).catch(function(err) {
        console.log("An error was encountered: " + err);
    });
});

我需要支持/employees?status=value/employees?department=value

等查询

我在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);
        }
    });
}

如何在GET/employees路线中正确调用这些功能?我不知道我应该在哪里指定这些查询。我估计某处必须有IF/ELSE语句,但我的app.get路由指定app.get("/employees", ...。我在哪里添加IF/ELSE

1 个答案:

答案 0 :(得分:1)

我认为您需要为“employees”路径创建另一个处理程序,然后,您需要使用request.query检查查询字符串是否可用,该查询字符串返回一个带有来自查询字符串的params的对象,并且检查应从那里采取什么行动。

类似于:

app.get("/employees", (req, res) => {

    if(req.query.department)
         getEmployeesByStatus(req.query.department);
    else if(req.query.status)
        //and so on

});

另外,您可以设置一个名为filter的函数,例如,将req.query作为参数传递并相应地过滤。例如:

app.get("/employees", (req, res) => {

    if(!_.isEmpty(req.query))
        myService.filter(req.query);    
});