<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Sachin Sarawgi</title>
    <description>The latest articles on DEV Community by Sachin Sarawgi (@sachinsarawgi).</description>
    <link>https://dev.to/sachinsarawgi</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F403564%2Fd4c91253-a005-440d-aed9-dd54903015a3.jpg</url>
      <title>DEV Community: Sachin Sarawgi</title>
      <link>https://dev.to/sachinsarawgi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sachinsarawgi"/>
    <language>en</language>
    <item>
      <title>Getting started with Spring Boot and Liquibase</title>
      <dc:creator>Sachin Sarawgi</dc:creator>
      <pubDate>Tue, 11 Apr 2023 07:23:07 +0000</pubDate>
      <link>https://dev.to/sachinsarawgi/getting-started-with-spring-boot-and-liquibase-56jc</link>
      <guid>https://dev.to/sachinsarawgi/getting-started-with-spring-boot-and-liquibase-56jc</guid>
      <description>&lt;p&gt;Java developers often use the Spring Boot framework to create web apps. It has a number of features that make it simple to start using and develop reliable, scalable apps. An open-source tool for managing database schema is called Liquibase. It makes it simple for developers to handle database changes, migrate between schema versions, and version control the database schema. Using a straightforward example, we’ll go over how to get started with Spring Boot and Liquibase in this tutorial.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 1: Create a new Spring Boot project
&lt;/h4&gt;

&lt;p&gt;To create a new Spring Boot project, you can use the Spring Initializr. This web-based tool allows you to generate a new Spring Boot project with all the necessary dependencies and configurations.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Open your web browser and navigate to the Spring Initializr website at &lt;a href="https://start.spring.io/." rel="noopener noreferrer"&gt;https://start.spring.io/.&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Fill in the following details:
– Project: Maven Project
– Language: Java
– Spring Boot: 3.0.5
– Group: com.springboot
– Artifact: learningLiquibase
– Packaging: Jar
– Java: 11
– Description: Getting started with Spring Boot &amp;amp; Liquibase&lt;/li&gt;
&lt;li&gt;Click on Add dependencies and add the following dependencies:
– Spring Web
– Spring Data JPA
– H2 Database
– Liquibase Migration&lt;/li&gt;
&lt;li&gt;Click on Generate and download the generated zip file.&lt;/li&gt;
&lt;li&gt;After all configuration, the setup should look like this.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F1%2Ac7JGKy9ajnL4oWY4G6PP7g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F1%2Ac7JGKy9ajnL4oWY4G6PP7g.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 2: Setup the database
&lt;/h4&gt;

&lt;p&gt;In this example, we’ll use the H2 database. Spring Boot comes with auto-configuration for H2, so we don’t need additional configuration.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Open the application.properties file located in the src/main/resources directory and add the following properties
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=learner
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialectydsfjbm
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These properties configure the H2 database for our application.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a new file called schema.sql in the src/main/resources directory and add the following SQL statements:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE customer (
  id INT PRIMARY KEY,
  name VARCHAR(50)
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will create a table called customer with two columns: id and name.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 3: Configure Liquibase
&lt;/h4&gt;

&lt;p&gt;Liquibase provides a way to version control the database schema and manages database changes. In this step, we’ll configure Liquibase for our Spring Boot application.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a new file called liquibase.properties in the src/main/resources directory and add the following properties:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;spring.liquibase.change-log=classpath:/db/changelog/db.changelog-master.yaml
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This property tells Liquibase where to find the changelog file.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a following directory path db/changelog in the src/main/resources directory.&lt;/li&gt;
&lt;li&gt;Create a new file called db.changelog-master.yaml in the src/main/resources/db/changelog directory and add the following content:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;databaseChangeLog:
  - include:
      file: classpath:/db/changelog/changes/001-initial-schema.sql
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This file defines a master changelog that includes a single changelog file called 001-initial-schema.sql.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a new directory called changes in the src/main/resources/db/changelog directory.&lt;/li&gt;
&lt;li&gt;Create a new file called 001-initial-schema.sql in the src/main/resources/db/changelog/changes directory and add the following SQL statements:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE customer (
  id INT PRIMARY KEY,
  name VARCHAR
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This file contains the same SQL statements that we added to schema.sql. This is because we want Liquibase to create the same database schema that we defined in schema.sql.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 4: Create a REST Controller
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Create a new file called CustomerController.java in the src/main/java/com/springboot/learningLiquibase directory and add the following content:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   package com.springboot.learningLiquibase;

   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.http.HttpStatus;
   import org.springframework.http.ResponseEntity;
   import org.springframework.web.bind.annotation.GetMapping;
   import org.springframework.web.bind.annotation.RestController;

   import java.util.List;

   @RestController
   public class CustomerController {

       @Autowired
       private CustomerRepository customerRepository;

       @GetMapping("/customers")
       public ResponseEntity&amp;lt;List&amp;lt;Customer&amp;gt;&amp;gt; getAllCustomers() {
           List&amp;lt;Customer&amp;gt; customers = customerRepository.findAll();
           return new ResponseEntity&amp;lt;&amp;gt;(customers, HttpStatus.OK);
       }
   }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This class defines a REST controller with a single endpoint that returns a list of customers. It uses the CustomerRepository to retrieve the data from the database.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a new file called CustomerRepository.java in the src/main/java/com/springboot/learningLiquibase directory and add the following content:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.springboot.learningLiquibase;

import org.springframework.data.jpa.repository.JpaRepository;

public interface CustomerRepository extends JpaRepository&amp;lt;Customer, Integer&amp;gt; {
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This interface extends the JpaRepository interface and defines a repository for the Customer entity. It provides methods for common database operations such as findAll(), findById(), save(), and delete().&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a new file called Customer.java in the src/main/java/com/springboot/learningLiquibasedirectory and add the following content:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.springboot.learningLiquibase;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Customer {

    @Id
    private Integer id;

    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This class defines the Customer entity with two properties: id and name. It uses JPA annotations to map the entity to the customer table in the database.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 5: Run the application
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Open a terminal window and navigate to the root directory of the project.&lt;/li&gt;
&lt;li&gt;Build the application by running the following command
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;java -jar target/liquibase-demo-0.0.1-SNAPSHOT.jar
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will start the application and listen for incoming HTTP requests.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 6: Test the application
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Open a web browser and navigate to &lt;a href="http://localhost:8080/customers." rel="noopener noreferrer"&gt;http://localhost:8080/customers.&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;You should see a JSON response containing an empty array []. This is because we still need to add customers to the database.&lt;/li&gt;
&lt;li&gt;Open a command prompt and navigate to the root directory of the project.&lt;/li&gt;
&lt;li&gt;Run the following command to start the H2 console:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;java -jar target/liquibase-demo-0.0.1-SNAPSHOT.jar --spring.h2.console.enabled=true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will start the H2 console and open a web browser window.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;In the H2 console, enter the following JDBC URL:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;jdbc:h2:mem:testdb
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will connect to the in-memory H2 database.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Click on the Connect button.&lt;/li&gt;
&lt;li&gt;You should see the CUSTOMER table in the list of tables. Click on the table&lt;/li&gt;
&lt;li&gt;Click on the SQL tab and enter the following SQL statement to insert a new customer:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSERT INTO CUSTOMER (ID, NAME) VALUES (1, 'John Doe');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will insert a new row into the CUSTOMER table with id 1 and name "John Doe".&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Click on the Run button to execute the SQL statement.&lt;/li&gt;
&lt;li&gt;Refresh the web browser window and you should see a JSON response containing a single customer with id 1 and name "John Doe".&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Congratulations! You have successfully created a Spring Boot application with Liquibase integration and tested it by adding a new customer to the database and retrieving the data through a REST API.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 7: Additional configuration
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;By default, Liquibase will look for a changelog file named db.changelog-master.yaml in the resources/db/changelog directory. You can change the location of the file by setting the spring.liquibase.change-log property in the application.properties file.&lt;/li&gt;
&lt;li&gt;For example, to use a changelog file named liquibase-changelog.yaml in the root directory of the project, add the following line to the application.properties file:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;spring.liquibase.change-log=classpath:/liquibase-changelog.yaml
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;You can also configure Liquibase to use a different database than H2. To do this, you need to add the appropriate JDBC driver dependency to the pom.xml file and set the spring.datasource.url, spring.datasource.username, and spring.datasource.password properties in the application.properties file.
For example, to use MySQL as the database, add the following dependency to the pom.xml file:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;mysql&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;mysql-connector-java&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;8.0.23&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, set the following properties in the application.properties file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Replace mydb, root, and password with your own database name, username, and password, respectively.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That’s it! You now have a fully functional Spring Boot application with Liquibase integration. You can use this project as a starting point for your own applications and customize them as needed.&lt;/p&gt;

&lt;p&gt;If you like the content, make sure to live a like :).&lt;/p&gt;

</description>
      <category>java</category>
      <category>spring</category>
      <category>learning</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>How to build a URL Shortener like bitly or shorturl using Node.js</title>
      <dc:creator>Sachin Sarawgi</dc:creator>
      <pubDate>Fri, 19 Jun 2020 19:14:53 +0000</pubDate>
      <link>https://dev.to/sachinsarawgi/url-shortner-with-limit-onclick-count-4maf</link>
      <guid>https://dev.to/sachinsarawgi/url-shortner-with-limit-onclick-count-4maf</guid>
      <description>&lt;p&gt;In this blog, we will see how to build a URL Shortner like bitly or shorturl using NodeJS.&lt;/p&gt;

&lt;p&gt;We may have heard many times that people are asking to build a URL shorter as an interview question, it’s not that complex but giving it a start to build one is complex though :).&lt;/p&gt;

&lt;p&gt;So without wasting time let’s do it.&lt;/p&gt;

&lt;h4&gt;
  
  
  What is a URL Shortner
&lt;/h4&gt;

&lt;p&gt;A URL shortener is a simple tool that takes a long URL and turns it into whatever URL you would like it to be.&lt;/p&gt;

&lt;h4&gt;
  
  
  Why we need it
&lt;/h4&gt;

&lt;p&gt;Sometimes the links to a location or generally to a social platform become so big that it becomes difficult to manage them. A URL shorter will help in managing, track-compile click data, and one important point they promote sharing.&lt;/p&gt;

&lt;h4&gt;
  
  
  npm Packages We Are Going To Use
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://www.npmjs.com/package/config"&gt;&lt;strong&gt;config&lt;/strong&gt;&lt;/a&gt; &lt;strong&gt;:&lt;/strong&gt; It lets you define a set of default parameters, and extend them for different deployment environments (development, QA, staging, production, etc.). For production, we have to define production.js similarly for development devlopment.js. By default, it will look for default.js.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This will be used to store config related to DB and others.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.npmjs.com/package/valid-url"&gt;&lt;strong&gt;valid-url&lt;/strong&gt;&lt;/a&gt;: This module collects common URI validation routines to make input validation, and maintaining easier and more readable. All functions return an untainted value if the test passes, and undefined if it fails.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This will be used to validate the URL given by the user for a shortening purpose.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.npmjs.com/package/shortid"&gt;&lt;strong&gt;shortid&lt;/strong&gt;&lt;/a&gt;: ShortId creates amazingly short non-sequential URL-friendly unique ids.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This will be used to generate a unique id for each shortened URL.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.npmjs.com/package/express"&gt;&lt;strong&gt;express&lt;/strong&gt;&lt;/a&gt;: The Express philosophy is to provide small, robust tooling for HTTP servers, making it a great solution for single-page applications, web sites, hybrids, or public HTTP APIs.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This will be used to create the server and route different HTTP path.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.npmjs.com/package/mongoose"&gt;&lt;strong&gt;mongoose&lt;/strong&gt;&lt;/a&gt;: Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks. As they use promise we will use async and await feature of JS.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This will be used for connecting with MongoDB, saving, updating and querying the DB.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Next, let’s setup MongoDB for setting our database.&lt;/p&gt;

&lt;h4&gt;
  
  
  Setting Up MongoDB Atlas
&lt;/h4&gt;

&lt;p&gt;I wanted to use the cloud setup of MongoDB instead of a local setup, you can choose what fits better for you.&lt;/p&gt;

&lt;p&gt;Steps for setting up cloud MongoDB Atlas account:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Visit the site &lt;a href="https://www.mongodb.com/cloud/atlas"&gt;https://www.mongodb.com/cloud/atlas&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Make an account, the cloud setup is free&lt;/li&gt;
&lt;li&gt;Create a cluster&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Puuj1BzL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2ANFoNRJns1XpJ0Wr88M4PuA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Puuj1BzL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2ANFoNRJns1XpJ0Wr88M4PuA.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Go to Connect, create a user&lt;/li&gt;
&lt;li&gt;Go to connect your application, you will see a URL (just remember the location of URL). Password will be replaced by your account password.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Setting Up The Project
&lt;/h4&gt;

&lt;p&gt;Create a separate directory for your project urlshortner , open that directory in your favorite IDE. I am using Visual Studio Code here.&lt;/p&gt;

&lt;p&gt;Go inside the folder and type npm init , give the necessary details for setting up the project.&lt;/p&gt;

&lt;p&gt;Next, we need to download necessary node packages which we discussed earlier, type following command to download them&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i express config mongoose shortid valid-url
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;The above command will update package.jsonwith the dependencies and download the needed packages inside node_modules folder.&lt;/p&gt;
&lt;h3&gt;
  
  
  Phewwwwww, Let’s Do The Coding Part Now
&lt;/h3&gt;

&lt;p&gt;Open your code editor. Create a folder for storing the config, give the folder name config . Create a file inside folder default.js and give your MongoDB connect URL (we setup it earlier, I told you to remember it 😂) and baseURL.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;replace the username and password with the user and password we created in MongoDB atlas.&lt;/li&gt;
&lt;li&gt;allowedClick is a kind of restriction, that how many times the same URL can be used. Later can be used for pricing purpose. You can change it depending on your needs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Config file for MongoDB setup
&lt;/h4&gt;

&lt;p&gt;We will import necessary packages and connect with MongoDB&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h4&gt;
  
  
  Define Schema For Storing URL Details
&lt;/h4&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;mongoose.Schema will define the document details which it will store. When we will code it will be much clear what each detail does.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;urlCode&lt;/strong&gt; : This will store the unique id related to each URL.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;longURL&lt;/strong&gt; : This is the URL which we need to short.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;shortUrl&lt;/strong&gt; : This is the actual short URL&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;clickCount&lt;/strong&gt; : This stores how many times users have used the short URL.&lt;/p&gt;

&lt;h4&gt;
  
  
  Define Route for Shortening the URL
&lt;/h4&gt;

&lt;p&gt;Create a folder name routes , inside that create a file shorturl.js which will have the code for shortening the URL.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Let’s understand the code.🤓🤓🤓&lt;/p&gt;

&lt;p&gt;First of all, we imported the necessary packages which will be required later on. Used &lt;em&gt;express&lt;/em&gt; package to create a route, using that route created an HTTP POST handler.&lt;/p&gt;

&lt;p&gt;Next marked it async as it ensures that the function returns a promise, and wraps non-promises in it. Using async allow us to useawait , it makes JavaScript wait until that promise settles and returns its result.&lt;/p&gt;

&lt;p&gt;We take out the URL submitted for shortening purposes from the request body, also fetch base URL which is mentioned in default.js . Next, we check if the URL submitted for shortening is a valid URL or not using the &lt;em&gt;isUri&lt;/em&gt; method of &lt;em&gt;valid-url&lt;/em&gt; package.&lt;/p&gt;

&lt;p&gt;After the checking is successful we will query MongoDB to check if the URL sent for shortening already shorten or not. If shorten just return that result else short the URL.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;mongoose methods returns a &lt;strong&gt;promise&lt;/strong&gt; so we added &lt;strong&gt;await&lt;/strong&gt; before it to &lt;strong&gt;wait till we get response&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For shortening the URL we will generate a unique id using generate method of &lt;em&gt;shortid&lt;/em&gt; package. Next, append baseURL with the unique id to generate a URL as a short URL. Also, as the short URL is generated for the first time we will mark the &lt;em&gt;clikcCount&lt;/em&gt; to be zero. Save the document and return the result as JSON.&lt;/p&gt;

&lt;p&gt;Sample response (sending an amazon product links which need to be shortened).&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h4&gt;
  
  
  Define Route for Redirecting the Short URL top Destination
&lt;/h4&gt;

&lt;p&gt;Create a new file inside routes folder named getshortenurl.js .&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Let’s understand the code. 🤓🤓🤓&lt;/p&gt;

&lt;p&gt;First of all, we imported the necessary packages which will be required later on. Used &lt;em&gt;express&lt;/em&gt; package to create a route, using that route created an HTTP GET handler. The URL will be getting &lt;em&gt;shortUrl&lt;/em&gt; as a parameter. This parameter is the unique code that we appended to the baseUrl.&lt;/p&gt;

&lt;p&gt;Next, we extract the &lt;em&gt;shortUrl&lt;/em&gt; in a separate variable. As the code is unique so we can search the DB if we have any document with that unique code. The return result is stored in a variable.&lt;/p&gt;

&lt;p&gt;If the return result is a document that means we have already shortened the URL. Check the clicked count of the returned document if the clicked count is passed the limit which we set in default.js, if yes return an error else increase the click count of the document and update it in the DB also, redirect to the long URL using the &lt;em&gt;redirect&lt;/em&gt; method of &lt;em&gt;res&lt;/em&gt; object.&lt;/p&gt;

&lt;h4&gt;
  
  
  Let’s Combine Everything
&lt;/h4&gt;

&lt;p&gt;We need to have the main file which will combine all this together, remember we haven’t created the server yet. 😅😅😅&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;blockquote&gt;
&lt;p&gt;The baseURL which we configured in default.js has the value &lt;a href="http://localhopst:8000/v1,"&gt;http://localhopst:8000/v1,&lt;/a&gt; because our app is running in localhost and the server is listening on POST 8000. The URL for getShortenUrlRoute is /v1/ so that is appended to the baseUrl..&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let’s understand the code.🤓🤓🤓&lt;/p&gt;

&lt;p&gt;Import necessary packages with that import the routes which we have created in previous step, import config for MongoDB connection.&lt;/p&gt;

&lt;p&gt;Connect to the DB, create the server and connect to a PORT (here it’s 8000).&lt;/p&gt;

&lt;p&gt;app.use(express.json({})) this will parse incoming request body in JSON format.&lt;/p&gt;

&lt;p&gt;Next, connect the router to the appropriate URL. Now let’s hope things work out. Start the app by using node index.js and play.&lt;/p&gt;

&lt;p&gt;After creating a short URL paste the short URL in your browser it should redirect to the main URL.&lt;/p&gt;

&lt;p&gt;I hope this blog will help you in understanding the basics of how to make a URL shorter. For code, you can refer to &lt;a href="https://github.com/codesprintpro/urlshortner"&gt;here on GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you enjoyed reading this, don’t forget the like. 👏&lt;br&gt;&lt;br&gt;
Thank you.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you enjoyed the content buy me a coffee. &lt;a href="https://www.paypal.me/sachinsarawgi"&gt;SachinSarawgi&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>node</category>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Twitter Bot Using NodeJS, Step By Step Guide To Develop</title>
      <dc:creator>Sachin Sarawgi</dc:creator>
      <pubDate>Wed, 17 Jun 2020 04:26:32 +0000</pubDate>
      <link>https://dev.to/sachinsarawgi/twitter-bot-using-nodejs-step-by-step-guide-to-develop-3394</link>
      <guid>https://dev.to/sachinsarawgi/twitter-bot-using-nodejs-step-by-step-guide-to-develop-3394</guid>
      <description>&lt;p&gt;&lt;em&gt;We will build from scratch a Twitter Bot using NodeJS which will Retweet.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In this blog, we will understand how to build a Twiter bot that will retweet every time a tweet related to #100DaysOfCode is twitter using NodeJS.&lt;/p&gt;

&lt;p&gt;It’s better to set up a new Twitter account where we can put any random thing. Once done with the final version of the bot we can deploy it to our main Twitter account.&lt;/p&gt;

&lt;h3&gt;
  
  
  Topics Covered
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Setting up the Project&lt;/li&gt;
&lt;li&gt;Setting up config details&lt;/li&gt;
&lt;li&gt;Search tweet using Twitter Search Tweet API&lt;/li&gt;
&lt;li&gt;Retweet using Twitter POST Tweet API&lt;/li&gt;
&lt;li&gt;Combine Search &amp;amp; Post Twitter API&lt;/li&gt;
&lt;li&gt;Deploy the app on Heroku&lt;/li&gt;
&lt;li&gt;Enhancement to the code&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--LLjLzVEA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2ApJmPwLeNEb6PeoA1hfh8UA.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--LLjLzVEA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2ApJmPwLeNEb6PeoA1hfh8UA.jpeg" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Setting up the project
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Download and Install NodeJS from &lt;a href="https://nodejs.org/en/download/"&gt;here&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Create a separate directory from your command line mkdir twitterbot.&lt;/li&gt;
&lt;li&gt;Go inside the directory cd twitterbot&lt;/li&gt;
&lt;li&gt;Setup the project files usingnpm init , fill the proper details. This will create a package.json file.&lt;/li&gt;
&lt;li&gt;Install twit node package npm install twit --save . Extra attribute &lt;em&gt;save&lt;/em&gt; will save the package name in a list of dependencies in package.json file.&lt;/li&gt;
&lt;li&gt;Create a js file where you will write code, the file name should be the same as which you gave while mentioning the &lt;em&gt;main file&lt;/em&gt; detail in npm init.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That’s all for now to set up the project. Open the project in your favorite editor.&lt;/p&gt;

&lt;p&gt;twit package will hide many of the boilerplate code for us. We just need to worry about the Twitter APIs.&lt;/p&gt;

&lt;h4&gt;
  
  
  Setting up config details
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Open the main file in your editor. Let’s say the file name is &lt;em&gt;twitterbot.js&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;Import &lt;em&gt;twit&lt;/em&gt; module which is present inside the &lt;em&gt;twit package&lt;/em&gt; which we downloaded in our previous step let twit = require('twit'); .&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Create a twit object with config details.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;For getting all the above details we need to create an app on Twitter. From there we will get above four details.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Sign in to your Twitter account.&lt;/li&gt;
&lt;li&gt;Go to &lt;a href="https://developer.twitter.com/en/apps"&gt;https://developer.twitter.com/en/apps&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Make sure we have our phone number associated with the account we logged in.&lt;/li&gt;
&lt;li&gt;Click on Create an App.&lt;/li&gt;
&lt;li&gt;Give a unique App Name, fill &lt;em&gt;Application description&lt;/em&gt;, &lt;em&gt;Website URL,&lt;/em&gt; and _Tell us how this app will be used _fields.&lt;/li&gt;
&lt;li&gt;Click on Create. Our app has been created.&lt;/li&gt;
&lt;li&gt;Go to &lt;em&gt;Key and tokens&lt;/em&gt; tab copy Consumer API key and Consumer API Secret key. Fill it in our &lt;em&gt;twitterbot.js&lt;/em&gt; file.&lt;/li&gt;
&lt;li&gt;Click on &lt;em&gt;Generate Access token &amp;amp; access token secret,&lt;/em&gt; copy &lt;em&gt;Access token,&lt;/em&gt; and &lt;em&gt;Access token secret&lt;/em&gt;. Fill it in our &lt;em&gt;twitterbot.js&lt;/em&gt; file.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Run your file &lt;em&gt;twitterbot.js&lt;/em&gt; to see if the code we have written is correct or not. Though nothing dynamic happening here.&lt;/p&gt;

&lt;h4&gt;
  
  
  Search tweet using Twitter Search Tweet API
&lt;/h4&gt;

&lt;p&gt;We will use the &lt;em&gt;get&lt;/em&gt; method exposed by the twit package. It takes the twitter search API and optional parameters, callback function as input. T.get('search/tweets', [params], [callback]);&lt;/p&gt;

&lt;p&gt;The second optional argument has search query details. Suppose we want to search for Tweet having #100DaysOfCode as a hashtag, also we want to fetch 10 results at a time. For date, we will hard code it for now for some date.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The q key will have the text for which we want to search and the date from which the tweet should be searched. Right now the date is hardcoded, count tells upper bound of how many tweets should be given as a result.&lt;/p&gt;

&lt;p&gt;Now we need a function which will be called as a callback. Suppose for now we want to log the tweet message whenever we get a result of the search tweet.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;data.statuses will give us the array of tweets that it found based on the query parameter. tweetMsgs[i].textwill give the text message of each tweet.&lt;/p&gt;

&lt;p&gt;Final code for search tweet after callback function.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;For more on &lt;a href="https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets"&gt;Search API&lt;/a&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  Retweet using Twitter POST Tweet API
&lt;/h4&gt;

&lt;p&gt;We will use the &lt;em&gt;post&lt;/em&gt; method exposed by the twit package. It takes the twitter search API and optional parameters, callback function as input. T.get('statuses/retweet/:id', {id: tweetid}, [callback]).&lt;/p&gt;

&lt;p&gt;The API &lt;em&gt;id&lt;/em&gt; key has the value of the &lt;em&gt;id_str&lt;/em&gt; (it is a field inside the tweet JSON which we want to retweet). Suppose &lt;em&gt;tweetMsg&lt;/em&gt; variable is a JSON value of a tweet.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;T.post('statuses/retweet/:id', { id: tweetMsg.id\_str });
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;tweetMsg.id_str will give the value from JSON.&lt;/p&gt;

&lt;p&gt;Now we need a function which will be called as a callback. Suppose for now we will log if the tweet was successful or not.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;For more on &lt;a href="https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-retweets-id"&gt;Retweet API&lt;/a&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  Combine Search &amp;amp; Post Twitter API
&lt;/h4&gt;

&lt;p&gt;Now let us combine the search and post Twitter API. We will retweet each of the tweets present inside the search result.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;blockquote&gt;
&lt;p&gt;Updated code can be found &lt;a href="https://github.com/codesprintpro/twitterbot"&gt;here on GitHub&lt;/a&gt;. Remember to put config details for Twit object. Added function to give the date in real-time. setTimeout method is used to retweet in some interval.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4&gt;
  
  
  Deploy the app on Heroku
&lt;/h4&gt;

&lt;p&gt;We will be using Heroku to deploy our twitter bot.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Register in Heroku online&lt;/li&gt;
&lt;li&gt;Create an App in the Heroku dashboard online&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Local Machine Setup&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Install Heroku &lt;a href="https://devcenter.heroku.com/articles/heroku-cli"&gt;https://devcenter.heroku.com/articles/heroku-cli&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Go inside the project folder and execute git init&lt;/li&gt;
&lt;li&gt;Then bind the project with Heroku remote by executing heroku git:remote -a {appname} . appname is the app name in Heroku.&lt;/li&gt;
&lt;li&gt;Execute the following commands to push code and run remotely&lt;/li&gt;
&lt;li&gt;git add .&lt;/li&gt;
&lt;li&gt;git commit -m “message"&lt;/li&gt;
&lt;li&gt;git push heroku master This will start executing out a bot on Heroku.&lt;/li&gt;
&lt;li&gt;heroku logs to check logs of the app on the server.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Enhancement to the code
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;We can add a function that will give us a date in real-time so that we don’t have to hard code the date, which tells from which date we want the read the Tweet.&lt;/li&gt;
&lt;li&gt;Instead of directly retweet we can add a delay to our tweets so that not all are getting tweeted at the same time. We can use setTimeout for that.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I hope this blog will help you to understand how a simple Twitter Bot can be designed using NodeJS.&lt;/p&gt;

&lt;p&gt;Updated code can be found &lt;a href="https://github.com/codesprintpro/twitterbot"&gt;here on GitHub&lt;/a&gt;, added code for making a tweet as favorite. Remember to put config details for Twit object. Added function to give the date in real-time.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you enjoyed reading this, don’t forget the like. 👏&lt;br&gt;&lt;br&gt;
Thank you. Follow me on _ &lt;a href="https://twitter.com/SachinSarawgi"&gt;&lt;em&gt;Twitter&lt;/em&gt;&lt;/a&gt;&lt;/em&gt;._&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>node</category>
      <category>webdev</category>
    </item>
    <item>
      <title>{ "Objects" : "In JavaScript" }</title>
      <dc:creator>Sachin Sarawgi</dc:creator>
      <pubDate>Mon, 15 Jun 2020 06:05:27 +0000</pubDate>
      <link>https://dev.to/sachinsarawgi/objects-in-javascript-27bm</link>
      <guid>https://dev.to/sachinsarawgi/objects-in-javascript-27bm</guid>
      <description>&lt;p&gt;This article will cover Objects in JavaScript. It’s best suited for someone new to JavaScript.&lt;/p&gt;

&lt;h3&gt;
  
  
  Topic Covered
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  Objects &amp;amp; Its Use Case&lt;/li&gt;
&lt;li&gt;  Object Properties&lt;/li&gt;
&lt;li&gt;  How to Access Object Properties&lt;/li&gt;
&lt;li&gt;  Add &amp;amp; Delete Property&lt;/li&gt;
&lt;li&gt;  Nested Object&lt;/li&gt;
&lt;li&gt;  Object Methods&lt;/li&gt;
&lt;li&gt;  How to Execute Object Methods&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EH8X6TIe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/6qck3gkdje3sljsjk1rx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EH8X6TIe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/6qck3gkdje3sljsjk1rx.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Objects &amp;amp; Its Use Case
&lt;/h4&gt;

&lt;p&gt;Suppose a use case where we have to receive a Person details from a user. One approach could be to define multiple variables to get each type of detail like firstName, lastName, phoneNumber, streetNo, address, pincode, etc. This list can grow. There will be so many of them that handling and passing it across different execution points will be a headache. Well here comes the Object as a savior.&lt;/p&gt;

&lt;p&gt;In Object, we can store multiple variables (called Property) together, and also the methods which work on those variables.&lt;/p&gt;

&lt;p&gt;Here is how to declare an Object in JavaScript. This doesn’t have anything its just an empty object.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var person = {  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;
  
  
  Object Properties
&lt;/h4&gt;

&lt;p&gt;Object properties are kind of variables only that holds some value. They are represented by a label and then a colon, followed by the value of the label. The value can be of any type be it number, string, array, or even another object 😱.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var person = {  
  name: 'your name'  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;All valid variables can be treated as a label. But if we want something which is not a valid variable, we have to include that label in single quotes.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var person = {  
  name: 'your name',  
  'my address': 'your address'  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;em&gt;Note&lt;/em&gt;: We use comma to separate multiple properties in an Object.&lt;/p&gt;

&lt;h4&gt;
  
  
  How to Access Object Properties
&lt;/h4&gt;

&lt;p&gt;Once we have our object we would like to access it right? JavaScript provides two ways to do this. Once by dot notation and another one is to mention property name within single quotes inside square brackets.&lt;/p&gt;

&lt;p&gt;Access property using dot notation&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var person = {  
  name: 'your name',  
  'my address': 'your address'  
}

console.log(person.name);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Access property using square brackets&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var person = {  
  name: 'your name',  
  'my address': 'your address'  
}

console.log(person['name']);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;em&gt;Note&lt;/em&gt;: Now one may ask how we will access label which is not valid variable name. We do this by accessing them using a square bracket. A label that is not a valid variable name cannot be accessed using dot notation.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var person = {  
  name: 'your name',  
  'my address': 'your address'  
}

console.log(person['my address']); // correct  
console.log(person.my address // wrong
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;em&gt;Note&lt;/em&gt;: If the label accessed is not inside Object, &lt;em&gt;undefined&lt;/em&gt; will be returned.&lt;/p&gt;

&lt;h4&gt;
  
  
  Add &amp;amp; Delete Property
&lt;/h4&gt;

&lt;p&gt;Suppose we have the object which is already declared and defined. JavaScript gives us the power to add new property whenever we want 😆.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var person = {  
  name: 'your name',  
  'my address': 'your address'  
}

person.pincode = 'pincode';  
person['country'] = 'country';
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;We can also delete a property once its use is over so that we are not keeping unnecessary data.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var person = {  
  name: 'your name',  
  'my address': 'your address'  
}

person.pincode = 'pincode';  
person['country'] = 'country';

delete person.country;  
delete person['name'];
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;
  
  
  Nested Object
&lt;/h4&gt;

&lt;p&gt;As we previously read that object can be nested too. Here is how to declare them and access&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var person = {  
  name: 'your name',  
  address: {  
    street: 'street',  
    'road no': 1  
  }  
}

console.log(person.address.street); // will print 'street'  
console.log(person.address['road no']); //will print 1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;em&gt;Note&lt;/em&gt;: In the case of nested Object the dot and square bracket notation can be combined.&lt;/p&gt;

&lt;h4&gt;
  
  
  Object Methods
&lt;/h4&gt;

&lt;p&gt;It’s very good to bind property and the method which works on that property together. Similarly like different data type values, a label can also hold a function definition. For more on &lt;a href="https://medium.com/@codesprintpro/javascript-basics-part-5-9126888a5cde"&gt;function&lt;/a&gt;. Here is how we do it in javaScript&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var person = {  
  name: 'your name',  
  address: {  
    street: 'street',  
    'road no': 1  
  },  
  printMyName: function(){  
    console.log('your name');  
  }  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;It’s not similar to what we do in a normal function definition. Here we write first the label, then a colon, then the function definition inside the &lt;em&gt;function()&lt;/em&gt; block.&lt;/p&gt;

&lt;p&gt;We can also access the other property of the Object inside function definition using &lt;em&gt;this&lt;/em&gt; keyword.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var person = {  
  name: 'your name',  
  address: {  
    street: 'street',  
    'road no': 1  
  },  
  printMyName: function(){  
    console.log(this.name);  
  }  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Inside function parenthesis, we can any argument like a normal function. For accessing function argument we don’t need this as their scope is local to function definition.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var person = {  
  name: 'your name',  
  address: {  
    street: 'street',  
    'road no': 1  
  },  
  printWhatIPass: function(myVar){  
    console.log(myVar);  
  }  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;
  
  
  How to Execute Object Methods
&lt;/h4&gt;

&lt;p&gt;We can call object methods by using dot notation. If the function takes some argument we can pass that too.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var person = {  
  name: 'your name',  
  address: {  
    street: 'street',  
    'road no': 1  
  },  
  printMyName: function(){  
    console.log(this.name);  
  },  
  printWhatIPass: function(myVar){  
    console.log(myVar);  
  }  
}

console.log(person.printMyName()); // will print 'your name'

//will print 'my own text'  
console.log(person.printWhatIPass('my own text'));
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This ends the discussion about Objects, it’s property and methods. &lt;/p&gt;

&lt;p&gt;Reached till here, give me &lt;a href="https://dev.to/sachinsarawgi"&gt;follow up to get the latest stories&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you enjoyed reading this, don’t forget the like. 👏&lt;br&gt;&lt;br&gt;
Thank you.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Basic HTTP Server Using NodeJS From Scratch</title>
      <dc:creator>Sachin Sarawgi</dc:creator>
      <pubDate>Sun, 14 Jun 2020 04:46:31 +0000</pubDate>
      <link>https://dev.to/sachinsarawgi/basic-http-server-using-nodejs-from-scratch-2p6k</link>
      <guid>https://dev.to/sachinsarawgi/basic-http-server-using-nodejs-from-scratch-2p6k</guid>
      <description>&lt;p&gt;&lt;br&gt;
&lt;em&gt;In this blog, we will see how to create an HTTP Server to handle GET, POST, PUT, DELETE request method type from scratch.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;We need to have Node.js installed in our machine for the code to work. We will be using ‘&lt;strong&gt;&lt;em&gt;http&lt;/em&gt;&lt;/strong&gt;’ module provided out of the box to get the request and response object. We will not use any other custom library.&lt;/p&gt;

&lt;h3&gt;
  
  
  Steps For Creating A HTTP Server
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt; Create Server using &lt;strong&gt;&lt;em&gt;http&lt;/em&gt;&lt;/strong&gt; module and add a listener&lt;/li&gt;
&lt;li&gt; Do the necessary entry check for the request&lt;/li&gt;
&lt;li&gt; Extract request method type&lt;/li&gt;
&lt;li&gt; Writing handler for Http GET request&lt;/li&gt;
&lt;li&gt; Writing handler for Http POST request&lt;/li&gt;
&lt;li&gt; Writing handler for Http PUT request&lt;/li&gt;
&lt;li&gt; Writing handler for Http DELETE request&lt;/li&gt;
&lt;/ol&gt;




&lt;h4&gt;
  
  
  1. Create Server using http module and add a listener
&lt;/h4&gt;

&lt;p&gt;First of all, we need to create a server that will listen to some particular port. So that if any request comes to that port the listener will be called.&lt;/p&gt;

&lt;p&gt;We can do this using &lt;a href="https://nodejs.org/api/http.html"&gt;http&lt;/a&gt; module.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const server = http.createServer(requestListener);  
server.listen(8090);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;createServer&lt;/strong&gt; method accepts the listener as an argument. &lt;strong&gt;listen&lt;/strong&gt; method takes the port number where it will keep listening.&lt;/p&gt;

&lt;p&gt;Let’s see what empty &lt;strong&gt;requestListener&lt;/strong&gt; method looks like.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const requestListener = function (req, res) {  
 //all the code goes inside it  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;




&lt;h4&gt;
  
  
  2. Do the necessary entry check for the request
&lt;/h4&gt;

&lt;p&gt;Suppose we want our server to support REST API, and we want to have the following checks on request object:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Content-Type is application/json&lt;/li&gt;
&lt;li&gt;  Accept is application/json.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We will be using req object to get headers details and check the required values.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const REQUIRED_CONTENT_TYPE = 'application/json';  
const ACCEPT_ENCODING_1 = 'application/json';  
const ACCEPT_ENCODING_2 = '*/*';

const entryCheck = function (req) {  
  const contentType = req.headers["content-type"];  
  if (!contentType.includes(REQUIRED_CONTENT_TYPE)) {  
    throw new Error("Sorry we only support content type as json format.");  
  }  

  const accept = req.headers["accept"];  
  if (!(accept.includes(ACCEPT_ENCODING_1) ||  
accept.includes(ACCEPT_ENCODING_2))) {  
    throw new Error("Sorry we only support accept json format.");  
  }  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Let’s understand what’s going on.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  First, we declare constant for content-type and accept header which our server will support&lt;/li&gt;
&lt;li&gt;  Next &lt;strong&gt;entryCheck&lt;/strong&gt; is the method where we will check if the request headers have the required and matching details.&lt;/li&gt;
&lt;li&gt;  If either Content-type or Accept is not matching we will throw an error.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now let’s see how we will call this method from type listener.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const requestListener = function (req, res) {  
  try {  
    entryCheck(req);  
  } catch (error) {  
    res.writeHead(400);  
    res.end(error.message);  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;a href="https://nodejs.org/api/http.html#http_response_writehead_statuscode_statusmessage_headers"&gt;&lt;strong&gt;writeHead&lt;/strong&gt;&lt;/a&gt; method takes the HTTP Status code, it could be any valid status code. It has some optional parameters too, the second is a status message and the third is headers.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;end&lt;/strong&gt; method takes the response body which will be shown to the user. After this method, the response is sent back and the whole request-response process is done.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: We can add multiple entry checks depending on our condition like a cookie, hostname/IP address, a particular header etc.&lt;/p&gt;




&lt;h4&gt;
  
  
  3. Extract request method type
&lt;/h4&gt;

&lt;p&gt;We need to know HTTP method type to handle each one of them separately.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const requestListener = function (req, res) {  
  try {  
    entryCheck(req);  
    const methodType = req.method.toUpperCase();  
    ......
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;method property of request object gives us the Http method type like GET, POST, PUT, DELETE.&lt;/p&gt;

&lt;p&gt;Next, we can use switch to handle different Http requests type differently&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;....  
switch(methodType){  
  case 'GET':  
    break;  
  case 'POST':  
    break;  
  case 'PUT':  
    break;  
  case 'DELETE':  
    break;  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;




&lt;h4&gt;
  
  
  4. Writing handler for Http GET request
&lt;/h4&gt;

&lt;p&gt;Http GET requests are generally for finding an existing object by sending unique details&lt;/p&gt;

&lt;p&gt;We can simply return a generic response in every kind of Http method type.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;case 'GET':  
  res.writeHead(200);  
  res.end(`We received ${methodType} type request`);  
  break;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;But instead of just returning simple response let’s create some object and apply operations on it.&lt;/p&gt;

&lt;p&gt;Let us consider an employee object with the following fields:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{   
  "_id": "5ec02a534587193b1c607e2c",  
  "name": {  
    "first": "Pace",  
    "last": "Simmons"  
  },  
  "company": "MOLTONIC",  
  "email": "pace.simmons@moltonic.co.uk",  
  "phone": "+1 (941) 562-2930",  
  "address": "274 Dikeman Street, Somerset, Nevada, 6375"  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;We will have an object containing an array of above employee objects.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let employeeData = [  
 {   
  "_id": "5ec02a534587193b1c607e2c",  
  "name": {  
    "first": "Pace",  
    "last": "Simmons"  
  },  
  "company": "MOLTONIC",  
  "email": "pace.simmons@moltonic.co.uk",  
  "phone": "+1 (941) 562-2930",  
  "address": "274 Dikeman Street, Somerset, Nevada, 6375"  
 },  
 ......  
]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Consider GET request where we will ask for particular employee detail by providing the &lt;strong&gt;_id&lt;/strong&gt; value.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;localhost:8090/5ec02a53d8ba79b6992ba757
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Now we will need one method which will search for the request &lt;strong&gt;_id&lt;/strong&gt; in the array of objects. We will write one method to search employee based on &lt;strong&gt;_id&lt;/strong&gt;:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let findEmployee = (id) =&amp;gt; {  
  return employeeData.find((employee) =&amp;gt; {  
    if (employee._id === id)  
      return employee;  
  });  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Let’s rewrite the GET Http handler code&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const requestListener = function (req, res) {  
  ....  
  case 'GET':  
    getMethodHandler(url, req, res);  
    break;  
  ....  
}

const getMethodHandler = (url, req, res) =&amp;gt; {  
  const employeeId = url.substring(1);  
  const employee = findEmployee(employeeId);  
  if (!employee) {  
    res.writeHead(400);  
    res.end(`The employee with id ${employeeId} is not present.`);  
    return;  
  }  
  res.writeHead(200);  
  res.end(JSON.stringify(employee));  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;We have written a separate method&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  First, we found the requested &lt;strong&gt;_id&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;  We pass that &lt;strong&gt;_id&lt;/strong&gt; to &lt;strong&gt;findEmployee&lt;/strong&gt; method to get the employee object&lt;/li&gt;
&lt;li&gt;  Next, we check if an employee object is found or not if not we throw an error.&lt;/li&gt;
&lt;li&gt;  If everything goes fine we return the employee object in the response body.&lt;/li&gt;
&lt;/ul&gt;




&lt;h4&gt;
  
  
  5. Writing handler for Http POST request
&lt;/h4&gt;

&lt;p&gt;Http POST requests are generally for inserting the new objects. In our case, we will add the received employee object to the array. Let’s write code for that method&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let addEmployee = (employee) =&amp;gt; {  
  employeeData.push(employee);  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Next, we need to handle the POST request and parse the request body to get the employee object we need to insert:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const requestListener = function (req, res) {  
  ....  
  case 'POST':  
    getRequestBodyAndGenerateResponse(req, res, postMethodHandler);  
    break;  
  ....  
}

const getRequestBodyAndGenerateResponse = (req, res, callback) =&amp;gt; {  
  let body = '';  
  req.on('data', chunk =&amp;gt; {  
    body += chunk.toString();  
  });  
  req.on('end', () =&amp;gt; {  
    callback(res, JSON.parse(body));  
  });  
}

const postMethodHandler = (res, body) =&amp;gt; {  
  try {  
    let reqBody = body;  
    addEmployee(reqBody)  
    res.writeHead(200);  
    res.end(`The Employee object with id is ${reqBody._id} added.`);  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Let’s understand what we did here.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  We defined a method &lt;strong&gt;getRequestBodyAndGenerateResponse&lt;/strong&gt;(req, res, postMethodHandler).&lt;/li&gt;
&lt;li&gt;  This method reads the data from req object by listening for ‘&lt;strong&gt;data&lt;/strong&gt;’ event and append it to one variable body.&lt;/li&gt;
&lt;li&gt;  Once the ‘&lt;strong&gt;end&lt;/strong&gt;’ event is triggered means the request body read completely, it parses the string into JSON and calls the callback function passed to it.&lt;/li&gt;
&lt;li&gt;  This callback function is the one that prepares the response object.&lt;/li&gt;
&lt;li&gt;  In the callback function first, we add the employee to employee array.&lt;/li&gt;
&lt;li&gt;  Then prepare a response and sent it to the user.&lt;/li&gt;
&lt;/ul&gt;




&lt;h4&gt;
  
  
  6. Writing handler for Http PUT request
&lt;/h4&gt;

&lt;p&gt;Http PUT requests are generally for updating the old objects. In our case, we will update the received employee object if present inside the array. Let’s write code for that method&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let findAndReplace = (employee) =&amp;gt; {  
  let employeeFound = findEmployee(employee._id);  
  if (employeeFound) {  
    for (var key in employee) {  
      employeeFound[key] = employee[key];  
    }  
  return true;  
  } else {  
    return false;  
  }  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Next, we need to handle PUT request and parse the request body to get the employee object we need to update:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const requestListener = function (req, res) {  
  ....  
  case 'PUT':  
    getRequestBodyAndGenerateResponse(req, res, putMethodHandler);  
    break;  
  ....  
}

const putMethodHandler = (res, body) =&amp;gt; {  
  let reqBody = body;  
  findAndReplace(reqBody);  
  res.writeHead(200);  
  res.end(`The Employee object with id is ${reqBody._id} replaced.`);  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Let’s understand what we did here.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  We defined a method &lt;strong&gt;getRequestBodyAndGenerateResponse&lt;/strong&gt;(req, res, putMethodHandler).&lt;/li&gt;
&lt;li&gt;  This method reads the data from req object by listening for ‘&lt;strong&gt;data&lt;/strong&gt;’ event and append it to one variable body.&lt;/li&gt;
&lt;li&gt;  Once the ‘&lt;strong&gt;end&lt;/strong&gt;’ event is triggered means the request body read completely, it parses the string into JSON and calls the callback function passed to it.&lt;/li&gt;
&lt;li&gt;  This callback function is the one that prepares the response object.&lt;/li&gt;
&lt;li&gt;  In the callback function first, we update the received employee object inside the employee array.&lt;/li&gt;
&lt;li&gt;  Then prepare a response and sent it to the user.&lt;/li&gt;
&lt;/ul&gt;




&lt;h4&gt;
  
  
  7. Writing handler for Http DELETE request
&lt;/h4&gt;

&lt;p&gt;Http DELETE requests are generally for deleting an existing object. In our case, we will delete the received employee object &lt;strong&gt;_id&lt;/strong&gt; from the array. Let’s write code for that method&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let deleteEmployee = (id) =&amp;gt; {  
  let length = employeeData.length;  
  while (length--) {  
    if (employeeData[length]  
    &amp;amp;&amp;amp; employeeData[length]["_id"] === id) {  
      employeeData.splice(length, 1);  
      return true;  
    }  
  }  
  return false;  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Next, we need to handle the DELETE request, get &lt;strong&gt;_id&lt;/strong&gt; of the employee, and delete that object from the array.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const requestListener = function (req, res) {  
  ....  
  case 'PUT':  
    deleteMethodHandler(url, req, res);  
    break;  
  ....  
}

const deleteMethodHandler = (url, req, res) =&amp;gt; {  
  const employeeId = url.substring(1);  
  const response = deleteEmployee(employeeId);  
  res.writeHead(200);  
  res.end(`The employee with id ${employeeId} is deleted.`);  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Let’s understand what we did here.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  First, we found the requested &lt;strong&gt;_id&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;  We pass that &lt;strong&gt;_id&lt;/strong&gt; to &lt;strong&gt;deleteEmployee&lt;/strong&gt; method to delete the employee object&lt;/li&gt;
&lt;li&gt;  If everything goes fine we delete the employee object.&lt;/li&gt;
&lt;li&gt;  Then prepare a response and sent it to the user.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can find the above code &lt;a href="https://github.com/codesprintpro/jshttpserverusingnodejs"&gt;here&lt;/a&gt;. I tried to convert it into a modular format by separating data, methods, and using a module export-import feature of JS.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you enjoyed reading this, don’t forget the like. 👏&lt;br&gt;&lt;br&gt;
Thank you.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>ES5 Function To ES6 Arrow Function</title>
      <dc:creator>Sachin Sarawgi</dc:creator>
      <pubDate>Sun, 14 Jun 2020 04:38:22 +0000</pubDate>
      <link>https://dev.to/sachinsarawgi/es5-function-to-es6-arrow-function-9cf</link>
      <guid>https://dev.to/sachinsarawgi/es5-function-to-es6-arrow-function-9cf</guid>
      <description>&lt;p&gt;&lt;br&gt;
&lt;em&gt;With the introduction to ES6, there are many new features added in JavaScript one of them is Arrow Function.&lt;/em&gt; In this blog, we will discuss in detail how to use this feature. It’s best suited for someone new to JavaScript.&lt;/p&gt;

&lt;h3&gt;
  
  
  Topic Covered
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  Introduction to Arrow Function&lt;/li&gt;
&lt;li&gt;  Arrow Function Without Parameter&lt;/li&gt;
&lt;li&gt;  Arrow Function With Parameter&lt;/li&gt;
&lt;li&gt;  Return Value from Arrow Function&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fuezuk5xln4rfq82xisis.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fuezuk5xln4rfq82xisis.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Introduction to Arrow Function
&lt;/h4&gt;

&lt;p&gt;The arrow function concept was introduced in ES6. With the help of this, we can write a shorter and concise syntax for a normal function which we used to write in ES5.&lt;/p&gt;

&lt;p&gt;Normal function to print “Hello World”&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var printer = function(){  
  console.log("Hello World");  
}  
printer();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Arrow function to print “Hello World”&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var printer = () =&amp;gt; {  
  console.log("Hello World");  
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Note: In arrow function, if there is only one statement then we don't even need to use ‘{}’ curly braces.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var printer = () =&amp;gt; console.log("Hello World");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h4&gt;
  
  
  Arrow Function Without Parameter
&lt;/h4&gt;

&lt;p&gt;This type of arrow function is similar to what we have written in the above examples. But remember:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Even if there are no arguments to the function ‘()’ parenthesis should be there.&lt;/li&gt;
&lt;li&gt;  If the function is of single statement ‘{}’ curl braces can be removed&lt;/li&gt;
&lt;li&gt;  If the function has multiple statements the ‘{}’ curl braces is a must.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;
  
  
  Arrow Function With Parameter
&lt;/h4&gt;

&lt;p&gt;In this type of arrow function, we pass the arguments inside the ‘()’ parathesis, it’s just that function keyword is not there.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var getSum = (myVar1, myVar2) =&amp;gt; {  
  var result = myVar1 + myVar2;  
  return result;  
}  
getSum(5, 10);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We can write the above function is a single line by directly returning the result.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var getSum = (myVar1, myVar2) =&amp;gt; { return myVar1 + myVar2 };  
getSum(5, 10);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Note: The &lt;em&gt;return&lt;/em&gt; keyword is by default in a single line statement in case of arrow function. That’s the reason we didn’t remove the &lt;em&gt;return&lt;/em&gt; keyboard, as in a single line statement without curl braces return keyword throws an exception.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var getSum = (myVar1, myVar2) =&amp;gt; return myVar1 + myVar2;  
//this will throw exception saying unexpected token 'return'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If we want we have to remove the return keyword and ‘{}’ curl braces together.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var getSum = (myVar1, myVar2) =&amp;gt; myVar1 + myVar2;  
getSum(5, 10);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h4&gt;
  
  
  Return Value from Arrow Function
&lt;/h4&gt;

&lt;p&gt;In the case of multiple line functions, we have to write the return keyword explicitly for returning a value.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var getIteratorSum = (itr) =&amp;gt; {  
  var result = 0;  
  for(var i =0 ;i &amp;lt;itr; i++){  
    result += i;  
  }  
  return result;  
}  
console.log(getIteratorSum(5));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This ends our discussion on the arrow function feature in ES6.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Follow me over Medium for such articles  &lt;a href="https://medium.com/@codesprintpro" rel="noopener noreferrer"&gt;@CodeSprintPro&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>REST API With NodeJS Using SQLite3 and Express</title>
      <dc:creator>Sachin Sarawgi</dc:creator>
      <pubDate>Fri, 12 Jun 2020 17:55:20 +0000</pubDate>
      <link>https://dev.to/sachinsarawgi/rest-api-with-nodejs-using-sqlite3-and-express-l3c</link>
      <guid>https://dev.to/sachinsarawgi/rest-api-with-nodejs-using-sqlite3-and-express-l3c</guid>
      <description>&lt;p&gt;In this blog, we will discuss how to create REST API which provides CRUD functionality to an entity using NodeJS.&lt;/p&gt;

&lt;h3&gt;
  
  
  Topics Covered
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  What is REST&lt;/li&gt;
&lt;li&gt;  What is CRUD&lt;/li&gt;
&lt;li&gt;  REST &amp;amp; CRUD Together&lt;/li&gt;
&lt;li&gt;  REST Standards and Response Code Recommendation&lt;/li&gt;
&lt;li&gt;  Setting Up Database and Initial NodeJs File&lt;/li&gt;
&lt;li&gt;  GET API With NodeJS&lt;/li&gt;
&lt;li&gt;  POST API With NodeJS&lt;/li&gt;
&lt;li&gt;  PUT API With NodeJS&lt;/li&gt;
&lt;li&gt;  DELETE API With NodeJS&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you already know the concept you can jump onto the &lt;em&gt;Setting Up Database and Initial NodeJS File&lt;/em&gt; section.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is REST
&lt;/h3&gt;

&lt;p&gt;REST stands for Representation State Transfer, we can think it as an architectural style standard which simplifies the communication between computer systems. The computer system which is REST compliant also called REStful systems.&lt;/p&gt;

&lt;p&gt;RESTful systems are stateless and separate the concern of client and server in an HTTP communication protocol.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Separation of Client &amp;amp; Server&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The development of the client and server can take place independently. We&lt;br&gt;&lt;br&gt;
don’t have to bother while changing how each side work.&lt;/p&gt;

&lt;p&gt;Until and unless both sides know which format of the message to send, which is understood by the other side, they can be developed independently.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Statelessness&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Client and Server don’t have to know the state of the other side while communicating. They can understand each other messages without knowing anything about the previous message.&lt;/p&gt;

&lt;p&gt;From &lt;a href="https://restfulapi.net/statelessness/"&gt;https://restfulapi.net/statelessness/&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Each request from the client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client. client is responsible for storing and handling all application state related information on client side.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The statelessness behavior gives the power to scale, be a reliable and quick performer. &lt;a href="https://restfulapi.net/"&gt;For more on REST.&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  What is CRUD
&lt;/h3&gt;

&lt;p&gt;When we build API, we need it to provide four basic functionalities namely Create, Read, Update, and Delete a resource. The CRUD paradigm is common in constructing web applications because it provides a memorable framework for reminding developers of how to construct full, usable models.&lt;/p&gt;

&lt;h3&gt;
  
  
  REST &amp;amp; CRUD Together
&lt;/h3&gt;

&lt;p&gt;In the REST API, each verb in CRUD relates to a specific HTTP method.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Create — POST&lt;/li&gt;
&lt;li&gt;  Read — GET&lt;/li&gt;
&lt;li&gt;  Update — PUT&lt;/li&gt;
&lt;li&gt;  Delete — Delete&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The above four are the basic building blocks for a persistent backend system.&lt;/p&gt;

&lt;h3&gt;
  
  
  REST Standards and Response Code Recommendation
&lt;/h3&gt;

&lt;p&gt;Let us take an entity type for an example and explain the recommendation based on that.&lt;/p&gt;

&lt;p&gt;We will take an Employee entity here. DB Diagram for the &lt;em&gt;employee&lt;/em&gt; table.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--B2BltCZD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/uir4atbn4zkofpws5os9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--B2BltCZD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/uir4atbn4zkofpws5os9.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Before writing code let us understand the different REST API which we will write for employee resources.&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Create REST API Request&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;To create a resource in employees entity we use an HTTP POST request. POST creates a new resource of the specified resource type.&lt;/p&gt;

&lt;p&gt;Before we start discussing let’s fix the message format we will communicate to JSON.&lt;/p&gt;

&lt;p&gt;Let’s imagine employee resource, we want to add a new employee to the existing lists.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Request Format&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Request format will have always the resource name in plural format. Like here we are working on &lt;em&gt;employee&lt;/em&gt; resource the API should point to &lt;em&gt;employees&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://localhost:8080/employees/"&gt;http://localhost:8080/employees/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Request Body&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The body will be the new employee object detail in JSON format. In the case of a POST request, we will not pass the primary key as that will be automatically generated by the system.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{  
  "last_name": "Sarawgi",  
  "first_name": "Sachin",  
  "title": "Software Developer",  
  "address": "India",  
  "country_code": "IN"  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;HTTP Method Type:&lt;/strong&gt; POST&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Response Body&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The response body of a POST request should contain the newly created resource with the primary key.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{  
  "employee_id": 1,  
  "last_name": "Sarawgi",  
  "first_name": "Sachin",  
  "title": "Software Developer",  
  "address": "India",  
  "country_code": "IN"  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Response Code:&lt;/strong&gt; When we try to create a new resource and it’s successful then the server should return 201 (CREATED) response code.&lt;/p&gt;




&lt;h4&gt;
  
  
  GET REST API Request
&lt;/h4&gt;

&lt;p&gt;To read a particular item/row in an employee entity we use an HTTP GET request. Reading a resource should never change any information. GET requests can be used to read a particular item in a resource or read the whole list of items.&lt;/p&gt;

&lt;p&gt;Let’s imagine employee resource, we want to read a particular employee from the existing lists.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Request Format&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For reading a particular employee we will pass the primary key of the item.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://localhost:8080/employees/1"&gt;http://localhost:8080/employees/1&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For reading all the employees from the employee resource list.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://localhost:8080/employees/"&gt;http://localhost:8080/employees/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Request Body:&lt;/strong&gt; In the case of GET request, we don't send any request body.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;HTTP Method Type:&lt;/strong&gt; GET&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Response Body&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The response body of a GET request should contain the employee object we request for.&lt;/p&gt;

&lt;p&gt;If we requested for a particular employee it should be like:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{  
  "employee_id": 1,  
  "last_name": "Sarawgi",  
  "first_name": "Sachin",  
  "title": "Software Developer",  
  "address": "India",  
  "country_code": "IN"  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;If we requested for all employees, the response should be an array of employee&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[  
  {  
    "employee_id": 1,  
    "last_name": "Sarawgi",  
    "first_name": "Sachin",  
    "title": "Software Developer",  
    "address": "India",  
    "country_code": "IN"  
  },  
  {  
    "employee_id": 2,  
    "last_name": "Chandan",  
    "first_name": "Praveen",  
    "title": "Senior Software Developer",  
    "address": "India",  
    "country_code": "IN"  
  }  
]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Response Code:&lt;/strong&gt; When we try to read a resource and it’s successful then the server should return 200 (OK) response code.&lt;/p&gt;




&lt;h4&gt;
  
  
  Update REST API Request
&lt;/h4&gt;

&lt;p&gt;To update a resource in employees entity we use an HTTP PUT request. PUT updates an already existing resource of the specified resource type.&lt;/p&gt;

&lt;p&gt;Let’s imagine employee resource, we want to update an old employee with the new title.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Request Format&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Request format will have always the resource name in plural format. Like here we are working on &lt;em&gt;employee&lt;/em&gt; resources the API should point to &lt;em&gt;employees&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://localhost:8080/employees/"&gt;http://localhost:8080/employees/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Request Body&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The body will be the old employee object detail in JSON format. In the case of a PUT request, we will pass the primary key as that will be needed to identify the resource.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{  
  "employee_id": 1,  
  "last_name": "Sarawgi",  
  "first_name": "Sachin",  
  "title": "Senior Software Developer",  
  "address": "India",  
  "country_code": "IN"  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;HTTP Method Type:&lt;/strong&gt; PUT&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Response Body:&lt;/strong&gt; The response body of a PUT request is not necessary if asked we can return the updated employee object.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Response Code:&lt;/strong&gt; When we try to update an old resource and it’s successful then the server should return 200 (OK) response code.&lt;/p&gt;




&lt;h4&gt;
  
  
  DELETE REST API Request
&lt;/h4&gt;

&lt;p&gt;To delete a particular item/row in an employee entity we use an HTTP DELETE request. It is used to remove a resource from the system.&lt;/p&gt;

&lt;p&gt;Let’s imagine employee resource, we want to delete a particular employee from the existing lists.&lt;/p&gt;

&lt;p&gt;We should never provide bulk delete functionality.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Request Format&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For deleting a particular employee we will pass the primary key of the item.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://localhost:8080/employees/1"&gt;http://localhost:8080/employees/1&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Request Body:&lt;/strong&gt; In the case of DELETE request, we don’t send any request body.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;HTTP Method Type:&lt;/strong&gt; DELETE&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Response Body:&lt;/strong&gt; The response body of a DELETE request is not necessary.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Response Code:&lt;/strong&gt; When we try to delete an old resource and it’s successful then the server should return 200 (OK) response code.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1IKwW9ds--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/ed8c5vbaw05plxl3gecq.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1IKwW9ds--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/ed8c5vbaw05plxl3gecq.jpeg" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Setting Up Database and Initial NodeJs File
&lt;/h3&gt;

&lt;p&gt;Create a workspace in your local machine where you will write all the code. Type &lt;code&gt;npm init&lt;/code&gt; to set up the project with basic details. Run below command inside the folder.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Run&lt;code&gt;npm install sqlite3 --save&lt;/code&gt; to use the sqlite3 package in our project&lt;/li&gt;
&lt;li&gt;  Run&lt;code&gt;npm install express --save&lt;/code&gt; to use express package from npm&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Create a file with the name &lt;code&gt;restwithnodejssqlite3.js&lt;/code&gt; and write below code:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const sqlite3 = require('sqlite3');
const express = require("express");
var app = express();

const HTTP_PORT = 8000
app.listen(HTTP_PORT, () =&amp;gt; {
    console.log("Server is listening on port " + HTTP_PORT);
});

const db = new sqlite3.Database('./emp_database.db', (err) =&amp;gt; {
    if (err) {
        console.error("Erro opening database " + err.message);
    } else {

        db.run('CREATE TABLE employees( \
            employee_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\
            last_name NVARCHAR(20)  NOT NULL,\
            first_name NVARCHAR(20)  NOT NULL,\
            title NVARCHAR(20),\
            address NVARCHAR(100),\
            country_code INTEGER\
        )', (err) =&amp;gt; {
            if (err) {
                console.log("Table already exists.");
            }
            let insert = 'INSERT INTO employees (last_name, first_name, title, address, country_code) VALUES (?,?,?,?,?)';
            db.run(insert, ["Chandan", "Praveen", "SE", "Address 1", 1]);
            db.run(insert, ["Samanta", "Mohim", "SSE", "Address 2", 1]);
            db.run(insert, ["Gupta", "Pinky", "TL", "Address 3", 1]);
        });
    }
});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Run the file using &lt;code&gt;npm restwithnodejs.js&lt;/code&gt; , it will start the server on port 8000. It will also create the employee table and insert some sample records in the database.&lt;/p&gt;

&lt;h3&gt;
  
  
  GET API With NodeJS
&lt;/h3&gt;

&lt;p&gt;Now the server is up and running and the table is ready with some sample database.&lt;/p&gt;

&lt;p&gt;Next step is to query the table to get a particular employee based on the &lt;code&gt;employee_id&lt;/code&gt; .&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.get("/employees/:id", (req, res, next) =&amp;gt; {
    var params = [req.params.id]
    db.get(`SELECT * FROM employees where employee_id = ?`, [req.params.id], (err, row) =&amp;gt; {
        if (err) {
          res.status(400).json({"error":err.message});
          return;
        }
        res.status(200).json(row);
      });
});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;We can also write API for getting all the employee we can&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.get("/employees", (req, res, next) =&amp;gt; {
    db.all("SELECT * FROM employees", [], (err, rows) =&amp;gt; {
        if (err) {
          res.status(400).json({"error":err.message});
          return;
        }
        res.status(200).json({rows});
      });
});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;### POST API With NodeJS&lt;br&gt;
  After getting an employee by id, we need something by which we can insert an employee&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.post("/employees/", (req, res, next) =&amp;gt; {
    var reqBody = re.body;
    db.run(`INSERT INTO employees (last_name, first_name, title, address, country_code) VALUES (?,?,?,?,?)`,
        [reqBody.last_name, reqBody.first_name, reqBody.title, reqBody.address, reqBody.country_code],
        function (err, result) {
            if (err) {
                res.status(400).json({ "error": err.message })
                return;
            }
            res.status(201).json({
                "employee_id": this.lastID
            })
        });
});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h3&gt;
  
  
  PUT API With NodeJS
&lt;/h3&gt;

&lt;p&gt;Now suppose we want to update the existing employee.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.patch("/employees/", (req, res, next) =&amp;gt; {
    var reqBody = re.body;
    db.run(`UPDATE employees set last_name = ?, first_name = ?, title = ?, address = ?, country_code = ? WHERE employee_id = ?`,
        [reqBody.last_name, reqBody.first_name, reqBody.title, reqBody.address, reqBody.country_code, reqBody.employee_id],
        function (err, result) {
            if (err) {
                res.status(400).json({ "error": res.message })
                return;
            }
            res.status(200).json({ updatedID: this.changes });
        });
});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h3&gt;
  
  
  DELETE API With NodeJS
&lt;/h3&gt;

&lt;p&gt;Code for deleting a particular employee from the table&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.delete("/employees/:id", (req, res, next) =&amp;gt; {
    db.run(`DELETE FROM user WHERE id = ?`,
        req.params.id,
        function (err, result) {
            if (err) {
                res.status(400).json({ "error": res.message })
                return;
            }
            res.status(200).json({ deletedID: this.changes })
        });
});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This ends our coding part, we can run the file using &lt;code&gt;node restwithnodejssqlite3.js&lt;/code&gt; , try hitting the API using Postman. I hope this helps to understand the concepts of REST, CRUD, and how to write it in terms of coding using NodeJS. &lt;a href="https://github.com/codesprintpro/restapiusingnodejsandsqlite3"&gt;The complete code for the project can be found here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you enjoyed reading this, don’t forget the like. 👏&lt;br&gt;&lt;br&gt;
Thank you.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Follow me over Medium for such articles  &lt;a href="https://medium.com/@codesprintpro"&gt;@CodeSprintPro&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>11 Mantras To Become A Better Programmer</title>
      <dc:creator>Sachin Sarawgi</dc:creator>
      <pubDate>Fri, 12 Jun 2020 15:43:45 +0000</pubDate>
      <link>https://dev.to/sachinsarawgi/11-mantras-to-become-a-better-programmer-4foa</link>
      <guid>https://dev.to/sachinsarawgi/11-mantras-to-become-a-better-programmer-4foa</guid>
      <description>&lt;p&gt;&lt;em&gt;Learn how to become a better programmer in your daily life. Do you want to make yourself a better programmer?&lt;/em&gt; Here are some tips which can guide you on the way.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Never Fear From New Things
&lt;/h2&gt;

&lt;p&gt;You should  &lt;em&gt;never fear to do anything new&lt;/em&gt;  in this world of Software Engineering. If you are not open to trying your hands on something new, it's very difficult to grow as a programmer and  &lt;em&gt;you may get lost in the crowd&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;On the other hand, if you are open to new things you will find your knowledge increasing, confidence rising, and appreciation coming on the way.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Nobody, nobody knows everything, at some point people have to start something from scratch.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;2. Learn Different Programming Language&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;It's okay if your project requires to need you to know Java. One may think if I learn some parts of Java he/she will survive. Sorry but that’s a very wrong notion. What if that project gets closed, what if there are no more projects based on Java (all on web dev in your department). So never ever limit yourself to that one programming language that your project requires.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;You must know the basics of  &lt;em&gt;at least three programming languages in which you should be master of one&lt;/em&gt;. Like you know Java, JS, and Python but you are a master in java.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  3. Clear Your Basics
&lt;/h2&gt;

&lt;p&gt;This is one of the biggest mistakes which people do is they directly jump to the framework instead of studying the basic building behind that framework.&lt;/p&gt;

&lt;p&gt;Not even framework, even if you are working on some projects which have some hi-fi code of JavaScript you must first clear your basics of JavaScript then proceed with it. Because when things get complex believe me these basics will come in handy.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;It’s very good to know jQuery, but if you  &lt;em&gt;don’t know the basics&lt;/em&gt;  of JavaScript on which it is built it may become  &lt;em&gt;difficult to handle if things get complexed&lt;/em&gt;  in the jQuery framework.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  4. Data Structures
&lt;/h2&gt;

&lt;p&gt;Here comes the thing which many don’t bother to even look at. But the world is changing, nowadays if you don’t have an understanding of some common DS and Algos its difficult to even clear the first/second coding rounds on interview.&lt;/p&gt;

&lt;p&gt;Some may say what’s the use of it, I am not going to use it in my coding. DS is not like any programming language, knowing DS &amp;amp; Algos helps you to think  &lt;em&gt;better structure, solution, the efficiency of the code&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Knowing DS will help in your daily basis work, we can give a  &lt;em&gt;more efficient solution&lt;/em&gt;  instead of just giving the solution.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  5. System Design &amp;amp; System Architecture
&lt;/h2&gt;

&lt;p&gt;Lots of companies have their own engineering blog, study them. You will learn how people build their  &lt;em&gt;complex architecture&lt;/em&gt;, how they  &lt;em&gt;scale&lt;/em&gt;  their system to  &lt;em&gt;match such a huge load of customers&lt;/em&gt;  and also new technology which is in fashion.&lt;/p&gt;

&lt;p&gt;Here are some of them  &lt;a href="https://www.zomato.com/blog/category/technology"&gt;Zomato&lt;/a&gt;,  &lt;a href="https://bytes.swiggy.com/"&gt;Swiggy&lt;/a&gt;,  &lt;a href="https://instagram-engineering.com/"&gt;Instagram&lt;/a&gt;,  &lt;a href="https://engineering.fb.com/"&gt;Facebook&lt;/a&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;You will understand complex architecture, how to scale a system, solution specific to scenarious.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  6. Read Code From Github &amp;amp; Try to Understand
&lt;/h2&gt;

&lt;p&gt;Take your favorite language and search in GitHub for open source projects based on that language. Choose any one of an open-source projects, clone it, import it in your favorite IDE. Also, you will learn new frameworks which they may have used with your favorite programming language.&lt;/p&gt;

&lt;p&gt;Plus you can also  &lt;em&gt;contribute to these open source project&lt;/em&gt;, there is no better way to learn than contributing to open source projects. Your code may not get accepted in the first term (if they have high standard) but it's fine that’s how you learn isn't.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;These open-source projects have a  &lt;em&gt;lot of beautiful code&lt;/em&gt;, you will learn a lot of new ways to solve things.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  7. Always in Learning Mode
&lt;/h2&gt;

&lt;p&gt;Sometimes people get lazy and think now they know what requires them to perform and they stop learning. It may happen you are working on Java 8 and suddenly after some years, you found some new X version is released and you are way behind it.&lt;/p&gt;

&lt;p&gt;Industry always demands you to be  &lt;em&gt;updated with the latest&lt;/em&gt;  at least in the technology you worked on.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Keep reading blogs, keep yourself updated with  &lt;em&gt;any new feature or version&lt;/em&gt;  of your favorite programming language.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  8. Build POCs
&lt;/h2&gt;

&lt;p&gt;It’s doesn't matter if someone is watching you or not, do this for your better future. Build POC’s on the new thing you learned, create your repo on Github, and push it. At least you will have something to show in your resume that makes you  &lt;em&gt;stand different from the crowd&lt;/em&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  9. Practice Makes You Perfect
&lt;/h2&gt;

&lt;p&gt;You learn something new today, you tried a basic code it ran now you think you know that stuff and you never checked it back again. Sorry, that’s a wrong belief. It’s very easy to forget the syntax of a new programming language, so try to  &lt;em&gt;practice&lt;/em&gt;  that code  &lt;em&gt;three-four times on different days&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Keep practicing it will make you efficient, increase your productivity, and you will have fewer errors.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  10. Look For A Mentor
&lt;/h2&gt;

&lt;p&gt;If you want to excel in something, look for a mentor whom you think can guide you or who is  &lt;em&gt;subject matter expert&lt;/em&gt;  of it. As they have already gone through that path of mastering they know what mistakes one should avoid, what one should study.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Never feel ashamed of learning from someone who is of lesser experience then you,  &lt;em&gt;learning is never about age, it’s about sharing experience&lt;/em&gt;. If you are getting something new go for it.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  11. Help Others &amp;amp; Let Them Help You
&lt;/h2&gt;

&lt;p&gt;Last but not least if you are a master of something if you know something which others don’t please  &lt;em&gt;share your knowledge&lt;/em&gt;. Don’t let your attitude and ego come over it. Organize KT, Bootcamp within your team, department it will help others in gaining knowledge and you gaining recognition.&lt;/p&gt;

&lt;p&gt;Answers questions on tech social platforms that you know about, write blogs that can help others. Share knowledge it will grow :).&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you enjoyed reading this, don’t forget the like. 👏&lt;br&gt;&lt;br&gt;
Thank you.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Follow me over Medium for such articles  &lt;a href="https://medium.com/@codesprintpro"&gt;@CodeSprintPro&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>career</category>
    </item>
    <item>
      <title>Promise to Learn Promises in JavaScript</title>
      <dc:creator>Sachin Sarawgi</dc:creator>
      <pubDate>Fri, 12 Jun 2020 15:39:23 +0000</pubDate>
      <link>https://dev.to/sachinsarawgi/promise-to-learn-promises-in-javascript-1b95</link>
      <guid>https://dev.to/sachinsarawgi/promise-to-learn-promises-in-javascript-1b95</guid>
      <description>&lt;p&gt;&lt;em&gt;Stuck with callback hell, here is the Promise Object which promises to solve the Callback Function Problems.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;JavaScript is synchronous language by nature. The asynchronous functions like a callback, promise are internal to the JavaScript engine which is part of the browser. For example, Chrome uses the Google &lt;a href="https://v8.dev/"&gt;V8&lt;/a&gt; JavaScript engine. Because of this, all the functionality related to asynchronous is developed in external libraries.&lt;/p&gt;

&lt;p&gt;In JS we can solve asynchronous features using Callback, Promises, Async Await.&lt;/p&gt;

&lt;p&gt;Before we start please read about &lt;a href="https://dev.to/sachinsarawgi/callback-deep-dive-in-javascript-3a1e"&gt;Callback Deep Dive in JavaScript&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Topics Covered
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  What are Promises&lt;/li&gt;
&lt;li&gt;  Which Use Case Solved By Promises&lt;/li&gt;
&lt;li&gt;  Problem With Callback Functions, The Callback Hell&lt;/li&gt;
&lt;li&gt;  How To Write Promise Producer Code&lt;/li&gt;
&lt;li&gt;  Promise Object Properties&lt;/li&gt;
&lt;li&gt;  How To Write Promise Consumer Code&lt;/li&gt;
&lt;li&gt;  Solving Callback Hell With Promises&lt;/li&gt;
&lt;li&gt;### What are Promises&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Promises are JavaScript object introduced in ES6 onwards, which handles the asynchronous result of an operation.&lt;/p&gt;

&lt;p&gt;It consists of producer code which produces a result/response after some duration of time from the time when it’s called. The other part is called consumer code which consumes the result/response generated by producer code.&lt;/p&gt;

&lt;h3&gt;
  
  
  Which Use Case Solved By Promises
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt; Suppose we are calling an API, and that API response time is high. That means for processing the response we have to wait till we get the response.&lt;/li&gt;
&lt;li&gt; Suppose we are loading a JavaScript file in a function, and in the next line we are calling a function that is declared inside that script.&lt;/li&gt;
&lt;li&gt; Suppose you want to call another API once you get the first response, another one after you get a second API response. This type of requirement is called &lt;em&gt;callback chaining&lt;/em&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you know Callback functionality would seem similar based on the above scenario, indeed it is but there are some major problems with a Callback function which is handled by Promise very gracefully. One of them is called &lt;em&gt;Callback Hell,&lt;/em&gt; discussed in the next section_._&lt;/p&gt;

&lt;h3&gt;
  
  
  Problem With Callback Functions, The Callback Hell
&lt;/h3&gt;

&lt;p&gt;A callback function easy to understand when we don’t have callback chaining or callback after callback. Let’s take a simple example, where there is only one callback function&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getAPIRequest(_callbackOnSuccess_, _callbackOnError_){  var getReq = new XMLHttpRequest();  
  getReq.open("GET", "https://reqres.in/api/users?page=2");  
  getReq.send();  
  getReq.onload = () =&amp;gt; {  
    alert("The response is " + request.response);  
  }  
}
getAPIRequest();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;In the above code, we called a GET API and once the response is received we are calling &lt;em&gt;processSuccessResponse&lt;/em&gt; method as a callback. It seems correct, but suppose we want to call the second API once we get the first API response, similarly the third API when we get the first API response. Let’s see it as an example, we will be calling the same API for now:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getAPIRequest(_callbackOnSuccess_, _callbackOnError_){    
  var getReq1 = new XMLHttpRequest();  
  getReq1.open("GET", "https://reqres.in/api/users?page=2");  
  getReq1.send();  
  getReq1.onload = () =&amp;gt; {  
    alert("The response is " + request.response);  
    var getReq2 = new XMLHttpRequest();  
    getReq2.open("GET", "https://reqres.in/api/users?page=2");  
    getReq2.send();  
    getReq2.onload = () =&amp;gt; {  
      alert("The response is " + request.response);  
      var getReq3 = new XMLHttpRequest();  
      getReq3.open("GET", "https://reqres.in/api/users?page=2");  
      getReq3.send();  
      getReq3.onload = () =&amp;gt; {  
        alert("The response is " + request.response);  
        //another api call or some other processing  
      }  
    }  
  }  
}
getAPIRequest();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;As we can see this thing can grow very large and it will become difficult to read, maintain the code, and understand if any issues come later on.&lt;/p&gt;

&lt;p&gt;The promise is the answer to the above problem, it has consumer code that is kind of callback, and all consumers can be written separately and they will be executed one after another.&lt;/p&gt;

&lt;h3&gt;
  
  
  How To Write Promise Producer Code
&lt;/h3&gt;

&lt;p&gt;Promise producer code is the part that produces some result or output, which later can be processed by a consumer. Let’s try to call a GET API which is like our producer code and its result will the response which we are getting from the API.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getFirstAPIRequest() {  
  return new Promise(function(resolve, reject) {  
    var getReq = new XMLHttpRequest();  
    getReq.open("GET", "[https://reqres.in/api/users?page=2](https://reqres.in/api/users?page=2)");  
    getReq.send();  
    getReq.onload = () =&amp;gt; {  
      if(getReq.status == 200){  
        resolve(getReq.response);  
      }else{  
        reject(new Error("There was some problem in the request."));  
      }  
    }  
  });  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;em&gt;Note&lt;/em&gt;: Open &lt;a href="https://playcode.io/"&gt;https://playcode.io/&lt;/a&gt; and paste this code. If you want to learn do practice with this code.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The function passed to Promise is called executor, it runs automatically when the promise is created. The resolve and reject are callbacks provided by JavaScript itself.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;When the executor gets the result we can call these callbacks depending on our requirement. Like in our case we called &lt;em&gt;resolve&lt;/em&gt; in case of response status is 200 else we are calling &lt;em&gt;reject&lt;/em&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Promise Object Properties
&lt;/h3&gt;

&lt;p&gt;The Promise object created using the new keyboard has two properties &lt;em&gt;state&lt;/em&gt; and &lt;em&gt;result&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--oVC_n6D2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1600/1%2Ak2euAUq6vkJeVvTNNOcCEQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oVC_n6D2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1600/1%2Ak2euAUq6vkJeVvTNNOcCEQ.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;They change their values as follows&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;em&gt;state&lt;/em&gt; will be pending at first, if &lt;em&gt;resolve&lt;/em&gt; is called it will change to &lt;em&gt;resolved state&lt;/em&gt; else if &lt;em&gt;reject&lt;/em&gt; is called it will change to &lt;em&gt;rejected state&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;  &lt;em&gt;result&lt;/em&gt; will be undefined at first, &lt;em&gt;response&lt;/em&gt; when &lt;em&gt;resolve(response)&lt;/em&gt; is called else &lt;em&gt;error&lt;/em&gt; when &lt;em&gt;reject(error)&lt;/em&gt; is called.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Tgtxurme--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1600/1%2AUNw3kNwilaTwZ3w-5pZuQQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Tgtxurme--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1600/1%2AUNw3kNwilaTwZ3w-5pZuQQ.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  How To Write Promise Consumer Code
&lt;/h3&gt;

&lt;p&gt;If we want to consume response, we can do that in three ways in Promise using then, catch, and finally.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;then&lt;/strong&gt; Consumer Code&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;em&gt;then&lt;/em&gt; method of Promise accepts two function arguments, the first one is executed when &lt;em&gt;resolve&lt;/em&gt; is called and the second one is executed when &lt;em&gt;reject&lt;/em&gt; is called.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getFirstAPIRequest() {  
  return new Promise(function(resolve, reject) {  
    var getReq = new XMLHttpRequest();  
    getReq.open("GET", "[https://reqres.in/api/users?page=2](https://reqres.in/api/users?page=2)");  
    getReq.send();  
    getReq.onload = () =&amp;gt; {  
      if(getReq.status == 200){  
        resolve(getReq.response);  
      }else{  
        reject(new Error("There was some problem in the request."));  
      }  
    }  
  });  
}
getFirstAPIRequest()  
  .then((response) =&amp;gt; console.log(response), (error) =&amp;gt; console.log  
("Cannot process response"));
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This will produce the following output.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bW07BKVV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1600/1%2AyYfbLVLYlawxuzyaBVJR3A.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bW07BKVV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1600/1%2AyYfbLVLYlawxuzyaBVJR3A.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If we only want to consume resolve callback we can remove second method definition:&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getFirstAPIRequest()  
  .then((response) =&amp;gt; console.log(response));

_If we only want to consume reject callback we can pass null as the first argument and second any function definition._

getFirstAPIRequest().then(null, (error) =&amp;gt; console.log("Cannot process response"));
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;catch&lt;/strong&gt; Consumer Code&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;For handling reject callback promise has one special method called catch&lt;/em&gt;. We can write our definition inside it, which will be called only in case when &lt;em&gt;reject&lt;/em&gt; callback is called.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getFirstAPIRequest().catch((errorMsg) =&amp;gt; console.log(errorMsg));
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;finally&lt;/strong&gt; Consumer Code&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;There may be some cases where we want to close some resources before completing the callback.&lt;/em&gt; Then we use finally, it has only function definition (without any arguments) which will always be called. Once completed the execution will be passed to next function.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getFirstAPIRequest()  
  .finally(() =&amp;gt; console.log("Closing important resources))  
  .then((response) =&amp;gt; console.log(response), (error) =&amp;gt; console.log  
("Cannot process response"));
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;em&gt;Now suppose callback chaining case where we want to call another API on based on the response from the first API.&lt;/em&gt; Let’s see an example:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getFirstAPIRequest() {  
  console.log("Processing first call");  
  return new Promise(function(resolve, reject) {  
    var getReq = new XMLHttpRequest();  
    getReq.open("GET", "[https://reqres.in/api/users?page=2](https://reqres.in/api/users?page=2)");  
    getReq.send();  
    getReq.onload = () =&amp;gt; {  
      resolve(getReq.response);  
    }  
  });  
}
function getSecondAPIRequest(firstResponse) {  
  //do some processing on response, here I am passing the first simply  
  console.log("Processing second call");  
  return new Promise(function(resolve, reject) {  
    var getReq = new XMLHttpRequest();  
    getReq.open("GET", "[https://reqres.in/api/users?page=2](https://reqres.in/api/users?page=2)");  
    getReq.send();  
    getReq.onload = () =&amp;gt; {  
      resolve(getReq.response);  
    }  
  });  
}
getFirstAPIRequest()  
  .then((response) =&amp;gt; getSecondAPIRequest(response))  
  .then((response) =&amp;gt; console.log(response));
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This will produce the following output.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1zPs-EJu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1600/1%2AKYDUIoCDxVTl-9Loya58UQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1zPs-EJu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1600/1%2AKYDUIoCDxVTl-9Loya58UQ.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I hope all the above examples will make you understand what Promise is in JavaScript, how it is better then Callback as it gracefully handles Callback Hell.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Follow me over Medium for such articles  &lt;a href="https://medium.com/@codesprintpro"&gt;@CodeSprintPro&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
    </item>
    <item>
      <title>Top 10 Free Data Structure Courses</title>
      <dc:creator>Sachin Sarawgi</dc:creator>
      <pubDate>Fri, 12 Jun 2020 15:21:41 +0000</pubDate>
      <link>https://dev.to/sachinsarawgi/top-10-free-data-structure-courses-2l37</link>
      <guid>https://dev.to/sachinsarawgi/top-10-free-data-structure-courses-2l37</guid>
      <description>&lt;p&gt;In this blog, I will be mentioning some of the resources for Data Structure that have &lt;strong&gt;&lt;em&gt;quality content plus free&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Algorithm and Data Structure are two of the most important things required if you want to clear an interview for big and high paying product-based companies.&lt;/p&gt;

&lt;p&gt;Also, someone who has good knowledge of the above two will take better decision while implementing a solution and write code which can handle incremental changes in a better way.&lt;/p&gt;

&lt;p&gt;Some of the popular concepts of DS and Algos array, linked list, circular linked list, double linked list, binary search tree, graph, heap, stack, queue, etc.&lt;/p&gt;

&lt;h4&gt;
  
  
  1. &lt;a href="https://www.coursera.org/specializations/data-structures-algorithms"&gt;Data Structures and Algorithms Specialization&lt;/a&gt; (Basic to Intermediate)
&lt;/h4&gt;

&lt;p&gt;This course is from Coursera. This is a specialization type of course so instead of one course, this is divided into four separate courses. Although for getting the certification you need to pay, if you are looking for knowledge you can attend this course for free.&lt;/p&gt;

&lt;p&gt;This course is offered by UNIVERSITY OF CALIFORNIA SAN DIEGO.&lt;/p&gt;

&lt;p&gt;The four different parts of the course:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;a href="https://www.coursera.org/learn/algorithmic-toolbox?specialization=data-structures-algorithms"&gt;&lt;strong&gt;Algorithmic Toolbox&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;:&lt;/strong&gt; The course covers basic algorithmic techniques and ideas for computational problems arising frequently in practical applications: sorting and searching, divide and conquer, greedy algorithms, dynamic programming.&lt;/li&gt;
&lt;li&gt;  &lt;a href="https://www.coursera.org/learn/data-structures?specialization=data-structures-algorithms"&gt;&lt;strong&gt;Data Structures&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;:&lt;/strong&gt; In this course, they will consider the common data structures that are used in various computational problems. Also, you will learn how these data structures are implemented in different programming languages.&lt;/li&gt;
&lt;li&gt;  &lt;a href="https://www.coursera.org/learn/algorithms-on-graphs?specialization=data-structures-algorithms"&gt;&lt;strong&gt;Algorithms on Graphs&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;:&lt;/strong&gt; In this course, you will first learn what a graph is and what are some of the most important properties. Then you’ll learn several ways to traverse graphs and how you can do useful things while traversing the graph in some order.&lt;/li&gt;
&lt;li&gt;  &lt;a href="https://www.coursera.org/learn/algorithms-on-strings?specialization=data-structures-algorithms"&gt;&lt;strong&gt;Algorithms on Strings&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;:&lt;/strong&gt; We search for information using textual queries, we read websites, books, e-mails. All those are strings from the point of view of computer science. In this course, you will learn the string algorithm which search engines use.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  2. &lt;a href="https://www.coursera.org/specializations/algorithms"&gt;Algorithms Specialization&lt;/a&gt; (Advanced)
&lt;/h4&gt;

&lt;p&gt;This course is from Coursera. This is a specialization type of course so instead of one course, this is divided into four separate courses. Although for getting the certification you need to pay, if you are looking for knowledge you can attend this course for free.&lt;/p&gt;

&lt;p&gt;This course is very much at the advanced level then compare to the above specialization. So I would say first go for &lt;a href="https://www.coursera.org/specializations/data-structures-algorithms"&gt;Data Structures and Algorithms Specialization&lt;/a&gt; then select this one.&lt;/p&gt;

&lt;p&gt;This course is offered by Stanford.&lt;/p&gt;

&lt;p&gt;The four different parts of the course:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;a href="https://www.coursera.org/learn/algorithms-divide-conquer"&gt;&lt;strong&gt;Divide and Conquer, Sorting and Searching, and Randomized Algorithms&lt;/strong&gt;&lt;/a&gt;: The primary topics in this part of the specialization are: asymptotic (“Big-oh”) notation, sorting and searching, divide and conquer (master method, integer, and matrix multiplication, closest pair), and randomized algorithms (QuickSort, contraction algorithm for min cuts).&lt;/li&gt;
&lt;li&gt;  &lt;a href="https://www.coursera.org/learn/algorithms-graphs-data-structures"&gt;&lt;strong&gt;Graph Search, Shortest Paths, and Data Structures&lt;/strong&gt;&lt;/a&gt;: The primary topics in this part of the specialization are: data structures (heaps, balanced search trees, hash tables, bloom filters), graph primitives (applications of breadth-first and depth-first search, connectivity, shortest paths), and their applications (ranging from deduplication to social network analysis).&lt;/li&gt;
&lt;li&gt;  &lt;a href="https://www.coursera.org/learn/algorithms-greedy"&gt;&lt;strong&gt;Greedy Algorithms, Minimum Spanning Trees, and Dynamic Programming&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;:&lt;/strong&gt; The primary topics in this part of the specialization are: greedy algorithms (scheduling, minimum spanning trees, clustering, Huffman codes) and dynamic programming (knapsack, sequence alignment, optimal search trees).&lt;/li&gt;
&lt;li&gt;  &lt;a href="https://www.coursera.org/learn/algorithms-npcomplete"&gt;&lt;strong&gt;Shortest Paths Revisited, NP-Complete Problems&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;:&lt;/strong&gt; The primary topics in this part of the specialization are: shortest paths (Bellman-Ford, Floyd-Warshall, Johnson), NP-completeness and what it means for the algorithm designer, and strategies for coping with computationally intractable problems (analysis of heuristics, local search).&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  3. &lt;a href="https://www.coursera.org/learn/algorithms-part1"&gt;&lt;strong&gt;Algorithms 1&lt;/strong&gt;&lt;/a&gt; &lt;strong&gt;(Basic)&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;This course is from Coursera. This is not a specialization, it’s a separate course. This course is free for everyone also there will be no certification given to anyone.&lt;/p&gt;

&lt;p&gt;This course is offered by Princeton University.&lt;/p&gt;

&lt;p&gt;This course covers the essential information that every serious programmer needs to know about algorithms and data structures, with emphasis on applications and scientific performance analysis of Java implementations. Part I &lt;em&gt;covers elementary data structures, sorting, and searching algorithms&lt;/em&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  4. &lt;a href="https://www.coursera.org/learn/algorithms-part2"&gt;Algorithms 2&lt;/a&gt; (Intermediate)
&lt;/h4&gt;

&lt;p&gt;This course is from Coursera. This is not a specialization, it’s a separate course. This course is free for everyone also there will be no certification given to anyone.&lt;/p&gt;

&lt;p&gt;This course is offered by Princeton University.&lt;/p&gt;

&lt;p&gt;This course covers the essential information that every serious programmer needs to know about algorithms and data structures, with emphasis on applications and scientific performance analysis of Java implementations. Part II &lt;em&gt;focuses on graph- and string-processing algorithms&lt;/em&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  5. &lt;a href="https://www.udacity.com/course/data-structures-and-algorithms-in-python--ud513"&gt;Intro to Data Structures and Algorithms&lt;/a&gt; (Basic)
&lt;/h4&gt;

&lt;p&gt;This course is from Udacity. This course will cover the following topics &lt;em&gt;data structures and algorithms Searching &amp;amp; Sorting, Maps &amp;amp; Hashing, Graph, Trees&lt;/em&gt;. Also, this course will cover some case studies, introduce you to technical interviewing techniques, and practice interviews.&lt;/p&gt;

&lt;p&gt;It’s good for the people who are new to DS and know a little bit of Python, as the coding will be in Python programming language.&lt;/p&gt;

&lt;h4&gt;
  
  
  6. &lt;a href="https://www.edx.org/course/algorithms-and-data-structures"&gt;Algorithms and Data Structures&lt;/a&gt; (Basic)
&lt;/h4&gt;

&lt;p&gt;It’s a free course from eds. Although for getting the certification you need to pay, if you are looking for knowledge you can attend this course for free.&lt;/p&gt;

&lt;p&gt;This course is offered by Microsoft.&lt;/p&gt;

&lt;p&gt;This course will cover the following topics &lt;em&gt;Algorithmic Analysis, Sorting and Searching of Algorithms, Data Structures, Linked lists, Stacks, Queues&lt;/em&gt;. As it starts from basic it’s good for people with zero or no knowledge of data structures and algorithms.&lt;/p&gt;

&lt;h4&gt;
  
  
  7. &lt;a href="https://practice.geeksforgeeks.org/courses/must-do-interview-prep?vb=144"&gt;&lt;strong&gt;Must Do Interview Preparation&lt;/strong&gt;&lt;/a&gt; &lt;strong&gt;(Basic to Intermediate)&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;This is a free course offered by geeksforgeeks. This course is based on the most frequently asked questions in product-based companies. It will help to boost your preparation for different interview rounds in tech giants. The course will have programming questions from intermediate to advanced level.&lt;/p&gt;

&lt;p&gt;The concepts covered in this course are &lt;em&gt;arrays, String, LinkedList, Stack, Queue with some advance interview-based questions&lt;/em&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  8. &lt;a href="https://www.youtube.com/watch?v=0IAPZzGSbME&amp;amp;list=PLDN4rrl48XKpZkf03iYFl-O29szjTrs_O"&gt;Algorithms&lt;/a&gt; (Basic-Intermediate-Advance)
&lt;/h4&gt;

&lt;p&gt;Though it’s a youtube course, it covers the algorithms from basic to advanced concepts, and obviously its free of cost.&lt;/p&gt;

&lt;p&gt;The concepts covered in this course include &lt;em&gt;divide &amp;amp; conquer, recursion, binary search, heap sort, merge sort, quick sort, Huffman coding, Dijkstra algorithm, 0/1 knapsack, graph, tree, stack, queue, and linked list&lt;/em&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  9. &lt;a href="https://www.udemy.com/course/introduction-to-algorithms-and-data-structures-in-c/"&gt;Introduction to Algorithms and Data structures in C++&lt;/a&gt; (Basic)
&lt;/h4&gt;

&lt;p&gt;It’s a free course from Udemy. It gives concept related to very basic data structures like &lt;em&gt;Fibonacci sequence, Dynamic programming, 0/1 Knapsack problem, Stack, check parenthesis expression questions, Queue&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;It’s good for the people who are new to DS and know a little bit of C++, as the coding will be in C++ programming language.&lt;/p&gt;

&lt;h4&gt;
  
  
  10. &lt;a href="https://www.udemy.com/course/data-structures-part-1-lognacademy/"&gt;Data Structure — Part I&lt;/a&gt; (Basic)
&lt;/h4&gt;

&lt;p&gt;It’s a free course from Udemy. The topics covered in the course are among the most fundamental material in all of computer science. The students will not only understand the working behavior of data structures but also be able to implement those from scratch. The course will cover well-known data structures such as &lt;em&gt;dynamic arrays, linked lists, stacks, queues, and trees&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;It’s good for the people who are new to DS and know a little bit of Java, as the coding will be in Java programming language.&lt;/p&gt;




&lt;p&gt;I hope this blog will help you to get a goods resource for learning Data Structures &amp;amp; Algorithms. I would say start with the basic start type course then go to intermediate and advance one. In this way your learning curve will be much better.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Follow me over Medium for such articles  &lt;a href="https://medium.com/@codesprintpro"&gt;@CodeSprintPro&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>beginners</category>
    </item>
    <item>
      <title>Callback Deep Dive in JavaScript</title>
      <dc:creator>Sachin Sarawgi</dc:creator>
      <pubDate>Fri, 12 Jun 2020 15:15:05 +0000</pubDate>
      <link>https://dev.to/sachinsarawgi/callback-deep-dive-in-javascript-3a1e</link>
      <guid>https://dev.to/sachinsarawgi/callback-deep-dive-in-javascript-3a1e</guid>
      <description>&lt;p&gt;In this blog, we will understand how callback function works in JavaScript and how to write one.&lt;/p&gt;

&lt;h1&gt;
  
  
  Topic Covered
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;  What is a Callback Function?&lt;/li&gt;
&lt;li&gt;  Which Use Case Solved by Callback Function&lt;/li&gt;
&lt;li&gt;  Callback Function Synchronous Execution&lt;/li&gt;
&lt;li&gt;  Callback Function Asynchronous Execution&lt;/li&gt;
&lt;li&gt;  Nesting Callback Function Asynchronous Execution&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is a Callback Function
&lt;/h2&gt;

&lt;p&gt;In JavaScript, functions are first-class objects. Just like we can pass objects to functions, we can pass functions as an argument to another function.&lt;/p&gt;

&lt;p&gt;Now the functions which are passed an argument will execute later, after the function where it is passed already executed. That function is commonly known as Callback Function. Generally, this type of function waits for some event to happen or some timeout then it will get executed.&lt;/p&gt;

&lt;p&gt;Functions that accept another function as an argument is called a higher-order function.&lt;/p&gt;

&lt;p&gt;An understanding of callback is very much necessary.  &lt;em&gt;As event and callback structure is the mechanism by which JavaScript engine is managing multiple overlapped requests for I/O&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;JavaScript is a synchronous language by nature. The event and callback functions are internal to the JavaScript engine which is part of the browser. For example, Chrome uses the Google  &lt;a href="https://v8.dev/"&gt;V8&lt;/a&gt;  JavaScript engine. Because of this, all the functionality related to asynchronous is developed in external libraries.&lt;/p&gt;

&lt;h2&gt;
  
  
  Which Use Case Solved by Callback Function
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt; Suppose we are calling an API, and that API response time is high. That means for processing the response we have to wait till we get the response. Now, we don’t want the user to wait till then, that will be a bad design. Here comes the Callback as a savior.&lt;/li&gt;
&lt;li&gt; Suppose we are loading a JavaScript file in a function, and in the next line we are calling a function that is declared inside that script. This may not work as the script can be not loaded yet.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example solution for 1st case using a callback: We can write the response processing code inside a function, pass that function as an argument to a function that is calling the API. The response processing function will wait till it gets the response to process while the main function will complete its execution and exit. Similarly, we can do something about the second use case.&lt;/p&gt;

&lt;h2&gt;
  
  
  Callback Function Synchronous Execution
&lt;/h2&gt;

&lt;p&gt;Let’s first start with a simple example of a callback function.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function welcome(greetingMsg, callback){  
  console.log("Before calling callback");  
  callback(greetingMsg);  
  console.log("After calling callback");  
}
function sayMyName(greet){  
  console.log(greet + " Professor");  
}
welcome("Hello", sayMyName);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This is one of the simplest examples where the callback function which we passed as an argument will be executed synchronously.&lt;/p&gt;

&lt;p&gt;This may not be an important use case of using Callback Function so let’s jump into asynchronous calling.&lt;/p&gt;

&lt;h2&gt;
  
  
  Callback Function Asynchronous Execution
&lt;/h2&gt;

&lt;p&gt;Let’s take our first use case where we need to wait for the response to the process. We can solve it by callback function async execution.&lt;/p&gt;

&lt;p&gt;Here we will be using XMLHttpRequest object to request an API. XMLHttpRequest object is provided by the browser, it’s built-in browser object. I have used a sample API which will give a JSON response for testing purposes.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getAPIRequest(_callbackOnSuccess_){var getReq = new XMLHttpRequest();  
  getReq.open("GET", "https://reqres.in/api/users?page=2");  
  getReq.send();  
  getReq.onload = () =&amp;gt; {  
    if(getReq.status == 200){  
      callbackOnSuccess(getReq);  
    }  
  }  
}
function processSucessResponse(_request_){  
  alert("The response is " + request.response);  
}
getAPIRequest(processSucessResponse);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Open  &lt;a href="https://playcode.io/"&gt;https://playcode.io/&lt;/a&gt;  and paste this code. You will see it gives a pop up that has the API response.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s---CcnI2ov--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1600/1%2AWahcWJbXboMGk2zJXFb25Q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s---CcnI2ov--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1600/1%2AWahcWJbXboMGk2zJXFb25Q.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;XMLHttpRequest onload is an event that will occur when we get a result from the API. We can register our function for processing the response in the onload event. We are checking if the response code is 200 pass the request object to the callback function which is processSucessResponse. Let’s see how we can process an error response if the status code is 400.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getAPIRequest(_callbackOnSuccess_, _callbackOnError_){

  var getReq = new XMLHttpRequest();  
  getReq.open("GET", "https://reqres.in/api/users?page=2");  
  getReq.send();  
  getReq.onload = () =&amp;gt; {  
    if(getReq.status == 200){  
      callbackOnSuccess(getReq);  
    }else if(getReq.status == 400){  
      callbackOnError();  
    }  
  }  
}
function processSucessResponse(_request_){  
  alert("The response is " + request.response);  
}
function processErrorResponse(){  
  alert("The response has some errors.");  
}
getAPIRequest(processSucessResponse, processErrorResponse);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;If you know ajax it can be easy as follows:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getAPIRequest(_callbackOnSuccess){_  
  ajax("https://reqres.in/api/users?page=2", _callbackOnSuccess_);  
}
function processSucessResponse(_request_){  
  alert("The response is " + request.response);  
}
getAPIRequest(processSucessResponse);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;em&gt;Note&lt;/em&gt;: All the asynchronous functionality in JavaScript is provided by some external framework or library. &lt;em&gt;Whenever JavaScript engine sees an external API call, it will ask the browser this is yours to execute, and whenever you get a response run this code (the callback function code).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The browser then waits for the response to return, whenever it has some response it will schedule the callback function execution by putting it into the event loop.&lt;/em&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Nesting Callback Function Asynchronous Execution
&lt;/h4&gt;

&lt;p&gt;It may happen after getting a response from the first API we may want to fire another request based on the result. This kind of request is like a nested API request. For simplicity, we will be calling the same API.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getAPIRequest(_callbackOnSuccess_, _callbackOnError_){  
  var getReq = new XMLHttpRequest();  
  getReq.open("GET", "https://reqres.in/api/users?page=2");  
  getReq.send();  
  getReq.onload = () =&amp;gt; {  
    if(getReq.status == 200){  
      callbackOnSuccess(getReq, processNestedResponse);  
    }else if(getReq.status == 400){  
      callbackOnError();  
    }  
  }  
}

function processSucessResponse(_request_, _callbackOnSuccess_){  
  alert("The response is " + request.response);  
  var getReq = new XMLHttpRequest();  
  getReq.open("GET", "https://reqres.in/api/users?page=2");  
  getReq.send();  
  getReq.onload = () =&amp;gt; {  
    if(getReq.status == 200){  
      callbackOnSuccess(getReq);  
    }  
  }  
}
function processErrorResponse(){  
  alert("The response has some errors.");  
}
function processNestedResponse(_request_){  
  alert("The response is " + request.response);  
}
getAPIRequest(processSucessResponse, processErrorResponse);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This example explains how we can handle the nested API request.&lt;/p&gt;

&lt;p&gt;I hope this blog gave you a better understanding of what is a callback, when we can use callback and how to write it in JavaScript code.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Follow me over Medium for such articles  &lt;a href="https://medium.com/@codesprintpro"&gt;@CodeSprintPro&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>functional</category>
    </item>
  </channel>
</rss>
