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));

RegEx

https://regexr.com/

Pattern Matching

Regex Syntax

/<regex pattern>/

Starts with wild card character

^

Ends with wcc

$

set enclosed in

[set]
[^invert-set]

only numbers

^[0-9]+$
^\d+$

only characters

^[a-zA-Z]+$
^\w+$

occurance wcc

* => any number of occurance
? => 0 or 1 occurance
+ => 1 or many occurance

no special characters

^[0-9a-zA-Z\s]+$

limited characters or numbers

^[0-9]{6}$
^[a-z]{3}$

min / max range characters or numbers

^[0-9]{3,6}$
^[a-z]{3,6}$

OR clause

^(chacha|bhatija)$

case insensitive

//i

global check

//g

search any pattern
(.) e.g. “https://www.youtube.com/watch?v=hw_HpTI_Wkw”.match(/v=(.)/)[1]

will return video id hw_HpTI_Wkw

Assignment

  1. girls / boys name
  2. phone number
  3. find Indian zip code
  4. valid name
  5. email id
  6. 8-12 character password
  7. aadhaar number
  8. pancard
  9. name starts with vowels
  10. names ends with vowels
  11. names having only 5 characters
  12. credit card number

Sample Text

1234567890
123453
DAVPS0412P
127836320613
9876543210
098762
xyz@yahoo.com
smita
&UJMmju7
shailesh
143258761937
priyanka
abc@gmail.com
112096851365
%TGBbgt5
priya

DMA Project Cheat Sheet

To get the connection string

Atlas > Deployment > Databases > Connect > Connect your application > Driver Node.js > Version 2.2.12 or later

Create REST Api using Node.js | Express | Mongoose

index.js

const port = 8080;
const mongoose = require("mongoose");
//const conn_str ="C"
const conn_str = "mongodb://<user>:<passwd>@cluster0-shard-00-00.dslyw.mongodb.net:27017,cluster0-shard-00-01.dslyw.mongodb.net:27017,cluster0-shard-00-02.dslyw.mongodb.net:27017/<databasename>?ssl=true&replicaSet=atlas-3xk2hf-shard-0&authSource=admin&retryWrites=true&w=majority";


mongoose.connect(conn_str, { useNewUrlParser: true , useUnifiedTopology: true})
	.then( () => console.log("Connected successfully...") )
	.catch( (err) => console.log(err) );


const userSchema = new mongoose.Schema({
	name: String,
	age: Number,
	city: String
});

const user = new mongoose.model("users", userSchema);


/** Express Mongoose Integration **/

const express = require("express");
var cors = require('cors');
const app = express();


//add middlewares
app.use(express.json());
app.use(cors());


app.route("/user")
.get(async (req, res) => {
	let data = await user.find();
	res.send(data);
})
.post(async (req, res) => {
	req_data = req.query;
	let obj = new user(req.query)
	let result = await obj.save();
	res.send(result);
})
.put(async (req, res) => {
	console.log(req.body);
	
	//model.updateOne({where}, {set});
	let u_data = await user.updateOne({"_id": req.body._id}, {
		"$set": {
			"name" : req.body.name,
			"age" : req.body.age,
			"city" : req.body.city
		}
	});
	
	res.send(u_data);
})
.delete(async (req, res) => {
	let d_data = await User.deleteOne({"_id": req.body._id});
	res.send(d_data);
})


app.listen(process.env.PORT || port, () => {
	console.log("listening 8080...");
});

Call REST Api using Vanilla JS

index.html

<script>
function getDataById(id) {
	fetch(`http://localhost:8080/user/${id}`)
	.then((response) => response.json())
	.then((data) => { console.table(data); })
}

function getData() {
	fetch("http://localhost:8080/user")
	.then((response) => response.json())
	.then((data) => { console.table(data); })
}

function postData(data) {
	fetch("http://localhost:8080/user", {
		method: "POST",
		headers: {
		  'Accept': 'application/json',
		  'Content-Type': 'application/json'
		},
		body: JSON.stringify(data)
	})
	.then((response) => response.json())
	.then((data) => { console.table(data); })
}
	

function putData(data) {
	fetch("http://localhost:8080/user", {
		method: "PUT",
		headers: {
		  'Accept': 'application/json',
		  'Content-Type': 'application/json'
		},
		body: JSON.stringify(data)
	})
	.then((response) => response.json())
	.then((data) => { console.table(data); })
}

function deleteData(id) {
	fetch("http://localhost:8080/user", {
		method: "DELETE",
		headers: {
		  'Accept': 'application/json',
		  'Content-Type': 'application/json'
		},
		body: JSON.stringify({"_id": id})
	})
	.then((response) => response.json())
	.then((data) => { console.table(data); })
}


getDataById();
getData();
postData({"name": "Akshu", "age": 20, "city": "Koradi"});
putData({"_id" : "61082ae9cd4b7a0ccc39d377", "name": "chaitu"});
deleteData("61082b4ecd4b7a0ccc39d37a");
</script>

CRUD Application using Vanilla JS | HTML5 | CSS3 | Bootstrap5

users_module.js

//Step 1: Database connection
const mongoose = require("mongoose");

//mongodb://127.0.0.1:27017/dbname
//const conn_str = "mongodb://localhost:27017/tcet";
const conn_str = "mongodb://<username>:<password>@cluster0-shard-00-00.dslyw.mongodb.net:27017,cluster0-shard-00-01.dslyw.mongodb.net:27017,cluster0-shard-00-02.dslyw.mongodb.net:27017/<database>?ssl=true&replicaSet=atlas-3xk2hf-shard-0&authSource=admin&retryWrites=true&w=majority";


mongoose.connect(conn_str, { useNewUrlParser: true, useUnifiedTopology: true })
	.then(() => console.log("Connected successfully..."))
	.catch( (error) => console.log(error) );
	
	
//Step 2: Create Schema (Java Class)
const userSchema = new mongoose.Schema({
	name: String,
	age: Number,
	city: String
})

//Step 3: Create collection Object (model)
// MAPPING 
const userObject = new mongoose.model("users", userSchema);

exports.User = userObject;

index.js

const express = require("express");
const port = 8080;

const user_model = require("./users_module");
const User = user_model.User;

const app = express();
app.use(express.json());

var cors = require('cors');
app.use(cors());

app.get("/", (req, res) => {
	res.send("Hello Friends..");
});

app.get("/user", async (req, res) => {
	let data = await User.find().sort({_id:-1});
	res.send(data);
});

app.get("/user/:id", async (req, res) => {
	console.log(req.params.id);
	let data = await User.find({"_id": req.params.id});
	res.send(data[0]);
});

app.post("/user", async (req, res) => {
	console.log(req.body)
	let u = await User(req.body);
	let result = u.save();
	res.send(req.body);
});

app.put("/user", async (req, res) => {
	console.log(req.body);
	
	//User.updateOne({where}, {set});
	let u_data = await User.updateOne({"_id": req.body._id}, {
		"$set": {
			"name" : req.body.name,
			"age" : req.body.age,
			"city" : req.body.city
		}
	});
	
	res.send(u_data);
});

app.delete("/user", async(req, res) => {
	
	let d_data = await User.deleteOne({"_id": req.body._id});
	res.send(d_data);
});

app.listen(process.env.PORT || port, () => {	
	console.log(`Listening on port ${port}`);
});

script.js

//const api_url = "<heroku_app_url>"
const api_url = "http://localhost:8080/user"

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.html?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}`)
	.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.html";
	})
}	


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.html";
	})
}


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.html

<html>
	<head>
		<title>DMA 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.html">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">Copyright &copy; 2021</span>
		  </div>
		</footer>
	</body>
	<script src="script.js"></script>
	<script>
		getData();
	</script>
</html>

add.html

<html>
	<head>
		<title>DMA 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.html">Listing</a>
					<a class="nav-link active" aria-current="page" href="add.html">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.html" 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">Copyright &copy; 2021</span>
		  </div>
		</footer>
	</body>
	<script src="script.js"></script>
	<script>
	</script>
</html>

edit.html

<html>
	<head>
		<title>DMA 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.html">Listing</a>
					<a class="nav-link active" aria-current="page" href="add.html">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.html" 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">Copyright &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>

Screenshots

listing

delete

add

edit

Reference Link: https://gitlab.com/tcet/mongodb-july-21.git

Deploy Node.js app on heroku

Signup/Signin on heorku

https://herokuapp.com/

Login from terminal (Make sure you have installed heroku cli – https://devcenter.heroku.com/articles/heroku-cli#download-and-install)

heroku login

Create app.js

const express = require("express");
const app = express();
const port = 8080;

app.get("/", (req, res) => {
    res.send("Hello Heroku");
})

app.listen(process.env.PORT || port, () => {
	console.log("listening 8080...");
});

process.env.PORT this will be provided by heroku server

Test locally by running following command

node app.js
OR
nodemon app.js

If you get any error e.g. module not found you can install those module using npm

npm install <module_name>

To find installed module version

npm view <module_name> version
e.g.
npm view express version

Create package.json

{
	"scripts" : {
		"start" : "node app.js"
	},
	"dependencies": {
		"express": "4.17.1",
		"mongoose": "5.13.3",
		"cors": "2.8.5"
	}
}

Run following command from terminal

#onetime
git init
#onetime
heroku create <yournewappname>

Run git commands

git add .
git commit -m 'msg'
#to verify origin
git config -l
git remote add origin heroku_git_url
git push origin master
#git push heroku master

Once app is deployed it will show you an url which you can access publicly from internet.

To see error logs

heroku logs --tail

PWA cheat sheet

index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="theme-color" content="#009578">
        <title>PWA</title>
        <link rel="stylesheet" href="src/master.css">
        <link rel="manifest" href="manifest.json">
        <link rel="apple-touch-icon" href="images/logo_2.jpg">
    </head>
    <body>
        <h3>Progressive Web App</h3>
        <script src="src/index.js"></script>
        <h4>Addition</h4>

    <label for="num1">Enter 1st Number:</label><br>
    <input type="text" id="num1" name="num1"><br>
    <br>

    <label for="num2">Enter 2nd Number:</label><br>
    <input type="text" id="num2" name="num2"><br><br>

    <button type="button" name="button" onclick="addition()">Add</button>

    <div>
        <h4>Result: <span id="res"> </span></h4>
    </div>

    <script>
        function addition() {
            var x = parseInt(document.getElementById("num1").value);
            var y = parseInt(document.getElementById("num2").value);

            var z = x + y;

            document.getElementById("res").innerHTML = z;
        }
    </script>

    </body>
</html>

manifest.json

{
    "name": "PWA demo",
    "short_name": "PWA",
    "start_url": ".",
    "background_color": "#6dcdb1",
    "theme_color": "#009578",
    "display": "standalone",
    "icons": [
        {
            "src": "images/logo_2.jpg",
            "sizes": "512x512",
            "type": "image/jpg"
        },
        {
            "src": "images/logo_1.png",
            "sizes": "512x512",
            "type": "image/png"
        }
    ]
}

sw.js

self.addEventListener("install", e => {
    // console.log("Install decode!");
    e.waitUntil(
        caches.open("static").then(cache => {
            return cache.addAll(["./", "./src/master.css", "./images/logo_2.jpg"]);
        })
    );
});


self.addEventListener("fetch", e => {
    // console.log(`Intercepting fetch request for: ${e.request.url}`);
    e.respondWith(
        caches.match(e.request).then(response => {
            return response || fetch(e.request);
        })
    );
});

src/index.js

if ("serviceWorker" in navigator) {
    navigator.serviceWorker.register("sw.js").then(registration => {
        console.log("SW Registered!");
        console.log(registration);
    }).catch(error => {
        console.log("SW Registration failed!");
        console.log(error);
    })
}

src/master.css

body {
    background: #eeeeee;
}

web socket chat app

chat_server.js

const express = require('express');
const http = require('http');
const WebSocket = require('ws');

const port = 8989;
const server = http.createServer(express);
const wss = new WebSocket.Server({ server })

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(data) {
    wss.clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(data);
      }
    })
  })
})

server.listen(port, function() {
  console.log(`Server is listening on ${port}!`)
})

index.html

<center><h1>WS Chat App</h1></center>
<pre id="messages" style="height: 400px; overflow: scroll"></pre>
<input type="text" id="messageBox" placeholder="Type your message here" style="display: block; width: 100%; margin-bottom: 10px; padding: 10px;" onkeyup="validateInput(event)"/>
<button id="send" title="Send Message!" style="width: 100%; height: 30px;">Send Message</button>

<script>
  (function() {
    const sendBtn = document.querySelector('#send');
    const messages = document.querySelector('#messages');
    const messageBox = document.querySelector('#messageBox');

    let ws;

    function showMessage(message) {
      messages.textContent += `\n\n${message}`;
      messages.scrollTop = messages.scrollHeight;
      messageBox.value = '';
    }

    function init() {
      if (ws) {
        ws.onerror = ws.onopen = ws.onclose = null;
        ws.close();
      }

      ws = new WebSocket('ws://localhost:8989');
      ws.onopen = () => {
        console.log('Connection opened!');
      }
      ws.onmessage = ({ data }) => showMessage(data);
      ws.onclose = function() {
        ws = null;
      }
    }

	
    sendBtn.onclick = function() {
      if (!ws) {
        showMessage("No WebSocket connection :(");
        return ;
      }

      ws.send(messageBox.value);
      showMessage(messageBox.value);
    }
	
	
	messageBox.onkeyup = function() {
		if(event.keyCode  == 13) {
			if (!ws) {
				showMessage("No WebSocket connection :(");
				return ;
			}

			ws.send(messageBox.value);
			showMessage(messageBox.value);
		}
    }

    init();
  })();
</script>

Angular Cheat Sheet

https://angular.io/guide/setup-local

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { AddComponent } from './add/add.component';
import { HomeComponent } from './home/home.component';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { HttpClientModule } from '@angular/common/http'

@NgModule({
  declarations: [
    AppComponent,
    AddComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts

if app-routing.module.ts is not present then run this in root folder
ng generate module app-routing –flat –module=app

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AddComponent } from './add/add.component';

const routes: Routes = [
  { path: 'add', component: AddComponent },
  { path: 'add/:num1/:num2', component: AddComponent },
  // { path: 'sub', component: SubComponent },
  // { path: 'mul', component: MulComponent },
  // { path: 'div', component: DivComponent },
  { path: '**', component: HomeComponent },
];

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule.forRoot(routes)
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule { }

app.component.html

<a routerLink="/"  routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">Home</a> |
<a routerLink="/add"  routerLinkActive="active">Add</a>
<router-outlet></router-outlet>

app.component.css

.active {
  background-color: beige;
}

home.component.ts

ng g c home

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms'
import { HomeService } from './home.service'

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  fruits = ["Orange", "Mango", "Banana", "Apple"];

  num1: number = 0;
  square: number = 0;

  form = new FormGroup({
    num1: new FormControl(),
    num2: new FormControl()
  });
  formResult: any;

  userRecords: any;

  constructor(private service: HomeService) { }

  ngOnInit() {
  }

  getSqr() {
    var x = this.num1;
    this.square = x * x;
  }

  addNum() {
    let x = parseInt(this.form.value.num1);
    let y = parseInt(this.form.value.num2);
    this.formResult = x + y;
  }

  getUsers() {
    this.service.getData().subscribe((response) => {
      console.log(response);
      this.userRecords = response;
    })
  }

}

home.component.html

<p>home works!</p>
{{ fruits }}

<div *ngFor="let fruit of fruits">
  {{fruit}}
</div>


<input type="text" (keyup)="getSqr()" [(ngModel)]="num1"/>
<div>
  Square of {{num1}} is {{square}}
</div>


<form [formGroup]="form" (submit)="addNum()">
  <input type="text" formControlName="num1"/>
  <input type="text" formControlName="num2"/>
  {{ form.value | json }}
  <div>
    Result: {{ formResult }}
  </div>
  <input type="submit" value="Add"/>
</form>


<button (click)="getUsers()">Get Data from Json Placeholder</button>
<div>
  {{userRecords}}
  <pre>
    {{userRecords | json}}
  </pre>
</div>

home.service.ts

cd home
ng g s home

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HomeService {

  constructor(private http: HttpClient) { }

  getData() {
    let url = "https://jsonplaceholder.typicode.com/users";
    return this.http.get(url);
  }
}

add.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.css']
})
export class AddComponent implements OnInit {

  number: number;
  param1: number;
  param2: number;

  constructor(private route: ActivatedRoute, private router: Router) {
    console.log(this.route.snapshot.url)
    console.log(this.route.snapshot.params)
    this.number = parseInt(this.route.snapshot.queryParamMap.get('id'))
    this.param1 = parseInt(this.route.snapshot.params.num1);
    this.param2 = parseInt(this.route.snapshot.params.num2);
  }

  ngOnInit() {
    console.log(this.number)
    console.log(this.param1)
    console.log(this.param2)

    // setTimeout(() => {
    //   this.router.navigate(['home']);
    // }, 3000)
  }

}
my-app\src\app\interceptor\httpconfig.interceptor.ts
import { Injectable } from '@angular/core';
import {
    HttpInterceptor,
    HttpRequest,
    HttpResponse,
    HttpHandler,
    HttpEvent,
    HttpErrorResponse
} from '@angular/common/http';

import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

@Injectable()
export class HttpConfigInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const token: any = localStorage.getItem('token');
        // const token: string = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1X25hbWUiOiJhZG1pbiIsInB3ZCI6IkBkbWluIiwiaWF0IjoxNjEyNjM2OTc5fQ.ehlxu7z_1HSW4bPK902nLOAZOpHtutfkJ43lCxQnL68`;
        if (token) {
            request = request.clone({ headers: request.headers.set('Authorization', 'Bearer ' + token) });
        }

        if (!request.headers.has('Content-Type')) {
            request = request.clone({ headers: request.headers.set('Content-Type', 'application/json') });
        }

        request = request.clone({ headers: request.headers.set('Accept', 'application/json') });

        return next.handle(request).pipe(
            map((event: HttpEvent<any>) => {
                if (event instanceof HttpResponse) {
                    console.log('event--->>>', event);
                }
                return event;
            }));
    }
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { RouterModule } from '@angular/router';

import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'
import { HttpConfigInterceptor } from './interceptor/httpconfig.interceptor';


@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    HttpClientModule
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: HttpConfigInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]

})
export class AppModule { }

Mongoose Express CRUD

const mongoose = require("mongoose");
const conn_str = "mongodb://localhost:27017/tcet"
mongoose.connect(conn_str, { useNewUrlParser: true , useUnifiedTopology: true})
	.then( () => console.log("Connected successfully...") )
	.catch( (err) => console.log(err) );

const userSchema = new mongoose.Schema({
	name: String,
	age: Number,
	city: String,
	state: String
});

const user = new mongoose.model("user", userSchema);

/** Express Mongoose Integration **/

const express = require("express");
const app = express();

app.route("/user")
.get(async (req, res) => {
	let data = await user.find();
	res.send(data);
})
.post(async (req, res) => {
	req_data = req.query;
	let obj = new user(req.query)
	let result = await obj.save();
	res.send(result);
})
.put(async (req, res) => {
	req_data = req.query;
	let result = await user.updateOne({_id: req.query.id}, {$set : {city: req.query.city}})
	res.send(result);
})
.delete(async (req, res) => {
	let result = await user.deleteOne({_id: req.query.id})
	res.send(result);
})

app.listen(8080, () => {
	console.log("listening 8080...");
});

Connect to MongoDB Atlas Cluster

Whitelist your ip / or allow from all 0.0.0.0/0

Get Your Current IP Address from google > what is my ip

Atlas > Security > Network Access > ADD IP ADDRESS

First get the connection string or URI from Atlas

Atlas > Deployment > Databases > Connect > Connect your application > Driver Node.js > Version 2.2.12 or later
const port = 8080;
const mongoose = require("mongoose");
const uri ="get_uri_from_atlas"
mongoose.connect(uri, { useNewUrlParser: true , useUnifiedTopology: true})
	.then( () => console.log("Connected successfully...") )
	.catch( (err) => console.log(err) );

const userSchema = new mongoose.Schema({
	name: String,
	age: Number,
	city: String
});

const user = new mongoose.model("users", userSchema);

/** Express Mongoose Integration **/

const express = require("express");
const app = express();

app.route("/user")
.get(async (req, res) => {
	let data = await user.find();
	res.send(data);
})
.post(async (req, res) => {
	req_data = req.query;
	let obj = new user(req.query)
	let result = await obj.save();
	res.send(result);
})
.put(async (req, res) => {
	req_data = req.query;
	let result = await user.updateOne({_id: req.query.id}, {$set : {city: req.query.city}})
	res.send(result);
})
.delete(async (req, res) => {
	let result = await user.deleteOne({_id: req.query.id})
	res.send(result);
})

app.listen(process.env.PORT || port, () => {
	console.log("listening 8080...");
});

mongoose cheat sheet

Insert

console.log("mongo db connection");

const mongoose = require("mongoose");

const conn_str = "mongodb://localhost:27017/tcet";
mongoose.connect(conn_str, { useNewUrlParser: true, useUnifiedTopology: true })
	.then( () => console.log("Connected Successfully..."))
	.catch( (error) => console.log(error));
	
//schema defining for collection
const teacherSchema = new mongoose.Schema({
	name: {
		type: String,
		required: true
	},
	age: Number,
	city: String
})

// create collection
const Teacher = new mongoose.model("Teacher", teacherSchema);
console.log(Teacher);
	
/*insertOne
const t1 = new Teacher({name: "Shailesh", age: 32, city: "Nagpur"});
console.log(t1.save());


//insertOne
const insertOne = async () => {
	try {
		const t2 = new Teacher({name: "Amy", age: 32, city: "Nagpur"});
		const result = await t2.save();
		console.log(result);
	} catch(e) {
		console.log(e);
	}
};

insertOne();


//insertMany
const insertMany = async () => {
	try {
		const t1 = new Teacher({name: "Amy1", age: 32, city: "Nagpur"});
		const t2 = new Teacher({name: "Amy2", age: 32, city: "Nagpur"});
		const t3 = new Teacher({name: "Amy3", age: 32, city: "Nagpur"});
		const result = await Teacher.insertMany([t1,t2,t3]);
		console.log(result);
	} catch(e) {
		console.log(e);
	}
};

insertMany();
*/

Connection Module

const mongoose = require("mongoose");

const conn_str = "mongodb://localhost:27017/tcet";
mongoose.connect(conn_str, { useNewUrlParser: true, useUnifiedTopology: true })
	.then( () => console.log("Connected Successfully..."))
	.catch( (error) => console.log(error));
	
//schema defining for collection
const teacherSchema = new mongoose.Schema({
	name: {
		type: String,
		required: true
	},
	age: Number,
	city: String
})

// create collection
const Teacher = new mongoose.model("Teacher", teacherSchema);

exports.Teacher = Teacher;

Read

var teacher = require("./teacher");
const Teacher = teacher.Teacher;

/*
const t1 = new Teacher({name: "Penny", age: 25, city: "Nagpur"});
console.log(t1.save());
*/

const getData = async () => {
const data = await Teacher.find({name: /l/i}).select({_id: 0, __v: 0}).limit(2).sort({name: -1});
	console.log(data);
}

getData();

Update

var teacher = require("./teacher");
const Teacher = teacher.Teacher;

/*
const updateOne = async (oname, nname) => {
	try {
		var res = await Teacher.updateOne({name: oname}, {
			$set : { name : nname }
		});
		console.log(res);
	} catch (e) {
		console.log(e);
	}
}

updateOne("Howa", "Kuwa.....");

const updateMany = async (city) => {
	try {
		var res = await Teacher.updateMany({age: {$lt: 30}}, {
			$set : { city : city }
		});
		console.log(res);
	} catch (e) {
		console.log(e);
	}
}

updateMany("Mumbai");

*/

Delete

var teacher = require("./teacher");
const Teacher = teacher.Teacher;

/*
const deleteMany = async (where) => {
	try {
		var res = await Teacher.deleteMany(where);
		console.log(res);
	} catch(error) {
		console.log(error);
	}
}

deleteMany({age : {$in: [25, 37]}});
*/

NodeJS Cheat Sheet

NODE CUSTOM MODULE

index.js

var mymath = require("./mymodule")

console.log(mymath.add(5,6));
console.log(mymath.sub(5,6));
console.log(mymath.mul(5,6));
console.log(mymath.div(5,6));
console.log(mymath.mod(5,6));

cobj = new mymath.MyCircle(5);
cobj.area();

mymodule.js

exports.add = (x, y) => x + y;
exports.sub = (x, y) => x – y;
exports.mul = (x, y) => x * y;
exports.div = (x, y) => x / y;
exports.mod = (x, y) => x % y;

exports.MyCircle = class {

constructor(r) {
    this.radius = r;
    console.log("Hello I am My Circle Constructor...");
}

area() {
    let area = Math.PI * this.radius * this.radius;
    console.log(`Area: ${area.toFixed(2)}`);
}
}

NODE http MODULE

index.js

var http = require(“http”)

http.createServer((req, res) => {
// res.writeHead(‘Content-Type’, ‘text/plain’);
// res.writeHead(‘Content-Type’, ‘application/json’);
res.writeHead(200, {‘Content-Type’ : ‘text/html’});
res.write("this is line 1….");

console.log(req.url);

if(req.url == "/") {
    res.write("Home req hit</br>")
} else 

if(req.url == "/teacher") {
    res.write("Teacher req hit</br>")
} else 

if(req.url == "/student") {
    res.write("Student req hit</br>")
} else 

{
    res.end("Page Not Found....");
}

res.end("hello world....");
}).listen(8989, () => {
console.log("listening at port 8989…")
});

EXPRESS ROUTING

index.js

var express = require(“express”)
var app = express();

app.get(“/”, (req, res) => {
// res.setHeader(‘Content-Type’, ‘text/plain’);
// res.setHeader(‘Content-Type’, ‘application/json’);
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“Home Page”);
})

app.get(“/student”, (req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = { “result” : “Student GET Request”}
res.send(JSON.stringify(data))
})
app.post(“/student”, (req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = { “result” : “Student post Request”}
res.send(JSON.stringify(data))
})
app.put(“/student”, (req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = { “result” : “Student put Request”}
res.send(JSON.stringify(data))
})
app.delete(“/student”, (req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = { “result” : “Student delete Request”}
res.send(JSON.stringify(data))
})

app.route(“/teacher”)
.get((req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = { “result” : “Teacher get Request”}
res.send(JSON.stringify(data))
})
.post((req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = { “result” : “Teacher post Request”}
res.send(JSON.stringify(data))
})
.put((req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = { “result” : “Teacher put Request”}
res.send(JSON.stringify(data))
})
.delete((req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = { “result” : “Teacher delete Request”}
res.send(JSON.stringify(data))
})

app.listen(8989, () => {
console.log(“Listening at port 8989”);
})

EXPRESS MODULAR ROUTING

index.js

var express = require(“express”);
var app = express();
var home = require(“./home”)
var student = require(“./student”)
var teacher = require(“./teacher”)

app.use(“/”, home);
app.use(“/student”, student);
app.use(“/teacher”, teacher);

app.use(function(req, res, next) {
res.status(404);
res.send(‘404: File Not Found’);
});

app.listen(8989, () => {
console.log(“Listening at port 8989”);
});

student.js

const express = require(“express”);
const router = express.Router();

router.route(“/”)
.get((req, res)=>{
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“student listing”);
})

.post((req, res)=>{
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“student post”);
})

.put((req, res)=>{
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“student put”);
})

.delete((req, res)=>{
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“student delete”);
})

module.exports = router

teacher.js

const express = require(“express”);
const router = express.Router();

router.route(‘/’)
.get((req, res)=>{
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“teachers listing”);
})

.post((req, res)=>{
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“teachers post”);
})

.put((req, res)=>{
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“teachers put”);
})

.delete((req, res)=>{
res.setHeader(‘Content-Type’, ‘text/html’);
res.send(“teachers delete”);
})

module.exports = router;

EXPRESS READ DATA

index.js

const express = require(“express”);
const app = express();

const bodyParser = require(‘body-parser’);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json())

app.route(“/”)
.get((req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = req.query;
res.send(JSON.stringify(data));
})
.post((req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = req.body;
res.send(JSON.stringify(data));
})
.put((req, res) => {
res.setHeader(‘Content-Type’, ‘application/json’);
data = req.body;
res.send(JSON.stringify(data));
})

app.listen(8989, () => {
console.log(“Listening at port 8989”);
});

Assignment: WA Web Service to read number from user and return square and cube of that number. Return data in JSON format.

Express File Upload

//get directory name
console.log(`Project Path: ${__dirname}`);

const express = require("express");
const fileUpload = require("express-fileupload");
const app = express();

//options / middleware
app.use(fileUpload());

app.post("/file_upload", (req, res) => {
	
	console.log(req.body);
	console.log(req.files);
	
	let file_to_upload = req.files.file_to_upload;
	
	//file_to_upload.mv(path,callbackfun);
	const upload_path = __dirname + '/uploads/' + file_to_upload.name;
	//file_to_upload.mv(upload_path);
	
	file_to_upload.mv(upload_path, (err) => {
		if(err) {
			res.status(500)
			res.send(err);
		}
		
		res.status(200)
		res.send("File Upload successfully...")
	})
	
});

app.listen(8989, () => {
	console.log("Listening at port 8989");
})

json webtoken

var jwt = require('jsonwebtoken');
var express = require("express");
var app = express();

username = "admin";
password = "@dmin";

app.use(express.json());

var cors = require('cors')
app.use(cors())

function errorHandler(req, res, next) {
    if (!req.headers.authorization) return res.status(401).send({message:"No token provided"});

    const token = req.headers.authorization.replace("Bearer ","");

    jwt.verify(token, 'shhhhh', function(err) {
        if (err){
            res.status(401).send({message: "unauthorized user"});
        } 
        res.send("jwt token is correct");
    });

    return res.status(500).json({ message: err.message });
}


app.route('/login')
.post((req, res)=>{
    if (username==req.body.username && password == req.body.password){
        var token = jwt.sign({ u_name: username}, 'shhhhh');
        res.send(token);
    }else{
        res.send("wrong creditionals");
    }
    
})

app.use(errorHandler)

app.route('/dashboard')
.get((req,res)=>{
    res.send("dashboard");
})

app.route('/employees')
.get((req,res)=>{
    res.send("emloypee page");
})

app.listen(8080,()=>{
    console.log("listening at 8080")
});