Monday, January 18, 2016

REST simplified by Nodejs

Wonderful !! Yes, its amazing to run javascript on server side and develop any application quickly with best performance.  So how we can run javascript on server ? Need to install any browser on server which parse request and response result to browser (client) :) ?? Nope... its very simple.. just need framework called nodejs.

Nodejs is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node is an interface to the V8 JavaScript runtime – the super-fast JavaScript interpreter that runs in the Chrome browser.


Ref : https://nodejs.org/en/


I would recommend to use Nodejs for following reasons :-

(1) Language : Its uses javascript and most of developer know about it.
(2) Speed : The operation is much much faster as compare to other scripting language
(3) Object Database : Leverage of using JSON which can be processed on client and server both. Thus can use mongodb which save data directly in JSON format.
(4) Data Streaming : Node can read/write streams to websockets just as well as it can read/write streams to HTTP. For example, we can pipe stdout from a running process on the server to a browser over a websocket, and have the webpage display the output in real-time.

You can do everything with Nodejs what you can do with other scripting language plus speed is bonus.


The following some important modules/library used to build a robust application using Nodejs



(1) NPM : NPM is a Package manager which Installs, publishes and manages node programs

(2) NVM: NVM (Node Versioning Manager) allow the managing of versions for the nodejs

(3) Jade: With node js we can use Jade as a template engine to manage the html.

(4) Bootstrap : Style your page with your choice.

(5) Mocha : Write your own Unit Tests and test your application while adding new features in your application. Very important for those who believes in Test Driven application.

Now let dive inside nodejs and take a look for it application. Let move ahead and build restful API's for a store in which we do some CRUD operations on items. Also we will authorize some users to access some items using different authentication methods.

Node Installation :  I am using MAC so installing node using package manager called  home brew.

Ref : http://brew.sh/ 
       brew install node

Now you can check node on your terminal by typing
       node --version  ( it will display the version of your node  eg. v0.12.2

Type "node" which will take you on node prompt.

        console.log("This is my nodejs")

It should display  "This is my nodejs" as output. Seems everything is set now and we are ready to build application using nodejs.



Create the skeleton for the application  as below :-


               Folders :  

                    Store/
                              models/
                              controllers/
                              node_modules/
                              package.json
                              server.js



Basically we are going to follow MVC structure using express module. We are going to define all required nodejs modules in package.json . In Nodejs we need to build our own server so will specify all primary setting and required module in server.js.


Module repository : https://www.npmjs.com/


Step-1 npm install ( Will install all modules defined in package.json)

Step-2 command (1) mongo (2) use store (To create new db named store)

mongod --dbpath=/Users/rakeshp/Documents/nodeprojects/db --port 27017
mongo will start and will point to 271017

Step-3 node server

Check url in browser : localhost:3000/api

You will see message like "Cannot GET /api".


Hurray.... :) Server is running and we are ready for development.

Basic setup. Include all required packages in package.json


eg.

package.json  :- 

{
  "name": "Store",
  "main": "server.js",
  "dependencies": {
    "express": "^4.1.1",
    "mongoose": "^4.3.6",
    "body-parser": "^1.14.2",
    "bcrypt-nodejs": "0.0.3",
    "passport": "^0.3.2",
    "passport-http": "^0.3.0",
    "passport-http-bearer": "^1.0.1",
    "oauth2orize": "^1.2.0",
    "express-session": "^1.13.0",
    "jade": "^1.11.0",
    "passport-local": "^1.0.0"
  }
}

Create your server :- 

eg.

server.js
// Load required modules 
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var jade = require('jade');
var session = require('express-session');
var passport = require('passport');

// Connect store with MongoDB
mongoose.connect('mongodb://localhost:27017/store');

// Create our Express application
var app = express();

// Create our Express router
var router = express.Router();

// Register all our routes
app.use(router);

// Start the server
app.listen(3000);

You can find sample application for rest api  using "Basic" strategy of passport at

https://github.com/parsoya/store



How to test rest api ???  Its very easy. You can use tools such as Soap UI or Postman. I would recommend to use postman plugin available for chrome. Its easy and free :)



Let add some sample users and then will add some items in our store.


(1) Add Users :-  




(2) List Users :- 
(3) Add Items :- 









































Tuesday, January 12, 2016

MVC or MOVE : Choice is your's !!

Few month back I build an restful application using ZF 2.4 and come across with its solid functionality called "EventManager". Yesss Event Manager which draw a broader line between Zf1 and new ZF2 Initially I was confused about its importance in my development but moving ahead I understood its real crux. So really ZF2 is MVC or MOVE ?
MVC = Model , View Controller
MOVE = Model Operation View Event
In Zf2 , controller are divided into two parts in MOVE i.e Operation and Event. You might have heard about "Fat Model , Skinny Controller" for doing good programming using MVC framework. Zf2 is answer for it .
How MOVE is different than MVC ?
Let us consider one small scenario in which user is logging using username and password. What would be case in ZF1 and Zf2. ? In ZF1 the action will be passed to model through controller and Model will talk to database to check the authenticity of user then again revert back result to controller which pass to user (views). No central watch for this action but using MOVE you can create your own events let say "loginevent" and control it centrally. So whenever "loginevent" is fired event take care to talk to model and pass result to view. It provide more controls to use this events from anywhere in your application which is not possible using MVC.
I found some similarity between ZF2 + Doctrine and Spring + Hibernate. Though I cannot say ZF2 is following purely based on MOVE but can bet its best framework developed in PHP. Most of concepts of ZF2 are derived from Spring, Ruby on Rails. Zend Framework use the power of scripting language and are getting more famous among developers. Spring is pure MVC framework which use power of POJO, Dependency Injection and many more which are also found in ZF2. Either its annotation or XML configurations in hibernate using spring or annotation or XML configurations in doctrine using zf , everything is possible. Think bigger now !! move to MOVE !!
Choice is your's :)