Sunday, September 16, 2018

NodeJS 25: Project - "ProductBacklog" -> Step by Step

NodeJS 25: Project - "ProductBacklog" -> Step by Step

Project – Product Backlog


Step1: Create folder “ProductBacklog” -> and open it in “Visual Studio code”
Step2: Create “package.json” -> npm init
Step3: install Express server. -> npm install express –save
Step4: Create public/assets folder
Step5: install “nodemon” -> npm install nodemon -save
Step6: need to install “EJS” as view engine -> npm install ejs –save
Step7: install body parser for POST req handling -> npm install body-parser –save
Step8: create app.js -> set up all layers (Express -> Middleware -> EJS (view engine)
Step9: create todoController.js -> write .get , post, delete
Step10: create ‘todo.ejs’ (view) and ‘todo-list.js’ (jquery to invoke AJAX call)
Step11: Run the app.js -> node app    OR   nodemon app
Step12: Install MongoDB locally or in Cloud -> mlab.com -> sign up -> create database “todopavanmr” and copy paste the URL
Step13: Install mongoose to connect to MongoDB -> npm install mongoose –save
Step14 : Run app.js -> Test UI -> try inserting deleting the records from mongoDB.

##########################################################################

Step1: Create folder “ProductBacklog” -> and open it in “Visual Studio code”


Step2: Create “package.json” -> to keep track of all versioning, acts like LOG file when we move project from DEV env to PROD env helps.

npm init


Step3: We need Server to host our project so install Express server.

npm install express –save


Step4: Create public/assets folder -> to keep all static files.


Add “logo.png” and “todostyles.css” under assets folder


Step5: Since we are developing that in dev env, to monitor need to install “nodemon

npm install nodemon -save


Step6: Since we are going to use our own “View engine” -> EJS , need to install “EJS”

npm install ejs –save


Step7: to handle all POST request, we need to install body-parser

npm install body-parser –save


Step8: create ‘app.js’ and set up all layers (Express -> Middleware -> EJS (view engine)


Step9: create ‘todoController.js’


Step10: create ‘todo.ejs’ (view) and ‘todo-list.js’ (jquery to invoke AJAX call)
todo.ejs -> is view layer to display data, should be inside /views folder always
todo-list.js -> jquery , to call AJAX and reload page/component back.



Run the app.js

node app    OR   nodemon app



Now to push/get from DB
è We need to install MongoDB locally or in Cloud
è Use driver to communicate to mongoDB , using Mongoose (acts like driver and ORM tool -> automatically maps Entity to database tables just like Hibernate)
d

è We need to install MongoDB locally or in Cloud




mlab.com
sign up








mongodb://<dbuser>:<dbpassword>@ds257752.mlab.com:57752/todopavanmr




è Use driver to communicate to mongoDB , using Mongoose (acts like driver and ORM tool -> automatically maps Entity to database tables just like Hibernate)


npmjs.com

mongoose  - acts   like
- Driver
- ORM

npm install mongoose –save


mongodb://test123:Pass123@ds257752.mlab.com:57752/todopavanmr


Insert Item from UI -> to insert in to MongoDB and refresh below list.





################################################################################

package.json

{
"name": "productbacklog",
"version": "1.0.0",
"description": "product backlog tracker",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "pavan",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.3",
"ejs": "^2.6.1",
"express": "^4.16.3",
"mongoose": "^5.2.14",
"nodemon": "^1.18.4"
}
}

todostyles.css

body{
background: #1d2c44;
font-family: tahoma;
color: #989898;
}

#todo-table{
position: relative;
width: 95%;
background: #090d13;
margin: 0 auto;
padding: 20px;
box-sizing: border-box;
}

#todo-table form:after{
margin: 0;
content: '';
display: block;
clear: both;
}

input[type="text"]{
width: 70%;
padding: 20px;
background:#181c22;
border: 0;
float: left;
font-size: 20px;
color: #989898;
}

button{
padding: 20px;
width: 30%;
float: left;
background: #23282e;
border: 0;
box-sizing: border-box;
color: #fff;
cursor: pointer;
font-size: 20px;
}

ul{
list-style-type: none;
padding: 0;
margin: 0;
}

li{
width: 100%;
padding: 20px;
box-sizing: border-box;
font-family: arial;
font-size: 20px;
cursor: pointer;
letter-spacing: 1px;
}

li:hover{
text-decoration: line-through;
background: rgba(0,0,0,0.2);
}

h1{
background: url(/assets/logo.png) no-repeat center;
margin-bottom: 0;
text-indent: -10000px;
}
         
app.js

var express=require('express');
var todoController=require('./controller/todoController');

var app=express();

app.use(express.static('./public'));

app.set('view engine','ejs');


todoController(app);

app.listen(3000);
console.log('listening on 3000');             


todoController.js

var bodyParser=require('body-parser');
var mongoose=require('mongoose');

//connect to Mongodb on the cloud
mongoose.connect('mongodb://test123:Pass123@ds257752.mlab.com:57752/todopavanmr',{useNewUrlParser: true});

//create database schema as an object | ORM
var todoSchema=new mongoose.Schema({
item:String
});

//Set the schema as the Model in the MVC Pattern
var Todo=mongoose.model('Todo',todoSchema);

//var data=[{item:'get milk'},{item:'walk the dog'},{item:'learn Nodejs'}];
var urlencodedParser=bodyParser.urlencoded({extended:false});

module.exports=function(app){
app.get('/todo',function(req,resp){
Todo.find({},function(err,data){
if (err) throw err;
resp.render('todo',{todos:data});
});
});

app.post('/todo',urlencodedParser,function(req,resp){
//data.push(req.body);
var newTodo=Todo(req.body).save(function(err,data){
if(err) throw err;
resp.render('todo',{todos:data});
});
});

app.delete('/todo/:item',function(req,resp){
Todo.find({item:req.params.item.replace(/\-/g," ")}).remove(function(err,data){
if(err) throw err;
resp.render('todo',{todos:data});
});
});

};

todo.ejs

<html>
<head>
<title>Product Backlog</title>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>

<script src="/assets/todo-list.js"></script>

<link href="/assets/todostyles.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<h1>My Todo List</h1>
<div id="todo-table">
<form>
<input type="text" name="item" placeholder="Add new Item...." required/>
<button type="submit">Add Item</button>
</form>
<ul>
<% for(var i=0; i < todos.length ;i++) { %>
<li><%=todos[i].item%></li>
<% } %>
</ul>
</div>
</body>
</html>

todo-list.js

$(document).ready(function(){ //wait for the page to load
$('form').on('submit',function(){ //resgister for submit button click in form
var item= $('form input'); //get ref to the text box on the form
var todo={item: item.val()}; //custom obj (item)= textbox value enteretd by the user
$.ajax({ //Async scope starts to fire async request to the server
type: 'POST', //send data in the body
url: '/todo',
data: todo, //data to be inserted (comes from textbox)
success: function (data){ //if all ok, refresh the page to display inserted data
location.reload(); //refreshes the page
}
});
return false; //return false on faliure
});

$('li').on('click',function(){
var item=$(this).text().replace(/ /g,"-");//clean the data of spaces
$.ajax({
type: 'DELETE',
url: '/todo/' + item, //append the item the user has clicked on to the url
success: function (data){
location.reload(); //refreshes the page
}
});
});
});

















No comments:

Post a Comment