All posts by admin

DNY node api (1 – setup)

  • download source
  • unzip the source code
  • go into directory and type npm install to install the modules
  • Once the packages are installed, run it npm run dev
  • Go to localhost:8080, then check terminal for logs

Set up

Open terminal, navigate to ‘Desktop’

mkdir dnyNodeAPI

cd dnyNodeAPI

npm init

press enter for all selections

npm install express

Then check your node_modules folder and you’ll see whole of packages being installed.

In our package.json file, change ‘main’: ‘index.js’ to ‘main’: ‘app.js’

Create file ‘app.js’:

in your terminal, if you went node app.js, it will run the server on port 8080.

But whenever we make a code change, we have to restart the server and this becomes cumbersome. So let’s install nodemon.

npm i nodemon

Then in your package.json:

Now, in your terminal, Ctrl+C to get out of whatever is running.
Then npm run dev.
It will run the command as specified in our package.json and we get the server running with constant updates.

Putting in Routes

routes/posts.js

app.js

Install Middleware

npm i morgan

Installing Database

Create account in mLab, and create a database. Select default for everything, i.e AWS, server at Europe, and create submit. Then ‘create db user’, and create a username and pwd for the db’s user.

Then, in your project, create a file .env:

.env

npm i dotenv

npm i mongoose

app.js

post.js

post.js

Forkify Web app (part 5 – Displaying the recipe view)

forkify-part5 source

install npm modules: npm install
run web app: open command line and type ‘npm run start’

We implement our files according to MVC paradigm:

We first create a recipe view file

src/js/views/recipeViews.js

We use fractional module to calculate integer display of fractions: npm install fractional –save

This is so that we can apply the effects to ingredient.count and ingredient.unit

renderRecipe is used in our controller (index.js) to display html when we click on an item. We use the html from the template, and then add data to it via the recipe object.

As you can see, when we fetched data for the recipe successfully, we then render the recipe.
src/js/index.js

src/js/models/Recipes.js

Forkify Web app (part 4 – Building the recipe model)

forkify-Recipes

We create the model part, and then get the controller to use it:

First create the Recipe where we fetch the data from the backend. We dynamically assign properties title, author, image…etc to the data that we get back.

What you’ll notice is that the ingredients we get back are whole words. What we want to do is to parse ingredients words into a short-handed format. But in the end, we also want to put them into an array of objects. That way, we can pass the measurement, unit, and text.

src/js/Model/Recipe.js

We do the same thing for Recipe as we did for Search.
We get data from server. Parse it, and do some processing on it.

We also implement functionality for ‘load’ event.

src/js/index.js

Make sure we render the results from our fetch operation. We put the result into a list on the left. The result is basically an array of recipes.

src/js/views/searchView.js

Forkify Web app (part 3 – loader and pagination)

Loader

Loader is about using the CSS that is provided to you. We copy and paste the html into our js file. Since the style file is present, it will animate the loader.
We then call the renderLoader js function in the controller.

src/js/views/base.js

When the data fetched is finished, we then call the removeLoader. We basically find the element with the class name ‘.loader’ and then go up to its parent, and call removeChild on it.

src/js/index.js

Now just use them right before and after the fetching of your data result.

Pagination

Pagination is part of rendering the results that we fetched from the backend.

src/js/index.js

We need to modify our renderResults functionality. Before, we just a simple forEach that renders all results. Now we have to be more selective.

We need to know two things, the page we’re on and the number of results per page.

We calculate for start and end so that we can selectively extract those data to be displayed.

If we were to start on say page 1, and 10 results per page we need 0-9.
if we start on page 2, 10 – 19…
…etc.

for ‘start’, we just do: (page-1) * resPerPage
for ‘end’, we simply do: page * resPerPage

Notice we get 0, 10
10 – 20
20 – 30…

We then use slice to get the start/end – 1

so slice(0,10) means to get elements from index 0 to 9
slice (10, 20) means to get elements from index 10 to 19
…etc

which is exactly how we want to render our recipes.

src/js/views/searchView.js

Forkify Web app (part 2 – fetching data and presenting it)

forkify-part2 download

The url to fetch data is https://forkify-api.herokuapp.com/api

We get GET data like so:
https://forkify-api.herokuapp.com/api/search?q=pizza
https://forkify-api.herokuapp.com/api//get?rId=47746

src/js/models/Search.js

We use Axios library for data fetching:

1) We await the Promise object to be done
2) then we extract the status to make sure its all OK
3) we finally log the result

The default http grammar is GET. axios(…) automatically use this if we only give it an url.

We will be using this Search’s getResults in the view. However, we need to set up utility functionality first.

src/js/views/base.js

This is just a way to get the DOM element of a certain class or id. Typically, we use document.querySelector, and then we store it in a literal object like so:

Once we get the DOM element, we can use textContent, innerText, innerHTML to get the content.

src/js/views/searchView.js

The whole point to this searchView is to create a renderResults function that our controller can use.
We implement a renderResults function that outputs HTML for rending the content. We render the content. It takes in an recipe object and then uses the object’s properties along with the HTML. We also shorten the incoming titles to the length we want by using reduce.

Other purpose is to clear textfields and such:

– clearResults
– clearInputs

We first import the base. Then we simply access value, or innerHTML, according to what we want. From there we can clear certain HTML controls.

for all elements in array A, see if any of it matches in array B.

Given an array of target data…

We want to see if an array of ids can be found in that target data.

Say a user selects these ids:

We want to see if the selected ids can be found in the target array:

Thus, you see that it looks through the target array on all the selected ids. If the ids match, then it saves it into an array and returns it to you:


output:

(2) [{…}, {…}]
0: {id: 136, providerName: “ATT”, providerID: 36, active: true}
1: {id: 138, providerName: “Bell”, providerID: 40, active: false}
length: 2
__proto__: Array(0)

You can also do it the other way, around, but it is not intuitive. You get every single target item and see if it exists in the toFind array.

It doesn’t fare very well as it forces you to go through every target item. If that target item is not found, undefined is returned and it sticks it into your result array. Thus, that is why we must use _.remove to removes those undefined. This is not the way to go.

forEach vs map

ref – https://programmingwithmosh.com/javascript/whats-the-difference-between-foreach-and-map-in-javascript/

Array.prototype.forEach

Anytime you want to iterate through the items in an array, the first thing that comes to our mind in any programming language is the for loop. forEach() in JavaScript is an interesting alternative to the regular for loops.
The forEach() iterates through the elements in the array. It calls a provided callback function once for each element in the array in ascending order.
The callback function accepts three arguments:
value of the element
index of the element
array object
Let’s take a look at an example to see how forEach() works.

Array.prototype.map

The map() method creates a new array with the results of calling a provided function on every element in the calling array. map() calls a provided callback function once for each element in an array, in order, and constructs a new array from the results.

The callback accepts three arguments:

  • value of the element
  • index of the element
  • array object

You may have used the map() function before. It qualifies as a higher-order function, because it takes in a callback function as an input argument.

In the example above, we have an array of numbers and creating a new array using the map(). The map() takes a function as an argument. The argument item within the function will automatically be assigned from each element of the array as map() loops through the original array.

What is the difference?

If you notice closely, although they look very similar there is a fundamental difference between forEach() and map() functions.

  • forEach() changes the original array
  • whereas map() returns a new array, without mutating the original array.

So which one should you pick? It depends on what you are trying to do with the array.
Note: I always prefer to use map() over forEach().
If you are looking to make changes to the array, map() is preferable. map() ensures that it doesn’t change/mutate the original array, and returns a new array instead.
forEach() is used when you want to iterate through the array and allows a callback function that mutates the original array unlike map(). If you are not looking to transform the array items, but just need to iterate through it and print them or do other actions with them, then forEach() could can be used.

Which one is faster

?
So which one is faster? There seems to be a very small difference between forEach() and map() with respect to speed. map() is faster, but these are so miniscule that it shouldn’t affect your application’s performance significantly. You can almost always use map() and other array methods like filter() and reduce() instead of using forEac

Which is better?

The original array that the map() function iterates through is immutable. This means it cannot be changed, and the map() has to return a new array with the updated items. This is a big benefit since your original array is guaranteed to remain the same and not change after the iteration. Incase your code needs the original array elsewhere, map() will be the best option.
h().

Forkify Web app (part 1 – setting up your environment)

download the forkify starter files.

Install Node

download node via command line or an executable/dmg file from Node’s website.

check if node is installed correctly:

node -v

Go into the forkify folder and you’ll see folders:
– dist
– src

This is where our source files are.

Go ahead and make this into a project: npm init

Go ahead and fill it in. The output should look something like this:


bogon:starter$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See npm help json for definitive documentation on these fields
and exactly what they do.

Use npm install afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (starter) forkify
version: (1.0.0)
description: forkify project
entry point: (index.js)
test command:
git repository:
keywords:
author: ricky t
license: (ISC)
About to write to /Users/*****/Desktop/complete-javascript-course/9-forkify/starter/package.json:

{
"name": "forkify",
"version": "1.0.0",
"description": "forkify project",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "ricky t",
"license": "ISC"
}

Is this OK? (yes) yes

Once you’re done, go back to the directory, and you’ll see a package.json.

Now let’s install webpack: npm install webpack –save-dev

It will save webpack as a development dependency. Now go back and look at your packpage.json, you’ll see that webpack has been added.

Your packpage.json should look something like this:

Now let’s install jQuery: npm install jquery –save

It will save jQuery not as a dev dependency, but as dependency.
You can also uninstall jQuery like so: npm uninstall jQuery –save

Let’s install local web server: npm install live-server –global

If you get an error, make sure you use ‘sudo’ to give permission:

sudo npm install live-server –global

when you install globally, you can run it anywhere by typing:
live-server

In main directory, create file webpack.config.js:

The entry point is where we want to start running the project. Create a file: /src/js/index.js

Basically, we have a value/component in test.js, and we export it to index.js.

Create file: /src/js/test.js

The output means that after we package all of our js files together, we want to export the resulting file into ‘dist/js’ with the name ‘bundle.js’.

This bundle.js will have all of our code, which can be easily run in the browser. It literally packs everything for the web to run. If you were to look inside the bundle.js file, you’ll see our js code of test and index.

Install webpack client: npm install webpack-cli –save-dev

Another thing you should look at is change your package.json when you run the scripts. Make sure we’re running the webpack conversion using development or production.

Your package.json should look like this:

Now, when you go: npm dev run, webpack should convert our web files into a bundle.js.


Built at: 12/15/2019 6:23:26 PM
Asset Size Chunks Chunk Names
bundle.js 1020 bytes 0 [emitted] main
Entrypoint main = bundle.js
[0] ./src/js/index.js + 1 modules 143 bytes {0} [built]
| ./src/js/index.js 92 bytes [built]
| ./src/js/test.js 51 bytes [built]

However, we need to put this bundle into an html file so we can see it:

create index.html in distr/

Then in index.html, type ‘!’, then press ‘tab’.

you’ll get the typical html template. Then in body tag, put:

your index.html should look like this:

Open the index html file dist/index.html and when you see the html load, it will also load the bundle.js file. You’ll see the test.js and index.js print out the results.Make sure your web server is running by typing live-server.

Development Server

Let’s install this so we don’t have to run webpack manually everytime.

package.json

webpack.config.js

now run:

npm run start

you’ll get a browser up and running with the code. Now, when you make changes to your code, you will get live compiling of the files. You don’t need to go to your terminal and run “npm run dev” every single time. Every save you make will automatically compile and rerun the server.

That you can go straight to the webpage to see the updates.

Now we try to run it with the given css from the css folder

remove index.html in distr/js

make sure to install html-webpack-plugin:

webpack.config.js

we alter our webpack.config.js like so:

however, u won’t see it because it’s not saving it on disk.
It simply injects the script.

If you want to save it to disk, run:

npm run dev

At this point, your files should look something like this:

forkify_lesson_7

Installing Babel

lesson8 – source

Babel is a JS compiler, in order to use next generation JS.

npm install babel-core babel-preset-env babel-loader –save-dev

check out package.json file to make sure you’ve installed.

Loaders allow us to import all different kind of files and process them. Convert es6 to es5. Or convert less to sass.

We need to babel loader to do the conversion.
There are certain rules to do these loading. So in our webpack.config.js, we need to define rules. It is an array.