Sunday, January 31, 2016

NodeJS Quick Guide - Part 2

In this part we will use the express web application to develop a sample web application.

How to customize the application:
1) Change the port
We can change the default port to a new port or better use the runtime arguments to set it.
For example:
if (process.argv[2]!=null){
    var port = normalizePort(process.argv[2]);
} else {
    var port = normalizePort(process.env.PORT || '8000');
}
app.set('port', port);

This will let us use the application by providing the port as an argument as following:
set DEBUG=mytestapp:* & npm start 8002

2) Add images in the images folder:
Download any HR logo image and place it in the images folder.

3) Add or Edit Routes
We can edit the current pages or create a new routes.
Let's create header and footer pages and place all these files in the views folder
1) header.jade 
<html><head><title>#{title}</title></head><body><center><h1>#{title}</h1><img src="/images/hr-logo.jpg" width=200 height=100><hr><br>

2) footer.jade
<hr><div> (c) Copyright 2016 </div></center></body></html>

Now modify index.jade to be as following:
include ./header.jade
block content
  h1= title
  p Welcome to #{title}
p Enter an Employee number to see his/her data
</p><form name='users' action='/users' method='get'><input type='text' name='emp_num' /><input type='submit' value='Submit' /></form>
include ./footer.jade


As you can see in these files, we have mixed the html tags with jade syntax e.g. <p> or p
We use the format #{ ... } for variables.
We have included the header and footer files using include statement.
The form in index.jade submit the user inputs to the /users

The index.js should be modified a little bit to include the correct page title:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'HR Express' });
});
module.exports = router;


Let's now edit the user.js file to capture this input field and route it into details page.

var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.render('emp', { title: 'HR Express', number: req.query.emp_num, name: 'Osama Oransa', position: 'PaaS Expert' });
});
module.exports = router;


You can see the query parameter is captured using req.query.parameter_name we have also set some variables, these variables should typically comes from the database tables.

Add emp.jade view with the following content:
include ./header.jade
block content
  h1= title
  p Welcome to #{title} - Employee Details
p Here is the Employee Data
P Number : #{number}
P Name : #{name}
P Position: #{position}
<br>
p
<a href='/'>Back</a>
include ./footer.jade


4) Test the application
We can now test the application by executing our command:
set DEBUG=mytestapp:* & npm start 8002

In the home page enter any employee number and click submit to view the details page.










5) Using Session object
To use the session object we need to install the following modules: connect and cookie-session.
npm install connect
npm install cookie-session


In app.js add the following to instantiate the session using cookies:
var connect = require('connect');
// store session state in browser cookie
var cookieSession = require('cookie-session');
app.use(cookieSession({
    keys: ['secret1', 'secret2']
}));

You can change the session keys to any unique keys.
Now in index.js modify the code to store a random guest name in the session.
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
  if(req.session.guest==null) req.session.guest='Osama '+random(1,10);
  res.render('index', { title: 'HR Express','guest':req.session.guest });
});
module.exports = router;
function random (low, high) {
    return Math.floor(Math.random() * (high - low + 1) + low);
}

In users.js add the parameter as well to the variables:
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.render('emp', { title: 'HR Express','guest':req.session.guest, number: req.query.emp_num, name: 'Osama Oransa', position: 'PaaS Expert' });
});


Finally in the header.jade add a p for the guest name just above the image:

<h1>#{title}</h1>
p Welcome #{guest}
<br>

6) Test the application
Now test the application using 2 different browsers to see the effect of the session.

You can see the guest name is now below the title, test using different browsers.

7) Connect to the DB
Now to connect the database we have many options, we can connect on SQL or NO-SQL database for example to use Oracle Database you need to modify the code to query the database.
Oracle provides a DB driver for NodeJS can be found in the following URL:
https://www.npmjs.com/package/oracledb
To Install it, you'll need the following steps:
Prerequisites:
    - Python 2.7
    - C Compiler with support for C++ 11 (Xcode, gcc, Visual Studio or similar)
    - The small, free Oracle Instant Client libraries if your database is remote. Or use a locally installed database such as the free Oracle XE release
    - Set OCI_LIB_DIR and OCI_INC_DIR during installation if the Oracle libraries and headers are in a non-default location
Installation:
Run:
 npm install oracledb
This will install it from the NPM registry.

Let's now modify the code to get the employee details from the DB (Oracle HR sample schema) as following:

var oracledb = require('oracledb');
oracledb.getConnection(
  {
    user          : "hr",
    password      : "hr",
    connectString : "localhost/XE"
  },
  function(err, connection)
  {
    if (err) { console.error(err.message); return; }
    connection.execute(
      "Sselect first_name||' '||last_name name, job_title "+
      " FROM employees,jobs"+
      " WHERE employees.job_id=jobs.job_id"+
      " and employee_id = :id ",
      [110],  // bind value for :id 

{outFormat: oracledb.OBJECT}, // outFormat can be OBJECT or ARRAY. The default is ARRAY
       function(err, result)
      {
        if (err) { console.error(err.message); return; }
        console.log(result.rows);
      });
  });

 We need to replace the [110] with our employee parameter: req.query.emp_num,
 And pass the result into our emp.jade page to render the employee details.
result[0].name & result[0].job_title
We need also to route the errors into error pages.
You can see here a lot of examples of how to use Oracle driver:
https://github.com/oracle/node-oracledb/tree/master/examples

This is a simple application to show us how to use some of the NodeJS features in nutshell.

No comments:

Post a Comment