MEAN.JS WORKSHOP
Michael Haberman
Freelancer
TODAY TASK
Get to know MEAN.js
See some code
Write some code
Understand the benefits of
MEAN.js
Experience the benefits of hotel
lunch
THE FULLSTACK SOLUTION
Most web apps uses the following layers:
client side (probably some framework)
API layer for client communication
backend (maybe couple of layers [dal, bl etc..])
DB
WHY DO WE STACK?
we could use Ember / knockout / Backbone instead of Angular
we could use Loopback.io / sails / hapi instead of Express
we could use CouchBase instead of MongoDB
Why MEAN.js?
easy to glow
eco-system
DEMO
The app we will develop today
APP ARCHITECTURE
Browser - Angular JS
API - Express
Backend - Node JS
DB - MongoDB
ROLES
Node.js - the server framework
Express - extending node
Angular - client side
MongoDB - the DB
WHAT IS NODE? AND WHY?
NODE.js server side based on Javascript
Base on chrome v8 engine
NON blocking
Event driven
JS both client / server
Huge community
Open source
WHAT DOES NODE PROVIDE?
https://nodejs.org/api/
NODE AS HTTP SERVER
var http = require(‘http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello Worldn');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
BLOCKING
function handleRequest(req){
saveToDB(req); // 100 ms
var user = getUserByReq(req); //150 ms
user.reqCount++;
notifyUser(user); // 70 ms
}
Total: 320 ms
NON -BLOCKING
function handleRequest(req){
db.saveNewReq(req, callback); //100 ms
db.getUser(req, function(user){
user.reqCount++;
notifyUser(user); // 70
}); //150 ms
}
Total: 100 ms parallel to 220ms-> 220 ms top.
EVENT DRIVEN?
operation(operationData, function(err,data){
});
db.query(‘select email from users where id = 4’, function(err,
email){
if(err) throw err;
sendByEmail(email);
});
CALLBACK HELL
var q1 = “select id from users where username = ‘Michael’”;
var q2 = “select postID from blogPost where userid =“+ id +””;
var q3 = “select attachment from post where postID =“+ post +””;
db.query(q1,function(…){
db.query(q2,function(…){
db.query(q1,function(…){
})
})
})
AVOID CALLBACK HELL
Use named functions
Small js files
Async library (or any other like it)
We will deal with that a bit later
NODE IS SINGLE THREADED
Single thread?!
Multi-process solution
SO NODE IS GOOD, WHY
ANOTHER LAYER?
Node is like a programming language
Node will provide low level http handling (listen to port,
response)
Node will not provide routing solution
ROLES
Node.js - the server framework
Express - extending node
Angular - client side
MongoDB - the DB
EXPRESS
High level http server
API Route
Template
Middleware
http://expressjs.com/
EXPRESS HTTP SERVER
var express = require('express');
var app = express();
app.get(‘/api/test', function(req, res) {
res.statusCode(200).json({response : “works!”});
});
app.listen(1234);
CODE TIME!
Node + Express
Api for authentication
ROLES
Node.js - the server framework
Express - extending node
Angular - client side
MongoDB - the DB
ANGULAR JS
Web app are getting complex
We need our client to be well designed, testable and easy to
maintain
Angular is an “all around” framework
ANGULAR KEY CONCEPTS
MVC
Directive
Sharing data / logic
Dependency Injection
Routing - SPA (Single Page Application)
ANGULAR MVC
VIEW
Controller
Model
ANGULAR - SIMPLE MVC
angular.module(‘main’).controller(‘myCntr’, function($scope){
$scope.sayHello = “Hello from controller”;
});
<div>
{{sayHello}}
</div>
ANGULAR - TWO WAY
BINDING & DIRECTIVE
angular.module(‘main’).controller(‘myCntr’, function($scope){
$scope.alertData = function(){
alert($scope.dataFromUI);
}
});
<div>
<input type=‘text’ ng-model=‘dataFromUI’/>
<input type=‘button’ value=‘alert data’ ng-click=‘alertData()’/>
</div>
Method to invoke
on click
Two way binding
SHARING DATA & LOGIC
Typical Angular app will have many controllers
Some of them would like to share data & logic
Login is always a common thing
There are few ways for sharing, we will start with Service
LOGIN SERVICE
angular.module(‘main’).serivce(‘loginService’,function(){
var self = this;
self.isLoggedin = false;
self.login = function(username,password){
// execute login logic
self.isLoggedin = true;
}
return self;
});
LOGIN SERVICE - DI
angular.module(‘main’)
.controller(‘controllerA’, function($scope, loginService){
loginService.login(‘michael’, 123);
});
angular.module(‘main’)
.controller(‘controllerB’, function($scope, loginService){
alert(loginService.isLoggedIn);
});
SERVICE VS FACTORY
There are several way to share things in Angular app:
service
factory
value
const
provider
FACTORY
angular.module(‘main’).factory(‘calculationFactory’, function(){
return {
calc: function(num1, num2){
// make some work here;
};
};
});
ANGULAR ROUTING
Route is what makes SPA possible
html 5 anchors (www.site.com/#/localchanges…)
/# some place in the site:
view (html page)
controller
ANGULAR ROUTING
angular.module(‘demo’).config([‘$routeProvider’,
function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: 'views/login.html',
controller: 'loginController'
}).
when('/homepage', {
templateUrl: 'views/items.html',
controller: 'itemsController'
}).
otherwise({
redirectTo: '/login'
});
}]);
CODE TIME!
Angular
login page (view + controller)
login service - access API
route
ROLES
Node.js - the server framework
Express - extending node
Angular - client side
MongoDB - the DB
NO SQL
Table free structure
no structure?
key-value
document
wide column
graph db
NO SQL - KEY VALUE
key value pairs
DB doesn't ware of the meaning
AWS DynamoDB, MemcacheDB
NO SQL - DOCUMENT
key -> Documents (usually structured - JSON)
DB is ware of the structure to allow querying
MongoDB
NO SQL - WIDE COLUMNS
row -> columns
columns are defined per row & not per table
Benefits from being structured & dynamic
Cassandra
NO SQL - GRAPH
Every item is related to other items
SQL OR NOSQL
DB is a tool to solve a problem
Understand the problem
Understand to tools
Make a decision
NOSQL - PROS
Scale out
Meant for big data
Less need of DBA
Dynamic data model
clustering
replication
NOSQL - CONS
Maturity
No official support
Less analytics
Less powerful indexes
Less powerful transaction
No standart
Complex queries
MONGODB
MongoDB is document base NoSQL database
Fast, easy, scaleable, structured but still dynamic.
MONGODB AND MONGOOSE
MongoDB does not provide object-model
Hard to work with
Let’s see some code
MONGOOSE DATA MODEL
Data model makes our development easier
enforce standart!
Let’s see how it looks
MONGOOSE BENEFITS
Model defintion includes:
types
validation (required)
error message
getter / setters
default values
in memory methods
DATA MODEL
var itemSchema = new Schema({
_Id: Schema.Types.String,
title: {type:String, required:true},
description: String,
category: {type: String, set: upperCase},
createTime: {type: Date, default: Date.now},
lastUpdateTime: Date,
price: {type: Number, validator: positiveNumber, msg: 'price has to be positive
number'}
});
CODE TIME!
Backend uses mongoose
create use schema
ROBO-MONGO
Nice tool to view & edit mongoldb instances
TOKENS
SERVER
CLIENT
sends
username +
password
validate and issue
token
saves to token and
sends it with every
request
token expires
after X
CODE TIME!
Use “jsonwebtoken” to issue & validate tokens
jsonwebtoken.sign(user, ‘key’, {expiresIn:2h});
jsonwebtoken.verify(token, ‘key’, function(err, decode){});
Delete Item
models.User({ _id:333 }).remove().exec(callback);
CODE TIME
MONGODB - QUERY
Person.
find({ occupation: /host/ }).
where('name.last').equals('Ghost').
where('age').gt(17).lt(66).
where('likes').in(['vaporizing', 'talking']).
limit(10).
sort('-occupation').
select('name occupation').
exec(callback);
CONTACT DETAILS
Email: michael@haberman.io
Twitter: @hab_mic
Site: http://haberman.io
Blog: http://blogs.microsoft.co.il/michaelh/

MEAN.js Workshop

  • 1.
  • 2.
    TODAY TASK Get toknow MEAN.js See some code Write some code Understand the benefits of MEAN.js Experience the benefits of hotel lunch
  • 3.
    THE FULLSTACK SOLUTION Mostweb apps uses the following layers: client side (probably some framework) API layer for client communication backend (maybe couple of layers [dal, bl etc..]) DB
  • 4.
    WHY DO WESTACK? we could use Ember / knockout / Backbone instead of Angular we could use Loopback.io / sails / hapi instead of Express we could use CouchBase instead of MongoDB Why MEAN.js? easy to glow eco-system
  • 5.
    DEMO The app wewill develop today
  • 6.
    APP ARCHITECTURE Browser -Angular JS API - Express Backend - Node JS DB - MongoDB
  • 7.
    ROLES Node.js - theserver framework Express - extending node Angular - client side MongoDB - the DB
  • 8.
    WHAT IS NODE?AND WHY? NODE.js server side based on Javascript Base on chrome v8 engine NON blocking Event driven JS both client / server Huge community Open source
  • 9.
    WHAT DOES NODEPROVIDE? https://nodejs.org/api/
  • 10.
    NODE AS HTTPSERVER var http = require(‘http'); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello Worldn'); }).listen(8124); console.log('Server running at http://127.0.0.1:8124/');
  • 11.
    BLOCKING function handleRequest(req){ saveToDB(req); //100 ms var user = getUserByReq(req); //150 ms user.reqCount++; notifyUser(user); // 70 ms } Total: 320 ms
  • 12.
    NON -BLOCKING function handleRequest(req){ db.saveNewReq(req,callback); //100 ms db.getUser(req, function(user){ user.reqCount++; notifyUser(user); // 70 }); //150 ms } Total: 100 ms parallel to 220ms-> 220 ms top.
  • 13.
    EVENT DRIVEN? operation(operationData, function(err,data){ }); db.query(‘selectemail from users where id = 4’, function(err, email){ if(err) throw err; sendByEmail(email); });
  • 14.
    CALLBACK HELL var q1= “select id from users where username = ‘Michael’”; var q2 = “select postID from blogPost where userid =“+ id +””; var q3 = “select attachment from post where postID =“+ post +””; db.query(q1,function(…){ db.query(q2,function(…){ db.query(q1,function(…){ }) }) })
  • 15.
    AVOID CALLBACK HELL Usenamed functions Small js files Async library (or any other like it) We will deal with that a bit later
  • 16.
    NODE IS SINGLETHREADED Single thread?! Multi-process solution
  • 17.
    SO NODE ISGOOD, WHY ANOTHER LAYER? Node is like a programming language Node will provide low level http handling (listen to port, response) Node will not provide routing solution
  • 18.
    ROLES Node.js - theserver framework Express - extending node Angular - client side MongoDB - the DB
  • 19.
    EXPRESS High level httpserver API Route Template Middleware http://expressjs.com/
  • 20.
    EXPRESS HTTP SERVER varexpress = require('express'); var app = express(); app.get(‘/api/test', function(req, res) { res.statusCode(200).json({response : “works!”}); }); app.listen(1234);
  • 21.
    CODE TIME! Node +Express Api for authentication
  • 22.
    ROLES Node.js - theserver framework Express - extending node Angular - client side MongoDB - the DB
  • 23.
    ANGULAR JS Web appare getting complex We need our client to be well designed, testable and easy to maintain Angular is an “all around” framework
  • 24.
    ANGULAR KEY CONCEPTS MVC Directive Sharingdata / logic Dependency Injection Routing - SPA (Single Page Application)
  • 25.
  • 26.
    ANGULAR - SIMPLEMVC angular.module(‘main’).controller(‘myCntr’, function($scope){ $scope.sayHello = “Hello from controller”; }); <div> {{sayHello}} </div>
  • 27.
    ANGULAR - TWOWAY BINDING & DIRECTIVE angular.module(‘main’).controller(‘myCntr’, function($scope){ $scope.alertData = function(){ alert($scope.dataFromUI); } }); <div> <input type=‘text’ ng-model=‘dataFromUI’/> <input type=‘button’ value=‘alert data’ ng-click=‘alertData()’/> </div> Method to invoke on click Two way binding
  • 28.
    SHARING DATA &LOGIC Typical Angular app will have many controllers Some of them would like to share data & logic Login is always a common thing There are few ways for sharing, we will start with Service
  • 29.
    LOGIN SERVICE angular.module(‘main’).serivce(‘loginService’,function(){ var self= this; self.isLoggedin = false; self.login = function(username,password){ // execute login logic self.isLoggedin = true; } return self; });
  • 30.
    LOGIN SERVICE -DI angular.module(‘main’) .controller(‘controllerA’, function($scope, loginService){ loginService.login(‘michael’, 123); }); angular.module(‘main’) .controller(‘controllerB’, function($scope, loginService){ alert(loginService.isLoggedIn); });
  • 31.
    SERVICE VS FACTORY Thereare several way to share things in Angular app: service factory value const provider
  • 32.
  • 33.
    ANGULAR ROUTING Route iswhat makes SPA possible html 5 anchors (www.site.com/#/localchanges…) /# some place in the site: view (html page) controller
  • 34.
    ANGULAR ROUTING angular.module(‘demo’).config([‘$routeProvider’, function($routeProvider) { $routeProvider. when('/login',{ templateUrl: 'views/login.html', controller: 'loginController' }). when('/homepage', { templateUrl: 'views/items.html', controller: 'itemsController' }). otherwise({ redirectTo: '/login' }); }]);
  • 35.
    CODE TIME! Angular login page(view + controller) login service - access API route
  • 36.
    ROLES Node.js - theserver framework Express - extending node Angular - client side MongoDB - the DB
  • 37.
    NO SQL Table freestructure no structure? key-value document wide column graph db
  • 38.
    NO SQL -KEY VALUE key value pairs DB doesn't ware of the meaning AWS DynamoDB, MemcacheDB
  • 39.
    NO SQL -DOCUMENT key -> Documents (usually structured - JSON) DB is ware of the structure to allow querying MongoDB
  • 40.
    NO SQL -WIDE COLUMNS row -> columns columns are defined per row & not per table Benefits from being structured & dynamic Cassandra
  • 41.
    NO SQL -GRAPH Every item is related to other items
  • 42.
    SQL OR NOSQL DBis a tool to solve a problem Understand the problem Understand to tools Make a decision
  • 43.
    NOSQL - PROS Scaleout Meant for big data Less need of DBA Dynamic data model clustering replication
  • 44.
    NOSQL - CONS Maturity Noofficial support Less analytics Less powerful indexes Less powerful transaction No standart Complex queries
  • 45.
    MONGODB MongoDB is documentbase NoSQL database Fast, easy, scaleable, structured but still dynamic.
  • 46.
    MONGODB AND MONGOOSE MongoDBdoes not provide object-model Hard to work with Let’s see some code
  • 47.
    MONGOOSE DATA MODEL Datamodel makes our development easier enforce standart! Let’s see how it looks
  • 48.
    MONGOOSE BENEFITS Model defintionincludes: types validation (required) error message getter / setters default values in memory methods
  • 49.
    DATA MODEL var itemSchema= new Schema({ _Id: Schema.Types.String, title: {type:String, required:true}, description: String, category: {type: String, set: upperCase}, createTime: {type: Date, default: Date.now}, lastUpdateTime: Date, price: {type: Number, validator: positiveNumber, msg: 'price has to be positive number'} });
  • 50.
    CODE TIME! Backend usesmongoose create use schema
  • 51.
    ROBO-MONGO Nice tool toview & edit mongoldb instances
  • 52.
    TOKENS SERVER CLIENT sends username + password validate andissue token saves to token and sends it with every request token expires after X
  • 53.
    CODE TIME! Use “jsonwebtoken”to issue & validate tokens jsonwebtoken.sign(user, ‘key’, {expiresIn:2h}); jsonwebtoken.verify(token, ‘key’, function(err, decode){});
  • 54.
    Delete Item models.User({ _id:333}).remove().exec(callback); CODE TIME
  • 55.
    MONGODB - QUERY Person. find({occupation: /host/ }). where('name.last').equals('Ghost'). where('age').gt(17).lt(66). where('likes').in(['vaporizing', 'talking']). limit(10). sort('-occupation'). select('name occupation'). exec(callback);
  • 56.
    CONTACT DETAILS Email: michael@haberman.io Twitter:@hab_mic Site: http://haberman.io Blog: http://blogs.microsoft.co.il/michaelh/