Blog

Datatable

listing.html

<!-- https://datatables.net/examples/server_side/simple.html -->
<!-- https://datatables.net/manual/ajax -->
<!-- https://datatables.net/manual/ajax#Column-data-points -->
<!-- https://stackoverflow.com/questions/64526856/how-to-add-edit-delete-buttons-in-each-row-of-datatable -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
  
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/dataTables.bootstrap5.min.css">

    <script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.6.1.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
    <title>Document</title>
</head>
<body>
<table id="example" class="display table table-striped" style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Address</th>
                <th>Salary</th>
                <th>Action</th>
            </tr>
        </thead>
    </table>
</body>
<script>
    $(document).ready(function () {
    $('#example').DataTable({
        processing: true,
        serverSide: true,
        ajax: 'http://ciacloud.in/juhi/rems/get_employees.php',
        columns: [
            { data: 'name'},
            { data: 'address'},
            { data: 'salary'},
            { 
                data: 'id',
                render: (data,type,row) => {
                    console.log({data,type,row})
                   return `<a href='edit_form.php?id=${data}'>Edit</a> | <a href='delete.php?id=${data}'>Delete</a>`;
                 }
            }
        ],
        columnDefs: [
            { orderable: false, targets: -1 },
            {
                "defaultContent": "-",
                "targets": "_all"
            }],
            order: [0,1,2,3],
    });
});
</script>
</html>

get_employees.php

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$params = $_REQUEST;
header('Access-Control-Allow-Origin: *');

$search = isset($params['search']['value'])  && $params['search']['value'] != '' ? $params['search']['value'] : '';

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $where = '';

  if($search !== '')
	  $where = " name LIKE '$search%' ";
  else
	  $where = " 1 = 1 ";

  $sort_columns = ['name', 'address', 'salary'];
  $sort_column_index = $params['order'][0]['column'];
  $sort_order = isset($params['order'][0]['dir']) && $params['order'][0]['dir'] != 1 ? $params['order'][0]['dir'] : 'desc';

  $order_by = " $sort_columns[$sort_column_index] $sort_order";
	
  $offset = $params['start'];
  $limit = $params['length'];

  $sql = "SELECT * FROM employees WHERE $where ORDER BY $order_by LIMIT $offset, $limit";
  $stmt = $conn->prepare($sql);
  $stmt->execute();

  // set the resulting array to associative
  $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
  $employees = $stmt->fetchAll();

} catch(PDOException $e) {
  echo "Error: " . $e->getMessage();
}

$count_sql = "SELECT COUNT(*) FROM employees WHERE $where";
$result = $conn->prepare($count_sql); 
$result->execute(); 
$totalRecords = $result->fetchColumn(); 

$conn = null;


$json_data = array(
		"draw"            => intval( $params['draw'] ),
		"recordsTotal"    => intval( $totalRecords ),
		"recordsFiltered" => intval($totalRecords),
		"data"            => $employees,
		"count_sql"	=> $count_sql,
		"sql"		=> $sql,
	);

echo json_encode($json_data);

Spring Boot

app.groovy

class Demo {

	public static String foo() {

		return "Hello Spring Boot";
	}

}


class Employee {

	String name;
	int salary;

	public Employee() {
		this.name = "";
		this.salary = 0;
	}

	public Employee(String n, int s) {
		this.name = n;
		this.salary = s;
	}

}


@RestController
class HelloWorld {
  @RequestMapping("/")
  String hello() {
    "Hello JournalDev World."  + Demo.foo();
  }

	@RequestMapping("/emps")
	public List<Employee> getEmps() {
		List<Employee> list = new ArrayList<>();
		list.add(new Employee("Alfi", 20000))
		list.add(new Employee("Nikhil", 30000))
		return list;
	}

	@RequestMapping("/sqr")
	String getSqr(@RequestParam("num") int x) {
		"Square of " + x + " is " + (x * x);
	}

	@RequestMapping("/emp")	
	public ResponseEntity<Employee> readRawJson(@RequestBody Employee e) {
		System.out.println("\n=============="+ e.name +"==============\n");
		return ResponseEntity.ok(e);
	}
}

To run via CLI

spring run app.groovy — –server.port=9000

Ref Link:
https://docs.spring.io/spring-boot/docs/current/reference/html/cli.html

SQL DQL Test 2

  1. list all selling in 2019
  2. count all selling year wise order by selling
  3. select all selling in march month of year 2019
  4. count selling in 22 week of year 2020
  5. select all selling from 1st Feb 2019 to 31st Mar 2019
  6. select all customers who place orders in 2019
  7. select all customers from USA who placed order in 2019
  8. select all customers whose order is on hold
  9. select all customers who placed order in march month only
  10. select top 5 customers from USA (who has maximum orders from country USA)

SQL DQL Test 1

  1. select employees in descending order – salary
  2. select all employees from Mumbai
  3. select all employees having salary more than average salary
  4. select sum of salary from table
  5. select all unique address
  6. select details, salary from table
    (details should be concatenation of name and address)
  7. select names of employees having max salary
  8. select employees having 2nd max salary
  9. count employees by address, order by employee count
    e.g. select count(name,address) from employee
  10. show count of employees from nagpur only
  11. select all employees whose names starts or ends with vowels
  12. find employees having max salary in particular city
  13. select top 5 salaried employees
  14. select 2nd highest salaried employees
  15. show cities having total salary more than 200000
  16. Show all students who appeared for exam
  17. show student, subject and total marks of students whose total marks are more than 80

PHP CRUD CHEAT SHEET

MySQL Schema

CREATE TABLE `users` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `age` int NOT NULL,
  `city` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

REST API

rest_api.php

<?php

header('Access-Control-Allow-Origin: *');

$servername = "localhost";
$username = "diituser";
$password = "%TGBbgt5";
$dbname = "ecom";

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch(PDOException $e) {
  echo "Error: " . $e->getMessage();
}




switch($_SERVER['REQUEST_METHOD']) {
    case 'GET':

        if(isset($_REQUEST['id']) && $_REQUEST['id'] != '') {
            $id = $_REQUEST['id'];
            $sql = "SELECT * FROM users WHERE id = $id";
            $stmt = $conn->prepare($sql);
            $stmt->execute();
            $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $records = $stmt->fetch();
        } else {
            $sql = "SELECT * FROM users";
            $stmt = $conn->prepare($sql);
            $stmt->execute();
            $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $records = $stmt->fetchAll();
        }
        echo json_encode($records);

    case 'DELETE':

        $data = json_decode(file_get_contents('php://input'), true);

        $id = $data["id"];
        $sql = "DELETE FROM users WHERE id = $id";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
        echo json_encode(["result" => "success"]);

    case 'POST':

        $data = json_decode(file_get_contents('php://input'), true);

        $name = $data["name"];
        $age = $data['age'];
        $city = $data['city'];
        $sql = "INSERT INTO `users` (`id`, `name`, `age`, `city`) VALUES (NULL, '$name', '$age', '$city'); ";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
        echo json_encode(["result" => "success"]);

    case 'PUT':

        $data = json_decode(file_get_contents('php://input'), true);

        $id = $data['id'];
        $name = $data["name"];
        $age = $data['age'];
        $city = $data['city'];
        $sql = "UPDATE users SET `name` = '$name', age = '$age', city = '$city' WHERE id = $id";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
        echo json_encode(["result" => "success"]);
}


$conn = null;

FRONT END

script.js

const api_url = "rest_api.php";
function loadData(records = []) {
  var table_data = "";
  for (let i = 0; i < records.length; i++) {
    table_data += `<tr>`;
    table_data += `<td>${records[i].name}</td>`;
    table_data += `<td>${records[i].age}</td>`;
    table_data += `<td>${records[i].city}</td>`;
    table_data += `<td>`;
    table_data += `<a href="edit.php?id=${records[i].id}"><button class="btn btn-primary">Edit</button></a>`;
    table_data += "&nbsp;&nbsp;";
    table_data += `<button class="btn btn-danger" onclick=deleteData('${records[i].id}')>Delete</button>`;
    table_data += `</td>`;
    table_data += `</tr>`;
  }
  //console.log(table_data);
  document.getElementById("tbody").innerHTML = table_data;
}
function getData() {
  fetch(api_url)
    .then((response) => response.json())
    .then((data) => {
      console.table(data);
      loadData(data);
    });
}
function getDataById(id) {
  fetch(`${api_url}?id=${id}`)
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
      document.getElementById("id").value = data.id;
      document.getElementById("name").value = data.name;
      document.getElementById("age").value = data.age;
      document.getElementById("city").value = data.city;
    });
}
function postData() {
  var name = document.getElementById("name").value;
  var age = document.getElementById("age").value;
  var city = document.getElementById("city").value;
  data = { name: name, age: age, city: city };
  fetch(api_url, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  })
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
      window.location.href = "index.php";
    });
}
function putData() {
  var id = document.getElementById("id").value;
  var name = document.getElementById("name").value;
  var age = document.getElementById("age").value;
  var city = document.getElementById("city").value;
  data = { id: id, name: name, age: age, city: city };
  fetch(api_url, {
    method: "PUT",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  })
    .then((response) => response.json())
    .then((data) => {
      console.table(data);
      window.location.href = "index.php";
    });
}
function deleteData(id) {
  user_input = confirm("Are you sure you want to delete this record?");
  if (user_input) {
    fetch(api_url, {
      method: "DELETE",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ id: id }),
    })
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
        window.location.reload();
      });
  }
}

index.php

<html>

<head>
    <title>Project</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
</head>

<body class="d-flex flex-column h-100 container">
    <header>
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <div class="container-fluid">
                <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
                    <div class="navbar-nav">
                        <a class="nav-link active" aria-current="page" href="#">Listing</a>
                        <a class="nav-link" href="add.php">Add New</a>
                    </div>
                </div>
            </div>
        </nav>
    </header>
    <table class="table table-striped table-hover text-center">
        <thead>
            <th>Name</th>
            <th>Age</th>
            <th>City</th>
            <th>Action</th>
        </thead>
        <tbody id="tbody">
        </tbody>
        <tfoot>
        </tfoot>
    </table>
    <footer class="footer mt-auto py-3 bg-light">
        <div class="container text-center">
            <span class="text-muted">right &copy; 2021</span>
        </div>
    </footer>
</body>
<script src="script.js"></script>
<script>
    getData();
</script>

</html>

add.php

<html>

<head>
    <title>Project</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
</head>

<body class="d-flex flex-column h-100 container">
    <header>
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <div class="container-fluid">
                <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
                    <div class="navbar-nav">
                        <a class="nav-link" href="index.php">Listing</a>
                        <a class="nav-link active" aria-current="page" href="add.php">Add New</a>
                    </div>
                </div>
            </div>
        </nav>
    </header>
    <h3>Add Document</h3>
    <form onsubmit="return false;">
        <div class="mb-3">
            <label for="name" class="form-label">Name</label>
            <input type="text" class="form-control" id="name" autofocus>
        </div>
        <div class="mb-3">
            <label for="exampleInputPassword1" class="form-label">Age</label>
            <input type="text" class="form-control" id="age">
        </div>
        <div class="mb-3">
            <label for="city" class="form-label">City</label>
            <input type="text" class="form-control" id="city">
        </div>
        <button class="btn btn-primary" onclick="return postData()">Submit</button>
        <a href="index.php" class="btn btn-primary">Cancel</a>
    </form>
    <footer class="footer mt-auto py-3 bg-light">
        <div class="container text-center">
            <span class="text-muted">right &copy; 2021</span>
        </div>
    </footer>
</body>
<script src="script.js"></script>
<script>
</script>

</html>

edit.php

<html>

<head>
    <title>Project</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
</head>

<body class="d-flex flex-column h-100 container">
    <header>
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <div class="container-fluid">
                <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
                    <div class="navbar-nav">
                        <a class="nav-link" href="index.php">Listing</a>
                        <a class="nav-link active" aria-current="page" href="add.php">Add New</a>
                    </div>
                </div>
            </div>
        </nav>
    </header>
    <h3>Edit Document</h3>
    <form onsubmit="return false;">
        <input type="hidden" class="form-control" id="id">
        <div class="mb-3">
            <label for="name" class="form-label">Name</label>
            <input type="text" class="form-control" id="name" autofocus>
        </div>
        <div class="mb-3">
            <label for="exampleInputPassword1" class="form-label">Age</label>
            <input type="text" class="form-control" id="age">
        </div>
        <div class="mb-3">
            <label for="city" class="form-label">City</label>
            <input type="text" class="form-control" id="city">
        </div>
        <button class="btn btn-primary" onclick="return putData()">Update</button>
        <a href="index.php" class="btn btn-primary">Cancel</a>
    </form>
    <footer class="footer mt-auto py-3 bg-light">
        <div class="container text-center">
            <span class="text-muted">right &copy; 2021</span>
        </div>
    </footer>
</body>
<script src="script.js"></script>
<script>
    const urlParams = new URLSearchParams(window.location.search);
    const id = urlParams.get('id');
    getDataById(id);
</script>

</html>

Deploy Flask App on Heroku

mkdir app
cd app

app.py

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route("/")
def index():
    return "Hello World!"

@app.route('/add')
def add():
    num1 = int(request.args.get('num1'));
    num2 = int(request.args.get('num2'));

    return f"{num1} + {num2} = {num1 + num2}"

#if __name__ == "__main__":
    #app.run(debug=True);
    #app.run(host="0.0.0.0", port=int("1234"), debug=True)

runtime.txt

python-3.10.2

Procfile

web: gunicorn app:app

requirements.txt

click==8.0.3
colorama==0.4.4
Flask==2.0.2
Flask-Cors==3.0.10
gunicorn==20.1.0
itsdangerous==2.0.1
Jinja2==3.0.3
MarkupSafe==2.0.1
PyMySQL==1.0.2
six==1.16.0
Werkzeug==2.0.2

OR

You can output all dependencies using following command

python -m pip freeze > requirements.txt
heroku login

#onetime
heroku create <appname>
heroku git:remote -a <appname>
git init

#repeat whenever you make changes
git add .
git commit -m 'heroku push'
git push heroku master

Test API

https://myflaskapp2022.herokuapp.com/
https://myflaskapp2022.herokuapp.com/add?num1=5&num2=9

Troubleshoot

heroku logs --tail --app eflask-app-dusra

If still it is not working please do check spellings of files

https://devcenter.heroku.com/articles/buildpacks

React Cheat Sheet

React is a free and open-source front-end JavaScript library for building user interfaces based on UI components. It is maintained by Meta and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications.

Create new react project

npm -v
npm i npx
npx create-react-app my-react-app
cd my-react-app
code .

Run from terminal

npm start

OR

npm start --port 8000

Open Browser and run the react app http://localhost:3000 OR http://ipaddress:3000

App.js

import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <>
      <h1>Test App</h1>
    </>
  );
}

export default App;

Create new component and use click and change event

src/components/Add.js

import { Fragment, useState } from "react";


function Add () {

    const [ num1, setNum1 ] = useState(0);
    const [ num2, setNum2 ] = useState(0);
    const [ result, setResult ] = useState(0);

    function addFun() {
        setResult(num1 + num2);
    }

    return (<Fragment>
        <h1>Addition of two numbers</h1>
        <input type="text" onChange={ e => setNum1(parseInt(e.target.value)) }/>
        <input type="text" onChange={ e => setNum2(parseInt(e.target.value)) } />
        <button onClick={addFun}>Get Addtion</button>
        <div>{result}</div>
    </Fragment>);
}

export default Add;

Add this Add component in App component as tag <Add />

import './App.css';
import Add from './components/Add';

function App() {
  return (
    <>
      <Add />
      <Add />
      <h1>Test App</h1>
    </>
  );
}

export default App;

React Properties

App.js

import './App.css';
import Add from './components/Add';

function App() {
  return (
    <>
      <Add x="5" y="6"/>
      <Add x="7" y="8"/>
      <h1>Test App</h1>
    </>
  );
}

export default App;

Add.js

import { Fragment, useState } from "react";


function Add (props) {

    const [ num1, setNum1 ] = useState(parseInt(props.x));
    const [ num2, setNum2 ] = useState(parseInt(props.y));
    const [ result, setResult ] = useState(0);

    function addFun() {
        setResult(num1 + num2);
    }

    return (<Fragment>
        <h1>Addition of two numbers</h1>
        <input type="text" onChange={ e => setNum1(parseInt(e.target.value)) }/>
        <input type="text" onChange={ e => setNum2(parseInt(e.target.value)) } />
        <button onClick={addFun}>Get Addtion</button>
        <div>{result}</div>
    </Fragment>);
}

export default Add;

Ajax call in React.js

Create new component Users

components/User.js

import { Fragment } from "react";

function User(props) {

    //object destructoring assignment
    const {id, name, username, email} = props.user;

    return (
        <Fragment>
            <tr>
                <td>{props.user.id}</td> 
                <td>{props.user.name}</td>
                <td>{username}</td>  
                <td>{email}</td>
            </tr>
        </Fragment>
    );

}

export default User;

components/UsersListing.js

import { Fragment, useState } from "react";
import User from "./User";

function UsersListing () {

    const [ users, setUsers ] = useState([]);


    function getUsers() {

        fetch("https://jsonplaceholder.typicode.com/users")
        .then(response => response.json())
        .then(json => {
                console.table(json)
                var rows = [];
                for(let i = 0; i < json.length; i++) {
                    rows.push(<User key={i} user={json[i]}/>);
                }
                setUsers(rows);
            }
        );

    }

    return (<Fragment>
        <h1>Users Listing</h1>
        
        <button onClick={getUsers}>Get Users</button>

        <table border='1'>
            <thead>
                <th>Id</th>
                <th>Name</th>
                <th>Username</th>
                <th>Email</th>
            </thead>
            <tbody>
                {users}
            </tbody>
        </table>
    </Fragment>);
}

export default UsersListing;

Use <UsersListing /> component in App.js JSX to show users list

Routing

https://www.w3schools.com/REACT/react_router.asp

Deploy React App on Github

Create repository on github

git init
git add .
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/<username>/<repositoryname>.git
git remote set-url origin https://<githubtoken>@github.com/<username>/<repositoryname>.git
#git clone https://<username>:<githubtoken>@github.com/<username>/<repositoryname>.git

To get github token Go To Profile Settings => Developer Settings => Personal Access Token => Generate New Token

npm install gh-pages --save-dev

vim package.json

{
  "name": "my-app",
  "version": "0.1.0",
  "homepage": "https://gitname.github.io/repositoryname",
  "private": true,
  
  
 "scripts": {
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build",
    "start": "react-scripts start",
    "build": "react-scripts build",
npm run deploy
git status
git add .
git commit -m 'deploy react on github'
git push

https://<username>.github.io/<repositoryname>/

To publish react app locally

npm run build

Verify build directory and index.html file

build/index.html

<link rel="manifest" href="manifest.json"/>
<title>React App</title>
<script defer="defer" src="./static/js/main.<yourhash>.js"></script>
<link href="./static/css/main.<yourhash>.css" rel="stylesheet">

You can publish this in xampp htdocs folder

Python CRUD App

Create CRUD Application using Python and MySQL connector

Show following options

1. List All Records
2. Delete
3. Insert
4. Update
5. Search
0. Exit

Write separate function for each functionality

Program should not get exited unless user select 0 option.

You can use any module to connect to MySQL from python

Blockchain Demo

main.js

const SHA256 = require('crypto-js/sha256');

class Block {
	
	constructor(index, timestamp, data, prevHash = '') {
		this.index = index;
		this.timestamp = timestamp;
		this.data = data;
		this.prevHash = prevHash;
		this.hash = this.calculateHash();
	}
	
	calculateHash() {
		return SHA256(this.index + this.prevHash + this.timestamp + JSON.stringify(this.data)).toString();
	}
	
}

class Blockchain {
	constructor() {
		this.chain = [this.createGenesisBlock()];
	}
	
	createGenesisBlock() {
		return new Block(0, "01/01/2021", "Genesis block", "0");
	}
	
	getLatestBlock() {
		return this.chain[this.chain.length - 1];
	}
	
	addBlock(newBlock) {
			newBlock.prevHash = this.getLatestBlock().hash;
			newBlock.hash = newBlock.calculateHash();
			this.chain.push(newBlock);
	}
	
	isChainValid() {
		for(let i=1; i < this.chain.length; i++) {
			const currentBlock = this.chain[i];
			const prevBlock = this.chain[i-1];
			
			if(currentBlock.hash !== currentBlock.calculateHash()) {
				return false;
			}
			
			if(currentBlock.prevHash != prevBlock.hash) {
				return false;
			}
		}
		
		return true;
	}
	
}

let tcoin = new Blockchain();
tcoin.addBlock(new Block(1, "03/09/2021", {amt: 100}));
tcoin.addBlock(new Block(1, "04/09/2021", {amt: 200}));

console.log(tcoin.isChainValid());
console.log(JSON.stringify(tcoin, null, 4));

//tempering data
tcoin.chain[2].amt = 2000;
console.log(JSON.stringify(tcoin, null, 4));
console.log(tcoin.isChainValid());

Proof of Work

const SHA256 = require('crypto-js/sha256');

class Block {
	
	constructor(index, timestamp, data, prevHash = '') {
		this.index = index;
		this.timestamp = timestamp;
		this.data = data;
		this.prevHash = prevHash;
		this.hash = this.calculateHash();
		this.nonce = 0;
	}
	
	calculateHash() {
		return SHA256(this.index + this.prevHash + this.timestamp + JSON.stringify(this.data) + this.nonce).toString();
	}
	
	mineBlock(complexity) {
		while(this.hash.substring(0, complexity) !== Array(complexity + 1).join("0")) {
			this.nonce++;
			//console.log(this.nonce);
			this.hash = this.calculateHash();
		}
		
		console.log(`Block mined: ${this.hash}`);
	}
	
}

class Blockchain {
	constructor(complexity = 0) {
		this.chain = [this.createGenesisBlock()];
		this.complexity = complexity;
	}
	
	createGenesisBlock() {
		return new Block(0, "01/01/2021", "Genesis block", "0");
	}
	
	getLatestBlock() {
		return this.chain[this.chain.length - 1];
	}
	
	addBlock(newBlock) {
			newBlock.prevHash = this.getLatestBlock().hash;
			//newBlock.hash = newBlock.calculateHash();
			newBlock.mineBlock(this.complexity);
			this.chain.push(newBlock);
	}
	
	isChainValid() {
		for(let i=1; i < this.chain.length; i++) {
			const currentBlock = this.chain[i];
			const prevBlock = this.chain[i-1];
			
			if(currentBlock.hash !== currentBlock.calculateHash()) {
				return false;
			}
			
			if(currentBlock.prevHash != prevBlock.hash) {
				return false;
			}
		}
		
		return true;
	}
	
}

let tcoin = new Blockchain(5);

console.log("Mining Block 1...");
tcoin.addBlock(new Block(1, "03/09/2021", {amt: 100}));

console.log("Mining Block 2...");
tcoin.addBlock(new Block(1, "04/09/2021", {amt: 200}));

console.log(JSON.stringify(tcoin, null, 4));