Start learning free

LESSON 18 OF 173 · BACKEND: YOUR FIRST API

Filter with a Query String

Practice

A client often wants only part of the data, and it can say so in the URL. Everything after the ? is the query string, made of name=value pairs. In /products?max_price=10 the path is still /products, so the same route answers: max_price is the name and 10 is the value.

Express puts the query parameters in req.query. Everything in a URL is text, so wrap the value in Number when you want a number. When the parameter is missing, or isn't a number, you get NaN, and Number.isInteger tells you whether you have a whole number. Here is the idea on another route:

app.get("/double", (req: Request, res: Response) => {
  const number = Number(req.query.number);
  if (!Number.isInteger(number)) {
    return res.send("Send a whole number, like /double?number=4");
  }
  res.send(String(number * 2));
});

The filter is a loop you already know: start an empty array, go through the products, and push the ones that pass the check. An empty array doesn't show TypeScript what will go in it, so you give it the type Product[]. When there is no max_price, every product passes, so /products still answers the whole list. Your code must give:

GET /products?max_price=10     →  200  [{"id": 2, "name": "Notebook", …}, {"id": 4, "name": "Pen", …}]
GET /products?max_price=12     →  200  [{"id": 1, "name": "Mug", …}, {"id": 2, …}, {"id": 4, …}]
GET /products?max_price=1      →  200  []
GET /products                  →  200  all 4 products
GET /products?max_price=cheap  →  200  all 4 products
GET /products/3                →  200  {"id": 3, "name": "Lamp", "price": 29, "category": "home"}

Your task: change the /products route so it reads max_price from the query string into maxPrice and answers only the products that cost maxPrice or less, or every product when there is no limit.


Assignment
Follow the Coding Tutorial to read max_price and filter the list in the /products route.


Hint
Give the empty array its type: const result: Product[] = [];. Check !Number.isInteger(maxPrice) first, then ||, then compare the price with <=. Send result after the loop, not inside it.


STEP 1 OF 6
    Ctrl + Enter to check