Start learning free

LESSON 81 OF 173 · BACKEND: APIS WITH A DATABASE

A Small Query Helper in JavaScript

Practice

Look at your routes. Almost every one calls db.prepare(...), picks .all(...) or .get(...), and passes the values for the ?s. Every route types the same moves again. A helper is a small function that makes those moves once, so each route gets its rows in one line.

Default values: a parameter can have a default, written with = inside the parentheses. A call can leave that argument out, and the parameter takes its default. For example, here is a helper for error answers:

function sendError(res, message, status = 400) {
  res.status(status).json({ error: message });
}

sendError(res, "Price must be a number");   // status keeps its default, 400
sendError(res, "Order not found", 404);     // status given: 404

Your helper, query(sql, params = [], one = false), runs the SQL and answers an array of objects, one per row. With true for one it answers only the first row, or undefined when no row matched, as .get() did. In this lesson the check also counts how many times each request calls your helper (/check/calls), and it calls the helper itself (/check/helper, where undefined is shown as null, since JSON has no undefined):

GET /products?category=kitchen  →  200  {"products": [{"id": 1, "name": "Mug", …}, {"id": 6, "name": "Teapot", …}], "total": 2, "next_page": null}
GET /check/calls                →  200  {"query_calls": 1}
GET /products?name=Sofa         →  200  {"products": [], "total": 0, "next_page": null}
GET /products/3                 →  200  {"id": 3, "name": "Lamp", "price": 29, "category": "home", "stock": 1, "discount": 0}
GET /check/calls                →  200  {"query_calls": 1}
GET /products/99                →  404  {"error": "Product not found"}
GET /check/helper               →  200  {"many": [{"id": 2, "name": "Notebook"}, {"id": 4, "name": "Pen"}, {"id": 7, "name": "Stapler"}], "empty": [], "one": {"name": "Eva Rossi", "city": "Rome"}, "missing": null, "no_params": {"customers": 5}}

Your task: below migrate();, write the helper query. It runs the SQL with its params and answers an array of objects. With true for one, it answers the first row, or undefined. Then make the /products and /products/:productId routes get their rows from it, in one line each.


Assignment
Follow the Coding Tutorial to write the query helper and use it in the /products and /products/:productId routes.


Hint
Always read the whole array of rows first. Only then, if one is true, take out the first one. rows[0] of an empty array is undefined, the same value .get() gives for a missing row, so the routes' checks keep working. A route passes its params array as it is, with no ...: the helper spreads it.


STEP 1 OF 7
    Ctrl + Enter to check

    Db Query Helper in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free