Start learning free

LESSON 67 OF 173 · BACKEND: APIS WITH A DATABASE

One Product from the Database

Practice

To read one product, a client puts its id in the path: /products/3. A route written as /products/:productId matches that piece of the path, and Express keeps it in req.params.productId as a string: "3", not 3. Number(...) turns it into a number.

This time the database does the searching, with a WHERE condition. You never paste the value into the SQL text: you write a placeholder, ?, and pass the value as an argument when you run the query. An id matches at most one row, so .get(...) gives that row, or undefined when the query found nothing. For example, with a table books:

const row = db.prepare("SELECT * FROM books WHERE year = ?").get(1965);
if (row === undefined) {
  console.log("No book from 1965");
}

The database puts the argument in place of the ?. When no row matches, the client asked for something that doesn't exist, so the answer is 404 with an error message.

GET /products/3   →  200  {"id": 3, "name": "Lamp", "price": 29, "category": "home", "stock": 1}
GET /products/8   →  200  {"id": 8, "name": "Gift card", "price": 50, "category": null, "stock": 999}
GET /products/99  →  404  {"error": "Product not found"}
GET /products/0   →  404  {"error": "Product not found"}

Your task: add GET /products/:productId, which asks the database for that product with a placeholder and answers it as JSON, or {"error": "Product not found"} with the status 404.


Assignment
Follow the Coding Tutorial to add the route that answers one product.


Hint
.get(...) gives undefined when the query finds nothing. Check for it before you send the row, and start the 404 answer with return so the function stops there.


STEP 1 OF 6
    Ctrl + Enter to check