Subscribe via RSS Feed

Develop Web Application with Node.js, Express.js REST Service and Neo4j (neo4j-js module) – Updated

May 27, 2013 2 Comments


This article is a proof of concept towards make a web application with Javascript based Web Server with Node.js and Neo4j.

To make this possible, we have selected -

1> Node.js for server side development

2> Rest based web service creation with express.js

3> Graph Database – Neo4j

4> Node.js Neo4j Module Extention (neo4j-js)

We have created a Proof of Concept with Javascript based web server, where we have focused on dealing with Neo4j(Graph Database) with javascript based framework Node.js.

We have taken help of the Neo4j-js module, which are discussed in Neo4j Site and the Github project contribution from Bret Copeland.

Our initial code can be downloaded here.

We have taken reference Data Model of Neo4j Graph Database for this application from our previous knowledge on Neo4j.

For reference of the Neo4j Graph Database Model , take a look at our previous 2 articles -

1> Case Study in Graph Database in Context of Neo4j Cypher Query

2> Neo4j Cypher Queries for Sample Graph Database

Architecture at a glance -

NodeJS Neo4j Architechture

So here are the steps -

Installation -

A> Download and install Node.js from here.

B> To Develop the application we need to install Neo4j-js module for Node.js

Command – npm install neo4j-js (should be connected to internet)

C> We need to install express.js for node.js

Command – npm install express  (should be connected to internet)

D> We need to install http status

Command – npm install http-status (should be connected to internet)

Configuration Code -

Now, we will try to describe the code portion -

 
var application_root = __dirname,
    express = require("express"),
    path = require("path"),
    HTTPStatus = require('http-status'); // To return http status for error codes

var config = require('./config');

Here we have initialised the express.js within javascript variables in respect of Node.js concept.

We have introduced another js file – config.js to put all the neo4j configuration related information.

 
var app = express();

Here we have initialised the express web server in app variable.

 
var neo4j = require('neo4j-js');

Here we have made the Node.js Neo4j-js module available .

 
var neo4jurl = process.env.NEO4J_URL ;
neo4jurl = neo4jurl +'/db/data/';

Here the Neo4j Database server url is set from configuration file.

 
var query = [ 'START me=node:node_auto_index(name={inputusername}) MATCH me<--friend<--friend_of_friend where 
(friend_of_friend.entitytype={inputentitytype}) RETURN friend_of_friend;'	];
var insertquery = [ 'CREATE (user {entitytype:{inputentitytype}, name : {inputname}}) return user;' ];
var queryforallrelation = [ 'start n = node:node_auto_index(name={inputusername}) match(n)--(x)  return x;'];

Here all the query variables are set with Neo4j Cypher Queries.

 
// Express 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

Rest Services 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('/friendoffriend/:username', function (req, res){
	res.set({'Content-Type': 'text/json'}); // setting content type
	username = req.params.username;
	type = 'user';
	neo4j.connect(neo4jurl, function (err, graph) { //Connecting neo4J

			graph.query(query.join('\n'), {inputusername : username, inputentitytype :type} ,
                             function (err, results) {	// Query to Neo4j Database through Neo4j-js Module
				if (err) {
					res.send(HTTPStatus.INTERNAL_SERVER_ERROR,'Internal Server Error'); 
                                        // Return Http Status for Error
				}
				else {
					res.send(HTTPStatus.OK,JSON.stringify(results)); 
                                        // Return the json in response
				}
			     });	
	             });
               });

Here we have created REST api to get user information from Neo4j Nodes Collection and so have done through Neo4j-js Extention Library. We have made a query for ‘Friend of Friend’ in Cypher Query Language.

More information about Neo4j Cypher query can be found in Neo4j Cypher Queries for Sample Graph Database.

Our sample api will be  - http://127.0.0.1:1212/friendoffriend/andrew (Get Method)

 
app.get('/insertuser/:username', function (req, res){
	res.set({'Content-Type': 'text/json'});
	username = req.params.username;
	type = 'user';
	neo4j.connect(neo4jurl, function (err, graph) { // Connection to neo4J

			graph.query(insertquery.join('\n'), {inputname : username, inputentitytype :type} 
                             ,function (err, results) {	// Query to Neo4j through neo4j-js module
				if (err) {
					res.send(HTTPStatus.INTERNAL_SERVER_ERROR,'Internal Server Error');
                                        // Return Http Status for Error
				}
				else {
					res.send(HTTPStatus.OK,JSON.stringify(results));
                                        // Return the json in response 
				}
			    });	
	               });
               });

Here we have inserted a node in database through cypher query via REST web service calling.

Our sample api will be  - http://127.0.0.1:1212/insertuser/anotheruser (Get Method)


//Cypher Query with Javascript Callback Example

function neo4jQuery(neo4jurl, query, parameters, giveresults) { 
        //Function with query, parameter and callback as arguments
	neo4j.connect(neo4jurl, function (err, graph) {  // Connection to neo4J
		graph.query(query.join('\n'), {inputusername : 'andrew'} ,
                        function (err, results) { // Query to Neo4j through neo4j-js module

			if (err) {
				giveresults(HTTPStatus.INTERNAL_SERVER_ERROR);  // Return Http Status in callback
			}
			else {
				giveresults(JSON.stringify(results));  // Return the json in callback
			}
		});	
	});
}

//Below is a separation of REST related code and neo4j related code via a javascript callback function
app.get('/allrelations/:username', function (req, res){
	res.set({'Content-Type': 'text/json'});
	username = req.params.username;
	parameters = {inputusername : username};
	neo4jQuery(neo4jurl, queryforallrelation, parameters, function(results){ // the previous function is called
		res.send(results);
	});
});

Our sample api will be  - http://127.0.0.1:1212/allrelations/andrew (Get Method)

Above we have taken another  Query Example from Node.js with Query, Parameter and Callback function.

 
// Launch server
app.listen(1212);

We have made the server to listen at 1212 port.

To run the application, we should use - node neo4jtest.js from command shell.

Update : We have updated  the code-base as per advice from Michael Hunger about improvement of the Post.

Evaluate the coding. Comments are welcome.

Enter your email address:

Delivered by FeedBurner

Sign Up to read the rest of the content

Email will be used only for updates of our site

No Thanks

  • Michael Hunger

    Please update your code:

    - take the neo4j url from process.ENV.NEO4J_URL
    - pull out a query method that takes a query, parameters and callback
    - return the correct http status codes on errors

    Please also update your github repositoy. The we can add your example as “getting started” to neo4j.org/develop/javascript

    • piyasde

      Hi,

      -I have introduced config.js and taken the process.ENV.NEO4J_URL from there.

      -made a seperate Cypher Query Example with query, parameter and callback

      -introduced node.js http-status module extention to handle the http status for error codes.

      Also I have updated the Github Repository.

      Please review all of the above changes and suggest us for any further changes.