Question
What would be a real-life example of this exercise?
Answer
I know sometimes console logging can feel pointless, but logging data gets to be helpful when we are not certain how does it look when it comes from the database, or how it will be arranged after our query, but usually, we would take advantage of the callback function to assign the rows to a variable for example. Let’s say that we have a coffee shop, and our whole system (because we are awesome like that) has been built by us, we have the stock in one table in a database, and if we wanted to display all the available teas we have in stock today for people to order, so, we have our function that displays the teas:
// let's say beverages so we can use it in other drinks
const displayBeverages = (bevArr) => {
if(bevArr){ //checking that the array exists
for( bev of bevArr){ //looping throug the array to access each object
let eachDiv = document.createElement('div');
let nameTag = document.createElement('h3');
let infoTag = document.createElement('p');
let moneyTag = document.createElement('p');
let img = document.createElement('img');
nameTag.innnerHTML = bev.name;
infoTag.innerHTML = bev.info;
moneyTag.innerHTML = bev.price;
img.src = bev.img;
eachDiv.appendChild(img);
eachDiv.appendChild(nameTag);
eachDiv.appendChild(infoTag);
eachDiv.appendChild(moneyTag);
body.appendChild(eachDiv); //by all purpose of the example body
//is a variable that contains the body element linked to it
//which should be displayed on localhost on the coffee
//shop's display's browser
}
}
}
Now that we have that, we can call our db:
const db = require('./db');
...
...
db.all(`SELECT * FROM inventory WHERE type = 'beverage' AND kind = 'tea' AND available = true;`, (err, rows) => {
if(err){
console.log(err);
} else {
displayBeverages(rows); //we call our function passing the tea rows
}
});
Now we can use db.get like in the challenge to display the tea of the month based on how much there is in stock, for example, if the quantity is greater than 500 ct o at least no less than 300;
db.get(`SELECT * FROM inventory WHERE type = 'beverage' AND kind = 'tea' AND available = true AND quantity > 500 OR NOT quantity < 300;`, (err, row) => {
let div = document.createElement('div');
let headTag = document.createElement('h1');
let nameTag = document.createElement('h3');
let infoTag = document.createElement('p');
let moneyTag = document.createElement('p');
let img = document.createElement('img');
headTag.innnerHTML = 'Tea of the month';
nameTag.innnerHTML = bev.name;
infoTag.innerHTML = bev.info;
moneyTag.innerHTML = bev.price;
img.src = bev.img;
div.appendChild(headTag);
div.appendChild(img);
div.appendChild(nameTag);
div.appendChild(infoTag);
div.appendChild(moneyTag);
body.appendChild(div);
})
That is an example of how we could use SQLite in a simple JavaScript + HTML project