A shop's front page often shows a menu of its categories. The shop keeps no list of them: each product only knows its own category. So your API builds the list from the products, every time someone asks.
The list must be distinct: two products are in "office", but the menu shows it once. Before adding a value to an array, includes tells you whether the array already holds it. Then sort() puts an array of strings in alphabetical order, with no compare function. The same idea on an array of colors, typed string[] since each color is text:
const colors: string[] = [];
for (const color of ["red", "blue", "red"]) {
if (!colors.includes(color)) {
colors.push(color);
}
}
colors.sort();
console.log(colors); // [ 'blue', 'red' ]
The list is built from the products on every request, so it always follows them. A product in a new category adds that category, and deleting the only product of a category removes it. Your code must answer these requests, in this order:
GET /categories → 200 ["home", "kitchen", "office"]
POST /products {"name": "Chair", "price": 45, "category": "furniture"} → 201 {"id": 5, "name": "Chair", …}
POST /products {"name": "Stapler", "price": 9, "category": "office"} → 201 {"id": 6, "name": "Stapler", …}
GET /categories → 200 ["furniture", "home", "kitchen", "office"]
DELETE /products/3 → 204
GET /categories → 200 ["furniture", "kitchen", "office"]
Your task: add a route for GET /categories that answers the distinct categories of the products, in alphabetical order, as a JSON list.
Assignment
Follow the Coding Tutorial to build the GET /categories route: an empty string[] array, a loop over products, an includes check, and a sorted answer.
Hint
Add the route above the last line, app.use(notFound);. Push a category only when the array does not include it yet: !categories.includes(...). An array of strings needs no compare function: categories.sort() puts it in alphabetical order.
Free plan: 30 tutor messages. PRO is unlimited.
