Saturday, February 25, 2017

RxJs Quick start

Reactive Programming is a pattern of development that works with asynchronous data stream created of UI Events, HTTP Requests, File System, cache etc. So data stream is an ongoing event sequence in time orderly manner. Stream can emit value, error, and status signal.

Observables are to watch these streams and trigger function on anything occurs in the stream. Observers can subscribe to observables.

RxJs is the library which helps us to do the exact same implementation in our project.

As per MSDN -
Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. Reactive Extensions represents all these data sequences as observable sequences. An application can subscribe to these observable sequences to receive asynchronous notifications as new data arrive. 

Great let’s see some RxJs Code and see how it works -

Example 1 –

import Rx from 'rxjs/Rx'; //import Rxjs
  
const src$ = new Rx.Observable.create(function (observer) {  //Create observable  
// Each next inside Observable will trigger subscribed function.
 observer.next('hi'); 
    observer.next('hello');
    setTimeout(function () {
        observer.next('bye');
        observer.complete();// Will end the observer
    }, 3000);
    //observer.error(new Error('Error'));// <-- uncomment the throw error
});

src$.subscribe(
    function (e) {
        console.log(e);// will execute when any change in Observable
    },
    function (er) {
        console.log(er);// will be called when error
    }, function () {
        console.log('completed'); // will be called when done
    }
 );
See comments for detail understanding.

Few more examples.

Example 2 – (Event Observable)

import $ from 'jquery';  //import jquery
import Rx from 'rxjs/Rx'; //import Rxjs
const btn = $('#btn'); // get element
const input = $('#inp');
    
const btnStream$ = Rx.Observable.fromEvent(btn, 'click'); // set observable event
btnStream$.scbscribe( // Subscribe to the event, to call function when event occurs
    function (e) {
        console.log(e);
    },
    function (er) { // error handling
        console.log(err);
    }, function () { // called when completed
        //completed
    });

const inputStream$ = Rx.Observable.fromEvent(input, 'keyup');

btnStream$.scbscribe(
    function (e) {
        console.log(e);
    },
    function (er) {
        console.log(err);
    }, function () {
        //completed
    });

Example 3- (Observable Array)

import Rx from 'rxjs/Rx';
   
const numbers = [1, 2, 3, 4, 5];
const numberStream$ = Rx.Observable.from(numbers);// Make array Observable
numberStream$.subscribe( // Subscribe to the array observable
    function (e) {
        console.log(e);
    },
    function (er) {
        console.log(err);
    }, function () {
        //completed
    });
   
Further study - https://xgrommx.github.io/rx-book/why_rx.html

Friday, February 17, 2017

TypeScript Intro


TypeScript is a typed superset of Javascript. “  

Let’s see what does this line means.  TypeScript is typed; it has the ability to define typed variables. In core javascript, we use “var” to initialize a variable or function. But in TypeScript, we can specify the type (Like- string, number, Boolean, etc.) of it while initializing. TypeScript is also a superset of javascript, that means any javascript code should work properly inside TypeScript. In other words, all Javascript is valid inside TypeScript.  So we can say, it is javascript with some more advanced features.

Ok, now let’s think, we created a web application using TypeScript. If we try to run that in our browser, it will not work as it is not core javascript, so it is not compilable by our browser engine. So to overcome we have something called transpiler, which will compile TypeScript code to core javascript which can get executed in a browser.
Microsoft has created this TypeScript transpiler. It comes with typescript package. So it install TypeScript, open your terminal and run-

>npm install –g typescript

So now typescript is installed. If you now run following, you should see the typescript transpiler version.

>tsc  --version

Now use VSCode editor for coding. It has inbuilt .ts type support.
Well, open your working folder in VSCode and create a file, name it Employee.ts. Yes , the extension will be .ts not .js.  Put the following code in the file-

//Interface
interface IEmployee { //defining interface
    yearOfJoin: number;// interface  property
    loyality : () => number;// interface function
}
//Base Class
class Company { //create class
    constructor(public name: string, public country: string) { //define constructor
                this.name = name;
                this.country = country;
    }
    public Details(details: string) {            
        return ('Company Name:' + this.name + ' Country: ' + this. country + ' Details: ' + details);
    }
}
//Child Class implements IEmployee and inherits from Company
class Employee extends Company implements IEmployee { //create class extend company and implement IEmployee
    firstName: string; // typed variable
    lastName: string;
    yearOfJoin: number;
    //private _company: Company;
    //Constructor           
    constructor(firstName: string, lastName: string, companyName: string, country: string, yearOfJoin: number) {
        super(companyName, country);
        this.firstName = firstName;
        this.lastName = lastName;
        this. yearOfJoin = yearOfJoin;
    }
    loyality () {
        return 2017 - this. yearOfJoin;  // as 2017 is current year
    }
    CompanyDetails() {
        var y = super. Details (' Software Company with CMMI lavel');
        console.log(y);
    }
    printDetails(): void {
        alert(this.firstName + ' ' + this.lastName + ' Company is: ' + this.name);
    }
}

Save the file and run-

>tsc Employee.ts --target ES5 --outDir js --watch

Here we are running typescript transpiler with following arguments –

1.       Typescript files to be compiled.
2.       Compiled to which js version.(ES5/ES6)
3.       What should be the output directory.(js)
4.       Watch the files as mentions in the first argument, and whenever any changes, compile it to js.

Note: for more options execute-  
> tsc –help

After the execution you should see a js folder inside your current folder. And the js folder will contain your compiled .js files form provided .ts files.


See code comments for clear understanding.

Friday, February 3, 2017

Express With MongoDB - Quick start

Let's access MongoDB from Nodejs using Express. 

What is Express? 
As per Express site, it's a minimal and flexible Node.js web application framework that provides a robust set of features for the web and mobile applications.

Features
·         Robust routing
·         Focus on high performance
·         Super-high test coverage
·         HTTP helpers (redirection, caching, etc)
·         View system supporting 14+ template engines
·         Content negotiation
·         Executable for generating applications quickly

Great.Lets start. (Assumed you have Nodejs and MongoDB installed, if not ,check Nodejs MongoDb)

Create a folder and run following command on your terminal-

 > npm init

It will ask you few questions (Like- Name for the project, author, version). For now, you can keep all the default values. This will give you your package.json inside the same folder.

Greate execute this now-

> npm install --save express
mongoose morgan body-parser

So here, we actually installed Express along with mongoose which is a Node.js library that provides MongoDB object mapping similar to ORM with a familiar interface within Node.js and Morgan which is basically used for logging request details. And body-parser parses incoming request bodies in a middleware before your handlers, available under the req.body property.

Now you should see a folder named node_modules inside your current folder. Inside node_modules all your installed node packages reside. We are now ready to go further.

Let's create a file and name it server.js. Put the following code and save it.

var express = require('express'); // load express module in your project

var morgan = require('morgan'); // load morgan module 

var mongoose = require('mongoose'); //load mongoose module 

var bodyParser = require('body-parser'); // load body-parser module 

var app = express(); //init express
var port = process.env.PORT || 6064; //allocate the port for your server
app.use(express.static('./public')); // set folder for public items , such as - image , css, html, client side js
app.use(morgan('dev')); // init morgan for logging request details
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

mongoose.connect('mongodb://localhost/mongodbtest'); // mongodb connection

routesetup(app);// set your route details with path and its handlers 
app.listen(port);// start your server
console.log("App listening on port " + port); 


function routesetup(app) { // function for route setup
   app.use( function (req, res, next) {  // will be executed for all request
        console.log(req.url);
        next();
    });
    app.use( function (err, req, res, next) { // will be executed for all error
        console.log(err);
        next();
    });    
// REST API to access from client side js--> 
    app.get('/api/todos', function (req, res) { // get method route
       todo.find(function (err, todos) { // used mongoose model to get data
            if (err) {
                res.send(err);
            }

            res.json(todos);
        });
    });
app.post('/api/todos', function (req, res) { //post method route
 var td = new todo({
 val: req.body.val
        });

        td.save(function (err, td) { // use mongoose model to dave data
            if (err) {
                return res.status(500).json({
                    message: 'Error when creating todo',
                    error: err
                });
            }
            return res.status(201).json(todo);
        });
});
    app.get('*', function (req, res) { // get method for html
        //throw new Error('err');
        res.sendFile(__dirname + '/public/index.html');
    });
}

var todo = mongoose.model('Todo', { //mongoose model
    val: {
        type: String,
        default: ''
    }
});

Now create a folder public and inside it create a file index.html  and add following -

<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script>
    $(document).ready(function () {
        $("#btn").click(function () {
            $.post("/api/todos",
                {
                    val: $("#txttask").val()
                },
                function (data, status) {
                    console.log("Data: " + data + "\nStatus: " + status);
                });

            $("#txttask").val('');
            getData();
        });
        function getData() {
            $.get("/api/todos", function (data, status) {
                var listVal = "";
                $.each(data, function (index, val) {
                    listVal += val.val + "<br>";
                })
                $("#listtask").html(listVal);
            });
        }
        getData();
    });
</script>
</head>

<body>
    <div>
        <b>Express Running</b></div>
    <div>
        <label> Task:</label><input type="text" id="txttask" /><button id="btn">Save</button>
    </div>
    <div>
        <b>Task List</b>
    </div>
    <div id="listtask"></div>
</body>

</html>

Save both the files.

Note: Please read all the inline comments carefully for better understanding.

Greate . Now we are ready to run our first Express application with MongoDB.

Run you mongoDB, before going further.(go to your mongo installation folder and then ./bin folder using a new terminal window)

mongod --directoryperdb --dbpath <folder path>


To Run the application, execute following in your terminal-

> node server.js

Now Try to open - http://localhost:6064/

If you have done it properly, you should see your HTML page with heading Express Running. Using the api created in server.js you can save and see the saved list of items in the page.

That's it.

Feel free to ask if you have any queries. 



Nodejs Create Server


We know what nodejs is, and up to now, we are able to run basic node server. If you have not gone through the previous tutorial please check it here.

Cool, let’s go ahead. Now we will create a more sophisticated application. So what we have up to now-

  var http = require('http');
    
    function onRequest(request, response){
        console.log('request '+ request.url);
        response.writeHead(200,{"Context-Type": "text/plain"});
        response.write('Server running');
        response.end()
       
    }
    http.createServer(onRequest).listen(9000);
    console.log('Server Running');

Add and modify few line of code in it-
  var http = require('http');
 function send404(response){
          response.writeHead(404,{"Context-Type": "text/plain"});
          response.write('Error 404');
          response.end();
    }
    function onRequest(request, response){
        console.log('request '+ request.url);
      if(request.method == 'GET' && request.url == '/'){
        response.writeHead(200,{"Context-Type": "text/plain"});
        response.write('Server running');
        response.end();
       }
       else{
         send404(response);
       }
    }
    http.createServer(onRequest).listen(9000);

    console.log('Server Running');

Save the file as server.js and run it (>node server.js). If you can see “Server Running” message, then we are good to go. Open http://localhost:9000 in your browser. You should see “Server Running” in the browser also.
Now change the URL to http://localhost:9000/somethingelse. You will get a message “Error 404”.

Now let me explain what exactly happened. When we request http://localhos:9000, it comes to the server , and as we setup onRequest as a handler function, it starts executing. Now depending on the condition check on request type & properties, it creates a response and sends it back to the browser. For error handling, we used send404 function. Now same way we can create multiple request and error handler.

Example –

    function onRequest(request, response){
      if(request.method == 'GET' && request.url == '/'){
        response.writeHead(200,{"Context-Type": "text/plain"});
        response.write('Server running');
        response.end();
       }
      else if(request.method == 'GET' && request.url == '/somethingelse'){
        response.writeHead(200,{"Context-Type": "text/plain"});
        response.write('Something else from server');
        response.end();
       }
       else{
         send404(response);
       }
    }

Replace your existing onRequest with just above onRequest and again hit http://localhost:9000/somethingelse .  You should see “Something else from server”.

Return physical files
Now instead of sending string response, let’s send files. To do that we need to add below line at the top of the server.js file–

    var fs = require('fs');

Now just update your onRequest function.

function onRequest(request, response){
        if(request.method == 'GET' && request.url == '/'){
            response.writeHead(200,{"Context-Type": "text/html"});
            fs.createReadStream('./index.html').pipe(response);       
        }
        else if(request.method == 'GET' && request.url == '/script.js'){
            response.writeHead(200,{"Context-Type": "text/plain"});
            fs.createReadStream('./script.js').pipe(response);       
        }
        else{
            send404(response);
        }
    }

[Note : Make sure you have index.html and script.js file in the folder]

Lets see what exactly we did. First we imported fs module (node module) for accessing files. Now in onRequest function we used that fs module to read an existing file and send it back as response.

Example -
index.html- 
<html>
<head><script src="./script.js"/></head>
<body>test</body>
</html>
script.js -
(function(){
console.log('test')
})();

In browser and in console you should see "test".


That’s it for now.