Tutorial 4 Creating the project [mypostorm]

In this post, we are going to explore a simple application. We will create a simple application named mypostorm just to post data and nothing else.The folder structure of the project is as shown below,

fs

Step 1: Create Express configuration file.

Lets create a JavaScript file config.express.js under the directory config. And now lets put some code in it. There will be solely one function named configureExpress(). This function configures our Express Web framework.

var express = require('express');
var bodyParser = require('body-parser')

exports.configureExpress = function() {
	var app = express();
	app.set('views', rootAppDir() + '/app/views');
	app.set('view engine', 'ejs');
	app.use(express.static(rootAppDir() + '/public'));
	app.use(bodyParser.json());
	app.use(bodyParser.urlencoded({
		extended : true
	}));
	console.log('Express Config Path: ' + rootAppDir());
	return app;
};

var rootAppDir = function() {
	var path = require('path');
	var appDir = path.dirname(require.main.filename);
	return appDir;
};

Now let me explain the use of the function rootAppDir(). In fact, this function does nothing but locating the root directory of the project. We need to access the root directory of the project because based on it we can navigate to the other files and folders of the project. May be it is a more or less whacky way but if you can suggest something better, I thank you in advance.And in this JavaScript module , we are exporting the method configureExpress()  which configures our Express web framework which is the backbone to run our web server.

Step 2: Create MySQL config file

Now second step is to configure the config.mysql.js under the config directory. I used MySQL as my preferred database. You can use any database of your choice that Node supports. Node supports a hell lot of databases and you can find the drivers for almost all.This is a very simple configuration file as shown below,

exports.createMySQLConn = function(sequelize)
{
	var connection = new sequelize('attendance', 'root', 'root', {
	host : 'localhost',
	dialect : 'mysql'
	});
	
	return connection;
};

The javascript file exports only single function called createMySQLConn(). This function accepts a single parameter “sequelize”, and I am going to dig it in detail in the next steps.

Step 3: NodeJS ORM framework for MySQL

There are ORM frameworks available specific to the databases. For example, for MongoDB we have Mongoose ORM framework.For MySQL we have Sequelize or may be more. But I preferred to use this because the documentation is awesome. You need to have a look in it for sure. The documentation is simple and it covers all parts and parcels. So, I am not going to explore and post the usage of Sequelize here.

In my demo app , we will have only two simple tables namely,

  1. TB_USER It will store the users information.
  2. TB_POSTS It will store whatever data we post

db

Now, let us create the Models under the app -> models directory.

user.js

exports.TbUserVO = function(connection, Sequelize)
{
	var TbUserVO = connection.define('TbUserVO', {
	userID : {
	type : Sequelize.INTEGER,
	primaryKey : true
	},
	firstName : {
	type : Sequelize.STRING,
	get : function()
	{
		return this.getDataValue('firstName');
	}
	},
	lastName : {
		type : Sequelize.STRING
	},
	login : {
		type : Sequelize.STRING
	},
	password : {
		type : Sequelize.STRING
	},
	email : {
		type : Sequelize.STRING
	}
	}, {
	freezeTableName : true,
	timestamps : false,
	tableName : "tb_user"
	});

	return TbUserVO;
};

Well, the javascript file has a single function names TbUserVO and it accets two arguments (connection, Sequelize). I will explain the types of these two arguments later on. The rest of this code is simple, just follow the documentations of Sequelize.

post.js

exports.TbPostVO = function(connection, Sequelize)
{
	var TbPostVO = connection.define('TbPostVO', {
	postID : {
	type : Sequelize.INTEGER,
	primaryKey : true
	},
	scrap : {
		type : Sequelize.STRING
	},
	date : {
		type : Sequelize.DATE
	}

	}, {
	freezeTableName : true,
	timestamps : false,
	tableName : "tb_posts"
	});

	return TbPostVO;
};

Note that we did not put the mappings in the scripts. Relationship between the models should be like this,

  • One user can post many scraps. So, one to many from TbUserVO to TbPostVO.
  • One scrap is posted by a user.So, one to one from TbPostVO to TbUserVO

Many times I saw that people put all the model definitions in a single file to facilitate the relationship mapping. But I do not think that this is a good idea to put all models in a single file. That’s why separated each model in each javascript file. To put the relationships among them, I created a separate mapping.js file. Here is the code for it,

// RootDir.
var rootAppDir = function()
{
	var path = require('path');
	var appDir = path.dirname(require.main.filename);
	return appDir;
};

exports.makeMapping = function(connection, DataType)
{
	var user = require(rootAppDir() + '/app/models/user');
	var post = require(rootAppDir() + '/app/models/post');

	var TbUserVO = user.TbUserVO(connection, DataType);
	var TbPostVO = post.TbPostVO(connection, DataType);

	// One to Many. One user can post many scraps.
	TbUserVO.hasMany(TbPostVO, {
	as : 'listPost',
	foreignKey : 'userid'
	});

	// One to one. One post belongs to a single user.
	TbPostVO.belongsTo(TbUserVO, {
		foreignKey : 'userid'
	});

	
};

The script file has only one method makeMapping which accepts two parameters (I will explain them soon). What it does is, load the two modues (user.js & post.js) and makes the mapping simply. Please do follow the documentation of Sequelize.

Step 4: The Server

Finally the Express server. For now I did not put any code related to Express server. Just some simple code and the mystery of the two parameters (connection,Sequelize or DataType) that appeared in the above script files. Here goes the code,

// Get the root dir i.e path of the F:/projects/mypostorm
var rootAppDir = function()
{
	var path = require('path');
	var appDir = path.dirname(require.main.filename);
	return appDir;
};


// Import the Sequelize module.
var sequelize = require('sequelize');

// Import the MySQL configuration config.mysql.js
var sql_config=require(rootAppDir() + '/config/config.mysql');

// Import the mapping.js
var mapping = require(rootAppDir() + '/app/models/mapping');

// Make connection by calling the createMySQLConn() of the config.mysql.js
var connection=sql_config.createMySQLConn(sequelize);

// Now make create the relationships by calling the makeMapping() of mapping.js
mapping.makeMapping(connection,sequelize);

// Just execute it and I hope you wont get error if everything is well done.

/*
P.S: Please do not worry. I will add the server codes later.
*/

Okay, till now we have configured the project structure,database tables, models and mapping. In the next posts we will be creating the servers and add the pages. We will use AngularJS as front end to excel our SPA (Single Page Application).

Thanks !!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s