MEAN.js Workshop

56
MEAN.JS WORKSHOP Michael Haberman Freelancer

Transcript of MEAN.js Workshop

Page 1: MEAN.js Workshop

MEAN.JS WORKSHOPMichael HabermanFreelancer

Page 2: MEAN.js Workshop

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

Page 3: MEAN.js Workshop

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

Page 4: MEAN.js Workshop

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

Page 5: MEAN.js Workshop

DEMO

The app we will develop today

Page 6: MEAN.js Workshop

APP ARCHITECTURE

Browser - Angular JS

API - Express

Backend - Node JS

DB - MongoDB

Page 7: MEAN.js Workshop

ROLES

Node.js - the server framework

Express - extending node

Angular - client side

MongoDB - the DB

Page 8: MEAN.js Workshop

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

Page 9: MEAN.js Workshop

WHAT DOES NODE PROVIDE?

https://nodejs.org/api/

Page 10: MEAN.js Workshop

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

Page 11: MEAN.js Workshop

BLOCKINGfunction handleRequest(req){saveToDB(req); // 100 msvar user = getUserByReq(req); //150 msuser.reqCount++;notifyUser(user); // 70 ms

}Total: 320 ms

Page 12: MEAN.js Workshop

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.

Page 13: MEAN.js Workshop

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

});

Page 14: MEAN.js Workshop

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(…){ })

})})

Page 15: MEAN.js Workshop

AVOID CALLBACK HELL

Use named functions

Small js files

Async library (or any other like it)

We will deal with that a bit later

Page 16: MEAN.js Workshop

NODE IS SINGLE THREADED

Single thread?!

Multi-process solution

Page 17: MEAN.js Workshop

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

Page 18: MEAN.js Workshop

ROLES

Node.js - the server framework

Express - extending node

Angular - client side

MongoDB - the DB

Page 19: MEAN.js Workshop

EXPRESS

High level http server

API Route

Template

Middleware

http://expressjs.com/

Page 20: MEAN.js Workshop

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

Page 21: MEAN.js Workshop

CODE TIME!

Node + Express

Api for authentication

Page 22: MEAN.js Workshop

ROLES

Node.js - the server framework

Express - extending node

Angular - client side

MongoDB - the DB

Page 23: MEAN.js Workshop

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

Page 24: MEAN.js Workshop

ANGULAR KEY CONCEPTS

MVC

Directive

Sharing data / logic

Dependency Injection

Routing - SPA (Single Page Application)

Page 25: MEAN.js Workshop

ANGULAR MVC

VIEW

Controller

Model

Page 26: MEAN.js Workshop

ANGULAR - SIMPLE MVCangular.module(‘main’).controller(‘myCntr’, function($scope){

$scope.sayHello = “Hello from controller”;});

<div>{{sayHello}}

</div>

Page 27: MEAN.js Workshop

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

Page 28: MEAN.js Workshop

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

Page 29: MEAN.js Workshop

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;

});

Page 30: MEAN.js Workshop

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

});

Page 31: MEAN.js Workshop

SERVICE VS FACTORYThere are several way to share things in Angular app:

service

factory

value

const

provider

Page 32: MEAN.js Workshop

FACTORYangular.module(‘main’).factory(‘calculationFactory’, function(){

return {calc: function(num1, num2){

// make some work here;};

};});

Page 33: MEAN.js Workshop

ANGULAR ROUTING

Route is what makes SPA possible

html 5 anchors (www.site.com/#/localchanges…)

/# some place in the site:

view (html page)

controller

Page 34: MEAN.js Workshop

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' }); }]);

Page 35: MEAN.js Workshop

CODE TIME!

Angular

login page (view + controller)

login service - access API

route

Page 36: MEAN.js Workshop

ROLES

Node.js - the server framework

Express - extending node

Angular - client side

MongoDB - the DB

Page 37: MEAN.js Workshop

NO SQLTable free structure

no structure?

key-value

document

wide column

graph db

Page 38: MEAN.js Workshop

NO SQL - KEY VALUE

key value pairs

DB doesn't ware of the meaning

AWS DynamoDB, MemcacheDB

Page 39: MEAN.js Workshop

NO SQL - DOCUMENT

key -> Documents (usually structured - JSON)

DB is ware of the structure to allow querying

MongoDB

Page 40: MEAN.js Workshop

NO SQL - WIDE COLUMNS

row -> columns

columns are defined per row & not per table

Benefits from being structured & dynamic

Cassandra

Page 41: MEAN.js Workshop

NO SQL - GRAPH

Every item is related to other items

Page 42: MEAN.js Workshop

SQL OR NOSQL

DB is a tool to solve a problem

Understand the problem

Understand to tools

Make a decision

Page 43: MEAN.js Workshop

NOSQL - PROSScale out

Meant for big data

Less need of DBA

Dynamic data model

clustering

replication

Page 44: MEAN.js Workshop

NOSQL - CONSMaturity

No official support

Less analytics

Less powerful indexes

Less powerful transaction

No standart

Complex queries

Page 45: MEAN.js Workshop

MONGODB

MongoDB is document base NoSQL database

Fast, easy, scaleable, structured but still dynamic.

Page 46: MEAN.js Workshop

MONGODB AND MONGOOSE

MongoDB does not provide object-model

Hard to work with

Let’s see some code

Page 47: MEAN.js Workshop

MONGOOSE DATA MODEL

Data model makes our development easier

enforce standart!

Let’s see how it looks

Page 48: MEAN.js Workshop

MONGOOSE BENEFITSModel defintion includes:

types

validation (required)

error message

getter / setters

default values

in memory methods

Page 49: MEAN.js Workshop

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

Page 50: MEAN.js Workshop

CODE TIME!

Backend uses mongoose

create use schema

Page 51: MEAN.js Workshop

ROBO-MONGO

Nice tool to view & edit mongoldb instances

Page 52: MEAN.js Workshop

TOKENS

SERVER

CLIENT

sends username +

password

validate and issue token

saves to token and sends it with

every request

token expires after X

Page 53: MEAN.js Workshop

CODE TIME!

Use “jsonwebtoken” to issue & validate tokens

jsonwebtoken.sign(user, ‘key’, {expiresIn:2h});

jsonwebtoken.verify(token, ‘key’, function(err, decode){});

Page 54: MEAN.js Workshop

Delete Item

models.User({ _id:333 }).remove().exec(callback);

CODE TIME

Page 55: MEAN.js Workshop

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

Page 56: MEAN.js Workshop

CONTACT DETAILS

Email: [email protected]

Twitter: @hab_mic

Site: http://haberman.io

Blog: http://blogs.microsoft.co.il/michaelh/