Start learning free

LESSON 66 OF 173 · BACKEND: APIS WITH A DATABASE

Rows as Objects in TypeScript

Practice

In the last lesson, the loop built a new Product for every row, with the very same keys and values the row already had. That copying isn't needed.

Every row the database hands over is an object whose keys are the column names. So you read row.price, never a position like row[2], and nothing breaks if someone changes the order of the columns in the SELECT. An array of rows is already an array of objects, ready to become JSON. For example, with a table books:

type Book = { title: string; year: number };

const library = new DatabaseSync("library.db");
const rows = library.prepare("SELECT title, year FROM books").all() as Book[];
const first = rows[0];
console.log(first.title);             // Dune
console.log(JSON.stringify(first));   // {"title":"Dune","year":1965}

Since the code doesn't depend on the order of the columns, the query can ask for all of them with SELECT *. The products' stock comes along too, which is why the Product type now has stock: number.

GET /           →  200  Welcome to the shop!
GET /products   →  200  [{"id": 1, "name": "Mug", "price": 12, "category": "kitchen", "stock": 10},
                         {"id": 2, "name": "Notebook", "price": 7, "category": "office", "stock": 0},
                         … 8 products in all …
                         {"id": 8, "name": "Gift card", "price": 50, "category": null, "stock": 999}]

Your task: write the /products route again, shorter: ask for every column of products and send the rows as they are, with no loop and no copying.


Assignment
Follow the Coding Tutorial to rewrite the /products route with SELECT * and no loop.


Hint
.all() already gives an array of objects, one for each row, with the column names as keys; as Product[] tells TypeScript so. res.json can send that array as it is.


STEP 1 OF 2
    Ctrl + Enter to check

    Db Row Dicts in TypeScript

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