New REST API, Real Time, MVC framework
npm install xenopsXenops Framework
=============================
This framework is simple and including full featured components of REST API, MVC framework, database management, web socket management and view with static, dynamic web pages. It includes socket management system, data driven REST API, static and dynamic views, friendly URL routing, validation, logging, REST API functionality testing module etc. This framework architecture is service handler oriented one and user can easily develop simple to complex level API functionality. Data management module handles data models with validation and sanitization, models retrieves the data from database using correct node modules. It is especially good for building REST API, multi room chat, virtual class room, real time scalable dashboards, multiplayer games and website with static, dynamic view based web pages. It is an extensible framework, user can easily extend the framework and rewrite functionality and change it according to their own needs.
Framework structure is shown in fig.
!screen!screen1
// Event emitter Handler Obj
var socketEventEmit = require('../events/socketEventEmitter');
`
!socketemitters
Views management
We have already mentioned that this framework is REST API based one and there is no view present in it. But in future we are looking for common framework for web based
and REST API. For this one, we have started static and dynamic html page rendering using current framework.
`
// Custom controller routes
this.server.get('/staticview', this.controllers.custom.staticView);
this.server.get('/dynamicview', this.controllers.custom.dynamicView);
`
Static and dynamic page render handlers.
!views
Template management
EJS is a very popular opensource javascript template library and used in this framework.
$3
Add one index.ejs file in views folder.
Fingent Technology Solutions
<% if (data.length) { %>
<% data.forEach(function(name) { %>
- <%= name %>
<% }) %>
<% } %>
Add new url route to routes.js
this.server.get('/template', this.controllers.custom.templateView);
template code for controller
CustomController.prototype.templateView = function(req, res, next) {
// Read it asynchronus mode
fs.readFile(constant.APP_PATH + '/views/index.ejs', 'UTF-8', function(err, templateStr){
if (err)
res.end(''+ err);
else {
var returnStr = ejs.render(templateStr, {
data: ['Fingent', 'Xenops', 'Framework']
});
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(returnStr);
}
});
return next();
};
Open the browser and type -> http://localhost:8888/template shows
!template
Object Relational Mapping(ORM)
This is node js object relational mapping module named orm node module. The key feature of ORM is the mapping it uses to bind an object to its data in the database.
ORM has the benefit of allowing you to more easily support more database engines.
Currently it supports following DBMS
- MySQL & MariaDB
- PostgreSQL
- Amazon Redshift
- SQLite
- MongoDB (beta)
It has so many features
- Create Models, sync, drop, bulk create, get, find, remove, count, aggregated functions
- Create Model associations, find, check, create and remove
- Define custom validations (several builtin validations, check instance properties before saving)
$3
Add new url to routes.js
this.server.get('/getcustomers', this.controllers.custom.getAllCustomers);
A Model is an abstraction over one or more database tables. Models support associations. The name of the model is assumed to match the table name.
Create model file customerModel.js and add code.
// Define customer model
module.exports = function(db){
var Customer = db.define('customer', {
name : String,
email: String
}, {
methods: {
getName: function(){
return this.name;
},
getEmail: function(){
return this.email;
}
}
});
return Customer;
};
customer is the table name and name, email are fields.
Drop this bits of code in /controllers/customController.js
CustomController.prototype.getAllCustomers = function(req, res, next){
res.writeHead(200, {'Content-Type': 'application/json'});
// ORM database connected
if (ormDb) {
var customerModel = require('../models/customerModel')(ormDb);
// To get all customers, {} for first customer {id: 1}
customerModel.find({}, function(err, customers){
if (err) {
console.log('DB Error ='+ err);
res.end(JSON.stringify(err));
return ;
}
// Print Collection of customer object
res.end(JSON.stringify(customers));
})
} else {
res.end('No database connection.');
}
return next();
};
Open the browser and type -> http://localhost:8888/getcustomers
[{"name":"John Luka","email":"luka@gmail.com","id":1},{"name":"Maria","email":"maria@gmail.com","id":2}]
results is the mysql table customer total records displayed as json.
Data handling in CRUD operations
Here we have already implemented a CRUD operation api functionalities using the current api framework.It includes user controller, model, routes etc.
Logging
In the current framework we are using winston log module.We can easily log the the info, error, warn and debug using this logger module.
!alt tag
this file is stored in utils/logger.js file.In the application we can use like,
`
// Log information
logger.info('Application server started. ');
`
Two log files are created inside log folder for debug and exception log.
Client testing
This module is very important one and it can be used for REST API functional testing. Here is one html and js file, html file is used for socket io connection testing and js file one is used for testing
!client
How to use this one ?
`
var client = require('./testClient/client');
// call client
client.clientConnect();
client.getUsers();
``