MEAN.js Workshop
-
Upload
michael-haberman -
Category
Software
-
view
423 -
download
0
Transcript of MEAN.js Workshop
MEAN.JS WORKSHOPMichael HabermanFreelancer
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
NODE AS HTTP SERVERvar http = require(‘http');
http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello World\n');}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
BLOCKINGfunction handleRequest(req){saveToDB(req); // 100 msvar user = getUserByReq(req); //150 msuser.reqCount++;notifyUser(user); // 70 ms
}Total: 320 ms
NON -BLOCKINGfunction handleRequest(req){db.saveNewReq(req, callback); //100 msdb.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 HELLvar 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 SERVERvar 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 MVCangular.module(‘main’).controller(‘myCntr’, function($scope){
$scope.sayHello = “Hello from controller”;});
<div>{{sayHello}}
</div>
ANGULAR - TWO WAY BINDING & DIRECTIVEangular.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 SERVICEangular.module(‘main’).serivce(‘loginService’,function(){
var self = this;self.isLoggedin = false;self.login = function(username,password){
// execute login logicself.isLoggedin = true;
}return self;
});
LOGIN SERVICE - DIangular.module(‘main’)
.controller(‘controllerA’, function($scope, loginService){loginService.login(‘michael’, 123);
});angular.module(‘main’)
.controller(‘controllerB’, function($scope, loginService){alert(loginService.isLoggedIn);
});
SERVICE VS FACTORYThere are several way to share things in Angular app:
service
factory
value
const
provider
FACTORYangular.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 ROUTINGangular.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 SQLTable 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 - PROSScale out
Meant for big data
Less need of DBA
Dynamic data model
clustering
replication
NOSQL - CONSMaturity
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 BENEFITSModel defintion includes:
types
validation (required)
error message
getter / setters
default values
in memory methods
DATA MODELvar 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 - QUERYPerson. 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: [email protected]
Twitter: @hab_mic
Site: http://haberman.io
Blog: http://blogs.microsoft.co.il/michaelh/