Presentation is loading. Please wait.

Presentation is loading. Please wait.

Advanced Topics in Concurrency and Reactive Programming: MEAN Stack

Similar presentations


Presentation on theme: "Advanced Topics in Concurrency and Reactive Programming: MEAN Stack"— Presentation transcript:

1 Advanced Topics in Concurrency and Reactive Programming: MEAN Stack
Majeed Kassis

2 The history of LAMP (Stack)
LAMP gained power in 1998 (until 2010) JavaScript was mainly used for simple addition 10s of lines of code to allow dynamic webpages Browser wasn’t that powerful as it is today They did not have good JavaScript virtual machines V8, SpiderMonkey, Chakra, JavaScriptCore Thin Client & Fat Server was the way to go Everything is created by the server While the browser is used to view the results.

3 What is LAMP Linux Apache Php(Python/Perl) MySQL Javascript Front-End
Linux – as an OS Apache – as a Web Server MySQL – as a database PHP – as a server side scripting language Front-End Back-End Database Linux Apache Php(Python/Perl) MySQL Javascript

4 Problems with LAMP PHP began as a collection of functions written in C
Called “Personal Home Page”! PHP was rewritten in v3 and in v4 PHP v6 was never released Too many languages are needed JavaScript for frontend PHP for server backend SQL queries for the database Too many data conversions: 𝐽𝑆𝑂𝑁↔ 𝑃𝐻𝑃 𝑃𝐻𝑃↔𝑆𝑄𝐿 No separation between server side and client side development. Everything is done server-side

5 Data Binding Definition: In MVC, data binding One-Way Data Binding:
Automatically change a property when another property is changed. Automatically pulling information out an object into another object. In MVC, data binding Is the synchronization between the data model and the view: Allows displaying data to users Allows the user to edit the data One-Way Data Binding: When data in the model changes, the view reflects the change Two-Way Data Binding: When data in the view changes, the model is updated as well

6 Data Binding Two-Way : One-Way:

7 MVC/MVP/MVVM Architectures which promote the ‘separation of concerns’
As a result model, logic and user interfaces are decoupled. Benefit: Maintaining and testing is easier and simpler. MVC: Model-View-Controller MVP: Model-View-Presenter MVVM: Model-View-ViewController

8 MVC: Model-View-Controller
First introduced in 1970 Divides an application into three sections: Model View Controller Model: (Collection of classes) Contains the data (Database) Data accessing Data manipulation Controller: Processes incoming requests Input received from the User Modified the Model as needed. Passes results to View for presentation View: Represents the user interface components Displays the data received from the controller Data is stored in the view itself.

9 MVC Sequence Diagram Example
User sends requests to the Controller via the View after some interaction. And event is handled by the Controller, as a result the Model is manipulated as needed. The View is notified by the changes – in order to update the view to reflect these changes The View can request (apply queries) to retrieve data, directly with the Model itself.

10 MVP: Model-View-Presenter
Divides an application into three sections: Model View Presenter Model: Contains the data (Database) Data accessing Data manipulation Presenter: Processes incoming requests Input received from the View Modifies the Model as needed. Passes results to View for presentation View: Represents the user interface components Views the data received from the presenter No data in the view No Model-View interaction!

11 MVP Sequence Diagram Example

12 Advantages of MVP over MVC
Clarifies the structure of the user interface code and can make it easier to maintain. All complex screen logic will now reside in the Presenter. View consists only of screen drawing code (UI elements) Makes it much easier to replace user interface components, whole screens, or even the whole user interface Separating UI part of other parts of the application allows for better modularity.

13 MVVM: Model-View-ViewModel
Divides an application into three sections: Model View ViewModel Model: Contains the data (Database) Data accessing Data manipulation View: Represents the user interface components Contains UI elements only. ViewModel: It contains the ‘model’ of the view. All data the view requires are given by the ViewModel Value changes in the ViewModel will automatically propagate to the View itself. This is done via ‘data binding’ When the user clicks a button in the View, a command on the ViewModel executes to perform the requested action. The ViewModel, never the View, performs all modifications made to the model data.

14 MVVM Sequence Diagram Example

15 Summary

16 MEAN Stack A full-stack Javascript platform for web applications.
Front End (Client) Backend (Server) Database

17 MERN Stack

18 JSON: JavaScript Object Notation
A lightweight data-interchange format It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Used in: Communication between servers and browser clients. Language independent data interchange Communication between peers. Built on two structures: A collection of name/value pairs. An ordered list of values.

19 JSON Object An unordered set of name/value pairs
An object begins with { (left brace) and ends with } (right brace) Each name is followed by “:” and the name/value pairs are separated by “,”. {"firstName":"John", "lastName":"Doe"}

20 JSON Value A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

21 JSON Array An array is an ordered collection of values.
An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma). Value can be any of: string, number, object, array, true, false, null "employees":[     {"firstName":"John", "lastName":"Doe"},     {"firstName":"Anna", "lastName":"Smith"},     {"firstName":"Peter", "lastName":"Jones"} ]

22 JSON String A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. Default: UTF-8 A character is represented as a single character string. A string is very much like a C or Java string.

23 JSON Javascript API: stringify
Converting object to JSON string: Examples: var jsonstring = JSON.stringify(employee); JSON.stringify({}); // '{}' JSON.stringify(true); // 'true' JSON.stringify('foo'); // '"foo"' JSON.stringify([1, 'false', false]); // '[1,"false",false]' JSON.stringify({ x: 5 }); // '{"x":5}' JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)) // '" T15:04:05.000Z"' JSON.stringify({ x: 5, y: 6 }); // '{"x":5,"y":6}' or '{"y":6,"x":5}' JSON.stringify([new Number(1), new String('false'), new Boolean(false)]); // '[1,"false",false]'

24 JSON Javascript API: parse
Converting JSON string to object: Examples: var obj = JSON.parse(text); JSON.parse('{}'); // {} JSON.parse('true'); // true JSON.parse('"foo"'); // "foo" JSON.parse('[1, 5, "false"]'); // [1, 5, "false"] JSON.parse('null'); // null

25 Angular.js Javascript framework developed by Google
Development started in 2009 (Open Source) Based on Model-View-* Pattern (client-side) Supports MVC/MVP/MVVM Two-way data binding Used for create web applications. “Simple Page Application” Does not require page refresh. AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions. HTML is extended using ng-directives Full list next two slide.

26 Angular.js Directives – Part 1
ng-app Declares an HTML element as the root of the AngularJS application. Mostly used on <html> or <body> Only one instance can be used per HTML file. ng-init Initializes application variables/data. ng-bind Automatically changes the text of an HTML element to the value of a given expression. Enforce one-way binding. ng-model Enforces two-way binding.

27 Angular.js Expressions and Data Binding
<div ng-app="" ng-init="firstName='John'"> <p>Name: <input type="text" ng-model="firstName"></p> <p>You wrote: {{ firstName }}</p> </div> ng-app defines the code between <div> ..</div> as an Angular.js application. ng-init will initialize ‘firstName’ variable with the value ‘John’ AngularJS will evaluate expressions: Syntax: {{ code }} Example: {{ }} AngularJS data binding is done using ng-model In this example, variable “firstName” is bound to the text input.

28 Angular.js Directives – Part 2
ng-repeat Instantiate an element once per item from a collection. <div ng-app="" ng-init="names=[ {name:'Jani',country:'Norway'}, {name:'Hege',country:'Sweden'}, {name:'Kai',country:'Denmark'}]"> <ul>   <li ng-repeat="x in names">     {{ x.name + ', ' + x.country }}   </li> </ul> </div> <div ng-app="" ng-init="names=['Jani','Hege','Kai']">   <ul>     <li ng-repeat="x in names">       {{ x }}     </li>   </ul> </div>

29 Angular.js Directives – Part 3
ng-show & ng-hide Conditionally show or hide an element, depending on the value of a boolean expression. Example: If ‘myVar’s value is true the <div> … </div> scope will be shown Otherwise it will be hidden. ng-hide is the negative version of ng-show Show HTML: <input type="checkbox" ng-model="myVar"> <div ng-show="myVar"> <h1>Welcome</h1> <p>Welcome to my home.</p> </div>

30 Angular.js Examples – Part 4
ng-controller Specifies a JavaScript controller class that evaluates HTML expressions Used to write the functions And define variables To manipulate the HTML file. <div ng-app="myApp" ng-controller="myCtrl"> Full Name: {{firstName + " " + lastName}} </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) {     $scope.firstName = "John";     $scope.lastName = "Doe"; }); </script>

31 Angular.js has a long list of directives
See full list here:

32 Node.js - https://node.green/
First released in 2009 Written in C++ Node.js is a platform built on Chrome's v8 JavaScript runtime. Used to build scalable network applications. Node.js built using an event-driven, non-blocking I/O model Same as AsyncIO, but in Javascript. Using Node.js which will act as the server We can implement our server logic. This is done using Javascript! It can be any type of server.

33 Installing Node.js Server: Hello World Server
Create Javascript file, and run node with it as its ‘main’ file: Command: node main.js All program logic will handle the ‘request’ object received. var http = require(“http”); http.createServer(function (request, response) { // Send the HTTP header // HTTP Status: 200 : OK // Content Type: text/plain response.writeHead(200, {'Content-Type': 'text/plain'}); // Send the response body as "Hello World" response.end('Hello World\n'); }).listen(8081); // Console will print the message console.log('Server running at

34 Express.js Fast, unopinionated, minimalist web framework for Node.js
Used to implement server-side logic. Uses ReSTful API (REpresentational State Transfer) Implements HTTP methods (GET, POST, DELETE, PUT) Stateless Exposes directory structure-like URIs. Data transfer uses XML, JSON, or both. Addressability is done via URIs: Depending on a URI we can callback a specific function to handle the request. Example: GET /index.html GET is the method /index.html is the URI

35 Express HelloWorld var express = require('express')
var app = express() app.get('/', function (req, res) { res.send('hello world') }) app.post('/', function (req, res) { res.send('POST request to the homepage') app.put('/user', function (req, res) { res.send('Got a PUT request at /user') app.delete('/user', function (req, res) { res.send('Got a DELETE request at /user')

36 Creating Express Server

37 Middleware Functions Middleware allows to define a stack of actions executed in sequence. Express servers themselves are a stack of middlewares. Middleware functions are functions that have access to: the request object (req) the response object (res) the next middleware function Middleware functions can perform the following tasks: Execute any code Make changes to the request and the response objects End the request-response cycle Call the next middleware function in the stack Calling next middleware is done explicitly This is done using next()

38 Creating Middleware Application level middleware
Used in every request for a specific URI. Syntax: app.use(‘URI’, function) Use Example: logging Router level middleware Can be used for a specific request type and its URI. But can be used for application-level as well! Syntax: app.get(‘URI’, router) Can be done for other HTTP functions as well.

39 Application Level Middleware
app.use('/user/:id', function (req, res, next) { console.log('Request URL:', req.originalUrl) next() }, function (req, res, next) { console.log('Request Type:', req.method) }) This is handled for all server functions Only for the ‘/user/:id’ URI. Without executing next(), the next middleware function will not be executed!

40 Router Level Middleware
var app = express() var router = express.Router() router.use(function (req, res, next) { console.log('Time:', Date.now()) next() router.use('/user/:id', function (req, res, next) { console.log('Request URL:', req.originalUrl) next() }, function (req, res, next) { console.log('Request Type:', req.method) next() }) // mount the router on the app.get() function app.get('/', router)

41

42

43

44

45

46 MEAN vs LAMP


Download ppt "Advanced Topics in Concurrency and Reactive Programming: MEAN Stack"

Similar presentations


Ads by Google