A query string can carry several parameters, joined with &. In /products?category=office&max_price=5 the client asks for office products that cost 5 or less. The order of the parameters doesn't matter, because you read each one by its name.
Not every parameter is a number. A category is text, so you read it without Number; like any parameter, it is undefined when the URL leaves it out. Here is the idea on another route, with two optional parameters:
app.get("/greet", (req, res) => {
let name = req.query.name;
let times = Number(req.query.times);
if (name === undefined) {
name = "friend";
}
if (!Number.isInteger(times)) {
times = 1;
}
let text = "";
for (let i = 0; i < times; i++) {
text = text + "Hello, " + name + "! ";
}
res.send(text);
});
To combine two filters, put one check inside the other: a product is added only when it passes the price check and the category check. Each check lets every product through when its parameter is missing, so each filter also works alone. Your code must give:
GET /products?category=office → 200 [{"id": 2, "name": "Notebook", …}, {"id": 4, "name": "Pen", …}]
GET /products?category=office&max_price=5 → 200 [{"id": 4, "name": "Pen", …}]
GET /products?max_price=20&category=kitchen → 200 [{"id": 1, "name": "Mug", …}]
GET /products?category=garden → 200 []
GET /products?category=home&max_price=10 → 200 []
GET /products?max_price=10 → 200 [{"id": 2, "name": "Notebook", …}, {"id": 4, "name": "Pen", …}]
GET /products → 200 all 4 products
Your task: read a second query parameter, category, and change the loop in the /products route so a product is pushed to result only when it passes both filters. Either filter can be left out.
Assignment
Follow the Coding Tutorial to read category and add the category check inside the price check.
Hint
The category check has the same shape as the price check: the "no filter" test first (category === undefined), then ||, then a comparison with ===. The result.push(product); line goes one level deeper, inside the new if.
Free plan: 30 tutor messages. PRO is unlimited.
