Categories
backend javascript nodejs

How Authentication works in REST APIs ?

Hey everyone 👋🏻,

In this article, let us learn about more about REST APIs. This is the second article on the topic REST API. The first article on this topic can be read by clicking on the below link :

https://dev.to/thenerdydev/what-is-a-rest-api-288l

How authentication works in REST API ?

Alt Text

So we again have our client and server. The client in order to authenticate needs to first send the authentication data (credentials), so basically the email and the password. This password is then compared with the password that is kept in the database before granting the access to the user. Now if you are working with an Express based server, then you must have used a package called bcryptjs that helps with all of this stuff. In traditional applications, we used to check data on the server and if the data was valid and if it was valid, only then a session used to get established.

Why no sessions any more ?

Well, there is a reason for this. We do not use session any more because REST APIs are stateless. The client and the server do not share the same connection history which means that both are totally decoupled from each other. Here we don’t care about the clients. Every request is treated as standalone which means that every request should have all the data it needs to authenticate itself. With session, the server has to store the information about the client that it is authenticated and this is not how REST APIs work. Therefore this approach is not what we use nowadays.

Now here in this approach we will still check the validity of the email and password combination on the server. But contrary to what we do in case of sessions, here we return a token to the client and that token is something that gets generated on the server. This token would hold some information that can be validated by the server and this token will then be stored in the client so basically in the local storage of the browser. The client can then attach this token to every subsequent request it sents to the server. Stored token is sent to authorize subsequent request and targets the resource on the server which requires authentication.
That token can only be validated by the server who created that token.

Now what if you try to change or fake the token ?

If you try to change or fake the token on the client side, then that will be detected because the server uses a special algorithm to generate the token and you simply cannot fake it since the algorithm that uses to generate the private key is not known to you.

What’s that token ?

JSON data + Signature => => => JSON web token (JWT)

This JWT (json web token) is what gets returned to the client and the signature can only be verified by the server. So you cannot edit or tamper the token at the client because the server will detect and will invalidate the token. This is how authentication is done in REST APIs.
So in essence, we have a token which can be checked by the server but need not be stored by the server.

So generating the token is one thing, the server sends the token. Next we need to make sure that we can send the token back to the server/backend REST API and then we check for the existence and the validity of token before we allow the request to continue.

If no token is attached to the incoming request, we should simply block access to those routes which do require some form of proven authentication. Remember, it is for the private routes that you do need a token attached to the request so that the user can access them.

Now to basically append the token with request you could attach the token with query params of the url or you could send them inside the body of NON-GET requests. But the best solution would be to send the token along with the headers. The benefit of this is that this would keep your URL clean. Also headers makes a lot of sense for the meta information which our token is in the end.

Now with Express.js, we use the jsonwebtoken package for decoding and verifying our token on the backend.

We use jsonwebtoken.verify to both encode and verify the token on the backend. We can also use jsonwebtoken.decode at the server side as well but then it won’t verify the token there.

Wrap up

The REST API server doesn’t care about the client. Requests are handled in isolation which means that every request is treated as if it arrived for the first time. So here we don’t use sessions. The REST APIs does not store any sessions. They don’t store any client data.

Due to no involvement of sessions in REST APIs, authentication works a bit differently here. Each request needs to be able to send some data that proves the authenticity of that request. JSON Web Tokens are a common way of storing authentication information on the client and proving the authentication status.

JWTs are signed by the server and can only be validated by the server.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text
Categories
backend database mongodb

Running Geospatial Queries in MongoDB

Hey everyone 👋🏻,

In this article, let us learn about Running Geospatial Queries in MongoDB .

Geospatial Queries – Finding Places

Geospatial Queries are an interesting thing in MongoDB. You can fire queries not just for text, boolean, number, dates as condition but you can also create queries for locations like :

Find me all the restaurants within a radius of 2km.

Find me all the hospitals that near to this specific place

Image description

Running Geo Queries

Let us try to find all the places that are near my current location. So for this, let’s run this query. Make sure to use the latitude and longitude of your location before you fire the below query :

Image description

And here the $geoNear is the behind the scenes name of our $near query. For this we will need the geospatial index for this query to run.
Not all the geospatial queries require the index but they all will somehow benefit from having such an index.

To add such an index we can use the createIndex method on the
collection.

Image description

And if we repeat the same query, it should now succeed.

Image description

Now the question that must come in our mind is that how is near defined near, meaning that relative to what it is near. It does not make sense unless we restrict it.

We can also define $maxDistance which is a value present
in metres here. We can also define the $minDistance which is also a value define in metres

Let us now write a query to find all places that are near to us in a certain radius distance.

Find out all places that are near to us in a certain radius distance

Image description
This answers our first question regarding which points are near to our current location. Now this area could either be in form of a sphere, polygon etc., let us say we want to find out which points are inside of that area ?

This is another typical question that we often encounter and in order to answer this let us add more points to our database.
Let us add three more places :

Image description
Image description
Image description
Image description

Now let us run a query to find all the places that lie inside a certain area :

For finding such places, go to Google Maps :
Inside the Google Maps Section

  1. Go to Your Places tab.
  2. Create a new map there.
  3. Let us draw a polygon around our location.

$geoWithin will help us to find all the elements within a certain shape or certain object typically like a polygon.
$geoWithin takes a document as a value and here we can add a geometry object which is just the GeoJSON Object

Store all the four coordinates inside the points
p1, p2, p3, p4

Image description
Finding out if a user is inside a specific area. This can also be done using geospatial queries.

Let us see how we can find places within a certain area :

Image description

This is what we get as a result :

Image description

The $near method gives us the list of the places in the sorted order whereas the $geoWithin method will give us the list of the places in the unsorted order but we can sort them using the sort method on the records that we get back.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text
Categories
frontend javascript reactjs

When to use the useRef hook ?

Hey everyone 👋🏻,

In this article, let us learn about a very special React Hook called as the useRef hook and understand how and when to use it.

What is the useRef hook ?

useRef hook is something that I briefly discussed in one of my articles where I described useRef hook as something equivalent to

Removing the state updating function from the useState, so basically just extracting the piece of state and take away the ability of state updation. This is something that will be equivalent to the useRef hook. I also discussed in that article that both the ref and state values persists across renders, so it is not the case that on every subsequent re-render they get set back to some default. So do make a note of the above points.

useRef is a React Hook which accepts a single argument as the initial default value and gives us something called as a ref. A ref is kind of an object that has a property called as current.

Let us see an example :

function SomeComponent() { 

    const usernameRef = React.useRef(''); 
    const handleSomething = () => { 
       console.log(usernameRef.currrent); 
       usernameRef.current = someOtherValue; 
    }
}

Now the things to note here is that usernameRef.current is used to access the value of the ref and if we want to update the ref value, then we can simply do so by setting usernameRef.current to a value of our choice.

To know more about refs, check my existing article on useRef hook. Here is the link for the same :

Image description

https://dev.to/thenerdydev/useref-hook-useref-vs-usestate-3i7k

In the above article, I have also taken some examples where I have demonstrated the usage of the useRef hook, we have discussed :

1. Ref Example – 1 (An Interval Timer)
2. Ref Example – 2 (Working with DOM using refs)
3. The third thing that we discussed in that article was :

useRef just like useState persists a value across renders but unlike useState it does not trigger a re-render of the component.

So in essence,

useRef = useState – state updating function

If you don’t know about the useState, no worries. You can learn about the same in this article :

https://dev.to/thenerdydev/react-hooks-demystifying-the-usestate-hook-in-under-10-minutes-examples-video-29ab

Let’s sum up what we learnt :

A ref is a plain JavaScript Object
{ current: <some_value> }

If you want to create a ref with the current value as null, then you can also make use of the createRef method,
React.createRef()

This gives us :
{ current: null }

Next, useRef(someInitialValue) also gives us a ref { current: someInitialValue }. The interesting thing about useRef is that it memoizes this ref so that it stays persistent across multiple renders of the component.

Another point to make a note of is that :

useRef(null) is basically equivalent to useState(React.createRef())[0]
But this kind of abuses the functionality.

Lastly, we learnt that useState causes a re-render in contrast to useRef. The state and the ref values (both) persist across re-renders.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Categories
reactjs

Memoizing with React.useMemo

Hey everyone 👋🏻,

In this article, let us learn about a very special React Hook called as the useMemo hook and understand how and when to use it.

What is the useMemo hook ?

useMemo is a React Hook that was introduced to memoize expensive computations. Let us understand some basics about this. In order to understand the useMemo hook, let us understand its syntax:

const memoResult = useMemo(someFunction, dependencies);

So what happens with useMemo is that when the component renders for the first time, the useMemo hook invokes the someFunction (it could be any function, I am just calling it as someFunction) and memoizes the value that it computes for us and then it returns the result back to the component. Now the interesting thing here is that if during the subsequent renders, the list of dependencies that we specify do NOT change, then in that case useMemo will not invoke the someFunction but instead it will return the memoized value. Contrary to this, if the list of dependencies experience a change during subsequent renders, then useMemo will invoke the someFunction, memoize the result that it gets as a result of computation and then return it back to the component. So in essence, this is what happens in the useMemo hook.

Now let us see a simple example :

Let us say we have a component that deals with computation of factorial of a number, let’s call the component as FactorialResult. Now what this component does is that it computes the factorial of a number that is supplied into the input field by the user. Let us see the basic code for same :

import React from 'react' 
function computeFactorial(num) { 
   if(num == 0) { 
       return 1;
   }
   return num * computeFactorial(num - 1)
}
const FactorialResult = () => { 
  const [num, setNum] = React.useState(0); 
  const factorial = computeFactorial(num); 

  const handleChange = event => { 
         setNum(+event.target.value); 
  }
  return ( 
    <div>
      Factorial of 
      <input type="number" 
       value={num} 
       onChange={handleChange} />
      is {factorial}
    </div>

   );
}

Now every time, you change the input value, the factorial is re-calculated as a result of re-render.
Now how can we memoize this factorial calculation which itself is an expensive operation ? We want to memoize the factorial computation when the component re-renders. So for this we can make use of the useMemo hook. Let us make small changes in our code and memoize this factorial calculation. So here is the new code for the same component :

import React from 'react' 
function computeFactorial(num) { 
   if(num == 0) { 
       return 1;
   }
   return num * computeFactorial(num - 1)
}
const FactorialResult = () => { 
  const [num, setNum] = React.useState(0); 
  const factorial = React.useMemo(() => {
      computeFactorial(num)
   },[num]); 

  const handleChange = event => { 
         setNum(+event.target.value); 
  }
  return ( 
    <div>
      Factorial of 
      <input type="number" 
       value={num} 
       onChange={handleChange} />
      is {factorial}
    </div>

   );
}

Now every time you change the value of the num, the computeFactorial will get invoked but only if the num has changed. If num does not change on the re-render, then it will return the memoized result for its factorial and will not make that extra computeFactorial call. I hope that makes perfect sense.

Let’s see one more example to make the useMemo hook extremely clear.

Let us say we want to return the full name of a person, so for this let us say we have a function in some component that gives us the full name:

const fullName = React.useMemo(() => {
   return firstName + " " + lastName
},[firstName, lastName])

In above code, if the firstName or lastName change, then our fullName function will get re-invoked because we have specified firstName and lastName as dependencies. Please note : functions themselves usually don’t need to be re-computed, and their dependencies are mostly closure values that may change.

const fullName = React.useCallback(() => {
     return firstName + " " + lastName
}, [firstName, lastName]);

Now for above piece of code when firstName or lastName change, we don’t need a separate instance of the function on each re-render of the component, but we need exact the one and same instance of the function so that it has up to date values in the closure.

So this is it for this article. Thanks for reading.

Categories
reactjs

🐱‍👤When to use the useCallback hook ?

Hey everyone 👋🏻,

In this article, let us learn about a very special React Hook called as the useCallback hook and understand how and when to use it.

What is the useCallback hook ?

useCallback is a React Hook which was introduced to prevent re-creation of a specific function in case our component re-renders.
It does so by memoizing the callback function that this hook takes and this memoized version will only change when one of the inputs has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.

So typically we should make use of the useCallback hook in one of the following cases :

  1. If you are passing the function on to child component as props and the child component doesn’t often need re-rendering except when a certain prop change then useCallback might prevent certain re-renders.
  2. You are specifying a function as a dependency to useEffect. In such a case you must ensure that the function is not recreated on every render or the useEffect will be triggered on every render.

So in the essence, the decision to make use of the useCallback must be made judiciously instead of blindly since you might just overdo the advantage offered by useCallback and end up degrading the performance since useCallback will also memoize the functions and a frequently changing dependency might anyways need to recreate the function.

If the dependencies of the useCallback change, only then the function will get recreated otherwise it will use the exact one and the same instance of that function across the re-renders.

Example :

In JavaScript, we know that when a function gets executed we know that each and every thing (variables functions, objects etc) that is present within the function gets re-created into the memory. So this happens on each execution of the function. Now for a function we might not want it to get re-created on each re-render of the component and in turn we may want to use the exact same instance for that specific function in each of our renders. We might only want to re-create the function when a specific dependency which that function uses gets changed and NOT otherwise. This is something that we can achieve by making use of the useCallback hook.

Let’s see a simple Counter component.
Here we have a single piece of state which we call as counter and we have a corresponding state updating function for it which we named as setCounter. The initial value for counter is given as 0.
Next we have a handleIncrement counter function and all it does is that it increments the value of counter by 1.

const Counter = () => {
  const [counter, setCounter] = useState(0);

  const handleIncrement = () => {
    setCounter(counter + 1);
  }

  return <div>
    Counter:{counter}<br/>
    <button onClick={handleIncrement}>Increment</button>
  </div>
}

Now the interesting thing to note here is that the handleIncrement function will get re-created on each render of the component. This means that each time the component re-renders, handleIncrement function will get re-created at a separate spot in memory. And due to this reason, when React tries to make a referential equality comparison, it finds a change because of the re-creation of the handleIncrement function.

Now what if we wrap this with the useCallback hook ?

What the useCallback does is that it internally caches the first created version of the function and returns it to the caller if the listed dependencies haven’t changed. In case the listed dependencies does change, then it automatically gives us a new instance of that function.
So if we introduce the useCallback hook into our above code, then our code should look something like this :

const Counter = () => {
  const [counter, setCounter] = useState(0);

  const handleIncrement = React.useCallback(() => {
    setCounter(counter + 1);
  }, [])

  return <div>
    Counter:{counter}<br/>
    <button onClick={handleIncrement }>Increment</button>
  </div>
}

Now with the above code, what React will do is that it will cache the handleIncrement function internally and will make sure to return the exact same instance of the function in case no external dependencies of the useCallback have changed. In case, the external dependencies do change, then in that case a brand new instance of the handleIncrement function will get created for us. For our case, there are no external dependencies for the handleIncrement function.

Now caching the function internally by using the useCallback has its own cons. The cached instance of the function call will not have direct access to the variables of our current function call. Instead of that it will have visibility of the variables that were introduced in the initial closure call where the stored function was created. So in essence, this means that our call will not work for the updated variables. Therefore, we need to specify those variables or dependencies of the function that can change. The list of dependencies is to be passed as the second argument of the useCallback. In our example, we need to tell to useCallback function that we need a fresh version of our counter variable on each call. If we don’t do that, then the counter variable after the call will always be 1 and this is what comes from the original value 0 plus 1.

const Counter = () => {
  const [counter, setCounter] = useState(0);

  const handleIncrement = React.useCallback(() => {
    setCounter(counter + 1);
  }, [counter])

  return <div>
    Counter:{counter}<br/>
    <button onClick={handleIncrement}>Increment</button>
  </div>
}

The above version of code will not re-render on every call.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
frontend javascript

5 Frontend Development Trends to follow in 2022

Hey everyone 👋🏻,

In this article, let us discuss about Top 5 Frontend Development Trends to follow in 2022

1. JavaScript

JavaScript is one of the most popular programming languages that you can learn these days. More than 70 percent of the websites are developed using JavaScript. It is continually evolving as more and more features are getting introduced into the language. JavaScript is the language that powers the web and is one of the top most tools that big companies are using these days.

There are currently 1.4 million JavaScript libraries that can be used by web developers across the world. In addition, web browsers now feature a separate JavaScript engine that speeds up these computations, resulting in faster page load times. JavaScript is a constant trend in front end development with a plethora of libraries.

Image description
Source

2. JAM Stack

JAM Stack is not a technology or language but an architectural design that uses JavaScript, APIs, and Markup. These individual technologies can be combined to produce a decoupled web application whose front-end and back-end are separated. JAM Stack boasts of providing following benefits to websites and project workflows : Security, Scale, Performance, Maintenance, Portability and Developer Experience

Image description
Check the website : https://jamstack.org

3. Micro-frontends

Image description

The term Micro Frontends first came up in ThoughtWorks Technology Radar at the end of 2016. It extends the concepts of micro services to the frontend world. The current trend is to build a feature-rich and powerful browser application, aka single page app, which sits on top of a micro service architecture. Over time the frontend layer, often developed by a separate team, grows and gets more difficult to maintain. That’s what we call a Frontend Monolith.

The idea behind Micro Frontends is to think about a website or web app as a composition of features which are owned by independent teams. Each team has a distinct area of business or mission it cares about and specialises in. A team is cross functional and develops its features end-to-end, from database to user interface.

Source

4. React.js

Image description

React.js is one of the most popular JavaScript libraries for building modern and sleek user interfaces these days. It does not need an introduction as such because it is that popular that almost every new developer these days is learning React. React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes.

Image description
Source : https://www.npmtrends.com/react-vs-vue-vs-@angular/core

5. Progressive Web Applications

Image description

The idea behind Progressive Web Applications is to provide a native app experience to the user through the browser itself. PWAs are extremely beneficial as they are of lesser size (in KBs) and provide a near-similar experience like a native application. You would often see PWAs are released as “Lite” versions on the play store and do not exceed 1 MB in size. Even though it looks like a native app, it opens up a browser inside to view the items.

Progressive Web Apps (PWAs) are web apps that use service workers, manifests, and other web-platform features in combination with progressive enhancement to give users an experience on par with native apps.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text
Categories
python

Build your own J.A.R.V.I.S in Python [Full Code + Video]

In this article, we will learn how to create a Feature Rich Virtual Assistant in Python. We will be adding following features to this project :

1. Time Reporting

2. Taking Screenshot

3. Performing Google Search

4. Opening a Specific Website

5. Searching on Wikipedia

6. Listen to Jokes

7. Desktop Notifications for COVID-19 Statistics.

Here is the code for the complete project :

import speech_recognition as sr
import pyttsx3
import datetime
import webbrowser
import wikipedia
import pyjokes
import pyautogui
from plyer import notification
from bs4 import BeautifulSoup
import requests

engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)


def input_query():
    recognizer = sr.Recognizer()
    with sr.Microphone() as source:
        print('recognition is on....')
        recognizer.pause_threshold = 0.7
        voice = recognizer.listen(source)
        try:
            query = recognizer.recognize_google(voice).lower()
            print('this is the query that was made....', query)
            return query
        except Exception as ex:
            print('An exception occurred', ex)


def report_time():
    current_time = datetime.datetime.now().strftime('%I:%M %p')
    return current_time


def speak_va(transcribed_query):
    engine.say(transcribed_query)
    engine.runAndWait()

def make_request(url):
  response = requests.get(url)
  return response.text

def activate_va():
    user_query = input_query()
    print('user query ....', user_query)
    if 'time' in user_query:
        current_time = report_time()
        print(f"the current time is {current_time}")
        speak_va(f"the current time is {current_time}")
    elif 'open website' in user_query:
        speak_va(
            "Please type the name of the website that you want to open (specify the full url) \n")
        website_name = input()
        print(website_name)
        webbrowser.get(
            'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open(website_name)
        speak_va(f"{website_name} opened.")
    elif 'wikipedia' in user_query:
        speak_va("Searching on Wikipedia")
        user_query = user_query.replace('wikipedia', ' ')
        result = wikipedia.summary(user_query, sentences=4)
        print(result)
        speak_va(result)
    elif 'joke' in user_query:
        random_joke = pyjokes.get_joke()
        print(random_joke)
        speak_va(random_joke)
    elif 'screenshot' in user_query:
        image = pyautogui.screenshot()
        image.save('screenshot.png')
        speak_va('Screenshot taken.')
    elif 'search' in user_query:
        speak_va("What do you want me to search for (please type) ? ")
        search_term = input()
        search_url = f"https://www.google.com/search?q={search_term}"
        webbrowser.get(
            'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open(search_url)
        speak_va(f"here are the results for the search term: {search_term}")
    elif 'covid stats' in user_query:
      html_data = make_request('https://www.worldometers.info/coronavirus/')
      # print(html_data)
      soup = BeautifulSoup(html_data, 'html.parser')
      total_global_row = soup.find_all('tr', {'class': 'total_row'})[-1]
      total_cases = total_global_row.find_all('td')[2].get_text()
      new_cases = total_global_row.find_all('td')[3].get_text()
      total_recovered = total_global_row.find_all('td')[6].get_text()
      print('total cases : ', total_cases)
      print('new cases', new_cases[1:])
      print('total recovered', total_recovered)
      notification_message = f" Total cases : {total_cases}\n New cases : {new_cases[1:]}\n Total Recovered : {total_recovered}\n"
      notification.notify(
        title="COVID-19 Statistics",
        message=notification_message,
        timeout=5
      )
      speak_va("here are the stats for COVID-19")
while True:
    activate_va()

Watch on YouTube

If you want to follow along with me, check the video here :

Follow me on:
👉 Twitter: https://twitter.com/The_Nerdy_Dev
👉 Instagram: https://instagram.com/thenerdydev
👉 YouTube: https://youtube.com/thenerdydev

Categories
frontend javascript vuejs

✨8 Vue Projects Every Beginner Should Try

Hey everyone 👋🏻,

In this article, let us see 8 Vue Projects Every Beginner Should Try.

This article was first published on https://the-nerdy-dev.com/.
Check the website for more interesting articles and tutorials on Web Development.

Introduction

Image description

Vue.js is an open-source model–view–view-model (MVVM) front end JavaScript framework for building user interfaces and single-page applications. It was created by Evan You, and is maintained by him and the rest of the active core team members

1. 6 Hours Vue.js and Firebase Project – FireBlogs by @traversymedia

Learn how to build a multi-user blog project with Vue.js, Vuex and Firebase.

What will you learn?

  1. Vue.js basics and fundmentals
  2. State Management using Vuex
  3. Working with Firebase

2. Build a COVID Tracker App with Vue.js and Tailwind

In this project, Brad uses Vue.js and Tailwind to create a Simple COVID Tracker Application.

What will you learn?

  1. Vue.js Fundamentals and Basics
  2. Working with Tailwind.css

3. Vue.js + Vuetify + Firebase Project – DevMeetup

In this tutorial, Maximilian Schwarzmuller shows how to build a complete Project – a Developer Meetup App – with Vue.js 2, Vuetify and Firebase. This is a 24 part series.

Image description

www.youtube.com/playlist?list=PL55RiY5tL51qxUbODJG9cgrsVd7ZHbPrt

What will you learn?

  1. Vue.js 2 Fundamentals and Basics
  2. Vuetify Components
  3. Working with Firebase

4. Build a Weather App in VueJS | Vue Beginner Tutorial

Learn how to make a Weather app in Vue JS, we use the Open Weather Map API to make calls to a restful api to return the current weather data. This uses the Modern Javascript Fetch API along with Vue JS Methods and conditionals.

What will you learn?

  1. Vue.js basics and fundamentals
  2. Interacting with APIs via API calls.

5. Build a Invoice App With Vue 3, Vuex & Firebase

In this video, we build out a full CRUD (create, read, update & delete) invoice app using Vue 3, Vuex & Firebase.

What will you learn?

  1. Vue.js basics and fundamentals
  2. Working with Firebase
  3. State Management using Vuex

6. Create a Gridsome Portfolio – Vue.js project

Learn how to make a portfolio kind of an application using Gridsome library with Vue.js

What will you learn?

  1. Vue.js basics and fundamentals
  2. Gridsome library

7. E-commerce Website With Django and Vue Tutorial (Django Rest Framework)

Learn how to build an e-commerce website using Django and Vue from scratch. Django uses Python Vue uses JavaScript.

Django Rest Framework is used to build the API and backend.
The frontend is a separate Vue project. To handle the payments, we implement Stripe.

What will you learn?

  1. Vue.js basics and fundamentals
  2. Learn Django to create a full stack application

8. Full Stack Web App in Vue.js & Express.js

Image description
Learn how to build a full stack application using Vue.js and Express.js with Postgres as the database

What will you learn?

  1. Vue basics and fundamentals
  2. Making a full stack application with Vue.js and Express along with Postgres as the database

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

👉🏻 Follow me on Twitter : https://twitter.com/The_Nerdy_Dev
👉🏻 Join our Discord Server : https://discord.gg/fgbtN2a

Categories
css frontend html web development

Web Dev Made Easy

Hey everyone 👋🏻,

In this article, I will tell you about a website using which you can use as a resource for learning Web Development.

So the website name is this :

web.dev

https://web.dev

Image description

Now some of the featured courses on their website are :

Image description

1. Learn Responsive Design

Image description

This course takes you on a journey through the many facets of modern responsive web design. The first few modules will ease you in with a history of where responsive design came from and a look at the fundamentals of responsive layouts. From there, you’ll learn about responsive images, typography, accessibility and more.

Along the way you’ll find out how to make websites responsive to user preferences and device capabilities. By the end, you’ll also have an understanding of what the future might hold for responsive design.

Each module has demos and self-assessments for you to test your knowledge.

This course is created for beginner and intermediate designers and developers. A basic understanding of HTML and CSS should be enough. You don’t need to know any JavaScript. If you’re completely new to making websites, there’s an introduction to HTML and another course to help you learn CSS.

2. Learn Forms

Image description

This course breaks down HTML forms into easy to understand pieces. Over the next few modules, you’ll learn how an HTML form works and how to use them effectively in your projects. Use the menu pane by the Learn Forms logo to navigate the modules.

You’ll learn how to build a basic HTML form, about HTML form elements, styling forms, help users re-entering data, ensuring the form is accessible, and secure, how to test your forms, and about specific form types.

Each module is full of interactive demos and self-assessments for you to test your knowledge.

This course is suitable for beginners and advanced HTML developers. The first few modules help you get started with building HTML forms, the other modules give more detail. You can go through the series from start to finish to get a general understanding of HTML forms, or pick a specific module you want to learn more about.

3. Learn Progressive Web Apps

Image description

This course covers the fundamentals of Progressive Web App development into easy-to-understand pieces. Over the following modules, you’ll learn what a Progressive Web App is, how to create one or upgrade your existing web content, and how to add all the pieces for an offline, installable app. Use the menu pane by the “Learn PWA” logo to navigate the modules.

You’ll learn PWA fundamentals like the Web App Manifest, Service Workers, how to design with an app in mind, what’s different from a classic web app, how to use other tools to test and debug your PWA. After these fundamentals, you’ll learn about integration with the platform and operating system, how to enhance your PWA’s installation and usage experience, and how to offer an offline experience.

Each module includes interactive demos and self-assessments for you to test your knowledge. You will be able to test and try demos on your mobile phone, tablet, or laptop while playing with the code to understand the fundamentals of what makes a Progressive Web App.

This course is created for a beginner and advanced web developers alike. You can go through the series from start to finish to get a general understanding of PWA from top to bottom, or you can use it as a reference for specific subjects. For those new to web development you will need a grounding in HTML, CSS, and JavaScript to follow along. Check out Learn CSS, and the HTML and JavaScript courses on MDN.

4. Learn CSS

Image description

This course breaks down the fundamentals of CSS into digestible, easy to understand pieces. Over the next few modules, you’ll learn how the core aspects of CSS work and how to use them effectively in your projects. Use the menu pane by the “Learn CSS” logo to navigate the modules.

You’ll learn CSS fundamentals like the box model, cascade and specificity, flexbox, grid and z-index. And, along with these fundamentals, you’ll learn about functions, color types, gradients, logical properties and inheritance to make you a well-rounded front-end developer, ready to take on any user interface.

Each module is full of interactive demos and self-assessments for you to test your knowledge. In addition to learning through reading and demos, there is an accompanying podcast episode for each topic as another way to learn and continue expanding your knowledge.

This course is created for beginner and advanced CSS developers alike. You can go through the series from start to finish to get a general understanding of CSS from top to bottom, or you can use it as a reference for specific styling subjects. For those new to web development overall, check out the intro to HTML course from MDN to learn all about how to write markup and link your stylesheets.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text
Categories
database mongodb

The NoSQL Database : Basics of CRUD in MongoDB – Part 1 – insertOne, find

Hey guys 👋🏻,
In this article, let us understand about The NoSQL Database : Basics of CRUD in MongoDB. So in this article we will learn about how to retrieve to retrieve/access, delete, create and update our documents. We will also see how we can delete a document by making use of its id and all that jazz. We will be covering the basics about collections and documents, the basic data types and we will also see how we can perform these CRUD operations. So without a further ado, let’s get started.

Image description

Database, Collections and Documents

In the MongoDB world, you can have one or more databases. Each database can hold one or more collections. Now what is a collection ?

A collection is just like a table that we have in a relational database like SQL. In a collection that you and I create, we can have multiple documents. Something that we will discuss a bit later.

Now what do we mean by documents ?

A document is essentially a data piece that you store in the database.

You don’t need to worry about these much. When working with MongoDB database, collections and documents gets implicitly created for you when you start storing the data and work with them.

A bit later in this article we will also learn an explicit way of creating documents in your collection using which you can also configure them a bit further.

The Shell and the MongoDB drivers for different languages

You will use MongoDB drivers in the real world applications
depending on the programming language you are using for writing
the backend servers on.

Shell is the only approach that will work for every language.

MongoDB CRUD Operations

Shell is what gets connected to the local mongo server.

Creating Databases and Collections

To check what databases, we have on the server we can run the command :

Now to switch to a database, we can make use of the use command.
If the database exists, then the use command in that case will make use of the existing one otherwise it will create the new one on the fly so basically on the execution of the command. So let us create a database and call it as flights

So to switch to the flights database, we can say :

We store collections in database. But in order to access a document we need to access that respective collection first in which the document resides, then only we will be able to access the document.

Understanding JSON data

Every document you enter gets a new unique id which is the feature
of the MongoDB. You need to have a unique id for each and every document. We do not have to specify it on its own. Mongodb does this for us under the hood which is of type ObjectId which is another type supported by MongoDB. This id will allow you to sort the documents because it has some timestamp associated to it. This is how JSON data gets stored into our database, to be precise into the collection of our database.

To list all the databases that are there on the MongoDB server, we can run the command :

and this would give us something like this :

Now let us switch to the flights database. Now currently as you can see, the flights database does not exists. So to create it on the fly, we can make use of the command use flights and this will automatically generate a flights database for us.

As a result of the above command, we get this as output in our terminal :

switched to db flights

Let us insert a new flight into the flightData collection which gets implicitly created on demand. Now this new flight is a new document which gets inserted in the flightData collection of the flights database which we reference as db. So db here represents the current database to which we are connected to.

Image description

Now on running the above query, we get this as the output :

To display the array of flight documents in a pretty formatted manner.

  1. First we reference the current active database db.
  2. Then reference the collection whose all the documents we want to retrieve which in our case is flightData
  3. The find() method retrieves all the documents in the current referenced collection.

So this is our query for same :

Image description

and this is the output for same :

Let us now do a comparison between JSON and BSON.

Comparing JSON and BSON

This is what JSON looks like :

JSON is what we insert or retrieve. Behind the scenes, MongoDB actually uses BSON data. This conversion is done by the drivers. This is simply done because BSON is more effective
to store than the JSON data, faster and more efficient in terms of size and efficient storage. There are different types of data – numbers, binaries etc. which are stored in different ways behind the scenes

BSON stands for Binary JSON for storing data into the database.

Let us insert one more flight in our flightData collection.

Image description
Image description

This above insertOne does work because the collection
can accept mixed documents since we know MongoDB is schemaless.

Two documents in the same collection don’t necessarily need to have the same schema

We may have the schema but it is not the must.
The id which is autogenerated you just don’t have to use the autogenerated id you just have to ensure that you have a unique id but if you cannot ensure this you can assign the ids on your own.

Let us insert the same document which we inserted which had missing schema with the id of our choice.
Make sure the id that you use is unique.

So here is the query for same. Please note here we are using an id of our choice i.e lmn-kpq:

Image description

After inserting the document into the flightData collection, we can find all the documents within the collection

Image description

Here the id is unique and it is the one that we used while creating the new document. It doesn’t have ObjectId type
for the simple reason because it was not autogenerated by MongoDB it is the id that we gave to the document. In the next article, we will learn more about CRUD operations. See you next time !

Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.