We have chosen nedb for our datastore to make the application simple for reader. NeDB is a javascript based Embedded database.
According tothis, NeDB is an "Embedded persistent database for Node.js, written in Javascript, with no dependency (except npm modules of course)."
To make the application, we have selected:
• Angular.js for client side development - Single Page Application.
• Cross Domain Communication in between Angular.js and Node.js.
• Node.js for server side development.
• Rest based web service creation with express.js.
• Database - NeDb.
• Node.js NeDB Module Extention.
We have created a Proof of Concept with a Javascript based web server, where we utilized NeDB with the javascript based framework Node.js and angular.js on the client side.
The architecture at a glance:
Figure 5.1: screenshot Here are the steps:
5.7.1 Installation
• Download and install Node.js as describedhere.
• To Develop the application we need to install nedb module for Node.js.
npm install nedb
• We need to install express.js for node.js.
npm install express
5.7.2 Configuration Code
Now, we will try to describe the used code portion:
var application_root = __dirname, express = require("express"), path = require("path");
Here we have initialised the express.js based on the Node.js concepts discussed above.
var app = express();
Here we have initialised the express web server and reference the app variable.
var databaseUrl = "/home/sampleuser/nedb/user.db";
var Datastore = require(’nedb’);
db = {};
db.users = new Datastore({ filename: databaseUrl, autoload: true }); // to autoload ←- datastore
Here we have made the connection to the nedb database using the Node.js nedb module extension library.
// Config
app.configure(function () { app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(application_root, "public")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
Here we have made the configuration related to express.js.
5.7.3 Router Handling Code
app.get(’/api’, function (req, res) { res.send(’Our Sample API is up...’);
});
Here we have made our first REST based web service and tested whether the express.js is up.
Our sample api will be:http://127.0.0.1:1212/api(GET Method).
app.get(’/getangularusers’, function (req, res) {
res.header("Access-Control-Allow-Origin", "http://localhost");
res.header("Access-Control-Allow-Methods", "GET, POST");
// The above 2 lines are required for Cross Domain Communication(Allowing the ←- methods that will come as Cross Domain Request
// More on this in later part of the code
db.users.find(’’, function(err, users) { // Query in NeDB via NeDB Module if( err || !users) console.log("No users found");
else {
res.writeHead(200, {’Content-Type’: ’application/json’}); // Sending data ←- via json
str=’[’;
users.forEach( function(user) {
str = str + ’{ "name" : "’ + user.username + ’"},’ +’n’;
});
str = str.trim();
str = str.substring(0,str.length-1);
str = str + ’]’;
res.end( str);
// Prepared the jSon Array here }
});
});
Here we have created another REST API to get all usernames from a user collection and so we have performed the necessary NeDB query.
Our sample api will be:http://127.0.0.1:1212/getangularusers(GET Method).
app.post(’/insertangularneuser’, function (req, res){
console.log("POST: ");
res.header("Access-Control-Allow-Origin", "http://localhost");
res.header("Access-Control-Allow-Methods", "GET, POST");
// The above 2 lines are required for Cross Domain Communication(Allowing the methods ←- that come as Cross
// Domain Request console.log(req.body);
console.log(req.body.mydata);
var jsonData = JSON.parse(req.body.mydata);
db.users.save({email: jsonData.email, password: jsonData.password, username: jsonData. ←- username},
function(err, saved) { // Query in NeDB via NeDB Module if( err || !saved ) res.end( "User not saved");
else res.end( "User saved");
});
});
Here we have made a POST request to create a user via a REST invocation.
Our sample api will be:http://127.0.0.1:1212/insertangularneuser(Post Method).
// Launch server app.listen(1212);
We have made the server to listen at 1212 port.
Now we can run node appnedbangular.js from command prompt/terminal.
5.7.4 Angular.js part
We have used Angular.js for our client side work and development. We have made the choice of Angular.js as our front-end development tool as this maintains a clear client-side Model-View-Presenter Architecture and makes the code more structured.
Since this part of the tutorial mainly concentrates on node.js and express.js, the reader is urged to acquire more knowledge about Angular.jshere.
We provide inline doucmentation with our code to help you better understand the application with Angular.js So, below is the code for theAngular Controller.
’use strict’;
var myApp = angular.module(’myApp’, []); // Taking Angular Application in Javascript ←- Variable
// Below is the code to allow cross domain request from web server through angular.js myApp.config([’$httpProvider’, function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common[’X-Requested-With’];
} ]);
/* Controllers */
function UserListCtrl($scope, $http, $templateCache) { var method = ’POST’;
var inserturl = ’http://localhost:1212/insertangularneuser’;// URL where the Node.js ←- server is running
$scope.codeStatus = "";
$scope.save = function() {
// Preparing the Json Data from the Angular Model to send in the Server.
var formData = {
’username’ : this.username,
’password’ : this.password,
’email’ : this.email };
this.username = ’’;
this.password = ’’;
this.email = ’’;
var jdata = ’mydata=’+JSON.stringify(formData); // The data is to be string.
$http({ // Accessing the Angular $http Service to send data via REST Communication ←- to Node Server.
method: method, url: inserturl, data: jdata ,
headers: {’Content-Type’: ’application/x-www-form-urlencoded’}, cache: $templateCache
}).
success(function(response) {
console.log("success"); // Getting Success Response in Callback
$scope.codeStatus = response.data;
console.log($scope.codeStatus);
}).
error(function(response) {
console.log("error"); // Getting Error Response in Callback
$scope.codeStatus = response || "Request failed";
console.log($scope.codeStatus);
});
$scope.list();// Calling the list function in Angular Controller to show all ←- current data in HTML
return false;
};
$scope.list = function() {
var url = ’http://localhost:1212/getangularusers’;// URL where the Node.js server ←- is running
$http.get(url).success(function(data) {
$scope.users = data;
});
// Accessing the Angular $http Service to get data via REST Communication from ←- Node Server
};
$scope.list();
}
5.7.5 Angular Template and HTML
<html lang="en" ng-app="myApp">
...
We refer to the Angular Application in above code.
<body ng-controller="UserListCtrl">
...
We refer to the Angular Controller in above code.
Search:
<input ng-model="user">
<!--Body content-->
<ul class="users">
<li ng-repeat="user in users | filter:user ">
{{user.name}}
We have used the ng-repeat tag to take the users data model from the REST invocation.
<form name="myform" id="myform1" ng-submit="save()">
<fieldset>
<legend>New User</legend>
<center><input type="text" placeholder="User..." ng-model="username" size ←-
=50 required/></center>
<center><input type="text" placeholder="Password..." ng-model="password" ←- size=50 required/></center>
<center><input type="text" placeholder="Email..." ng-model="email" size=50 ←- required/></center>
</fieldset>
<p>
<center><button type="submit" >Save now...</button></center>
</form>
We have used the ng-submit tag to send the user data model from the REST invocation and send to the node server in order to persist it in the NeDB database.
Please note that NeDB is just a light-weight Database which can be embedded in Node WebKit Applications. For fairly large scale database production systems, we should consider MongoDB.