A kind of nodejs MVC framework

Source: Internet
Author: User
Tags emit

MVC distributes the request, and the distribution typically has a controller (for the module), the action (for the method in the module), args (the requested parameter).

1. Set the URL of the HTTP request first, resolving various parameters in the URL:

// Config.js var route = require ('./route ');//For AJAX requests
Method: ' Get ', /^\/category/mailcategory/i, ' mailcategory ', ' Getmailcategory '});
Controller is empty, for page, for page route.map ({ ' get ', /^\/$/i, ', ' list.html '});

Entrance to Server.js:

Exports.runserver =function(port) {Port= Port | | 10088; /*function (req,res) {} It will automatically be added to the listen queue for the ' request ' event. It is HTTP.     An instance of Incomingmessage. */    varServer = Http.createserver (function(req, res) {var_postdata = ' '; //on to add a listener function to a specific eventReq.on (' Data ',function(chunk) {_postdata+=Chunk; }). On (' End ',function() {req.post=Querystring.parse (_postdata);        Handlerrequest (req, res);            });   }). Listen (port); The program runs the entry Console.log (' Server running at http://180.150.189.25: ' + 10088 + '/');};

Executes Handlerrequest (req, res) after receiving the requested URL;

/** * Uniform entry for all requests*/varHandlerrequest =function(req, res) {//use route to get controller and action information    varActioninfo =Route.getactioninfo (Req.url, Req.method); //If there is a matching action in the route, it is distributed to the corresponding action    if(actioninfo.action) {varController =Actioninfo.controller; //Direct Jump Page        if(Controller = = "")) {Viewengine.forward (req, res, actioninfo.action); return; }        //Load Action    if(Controller[actioninfo.action]) {varCT =NewControllerContext (req, res); //if it is a POST request, reset the parameters from            if(req.method.toLowerCase () = = "POST") {Actioninfo.args=Req.post; }            //The path transformation is here by using apply to pass the controller's context object to the action. Controller[actioninfo.action].call (CT, Actioninfo.args); }Else{handler500 (req, res,' Error:controller ' + Actioninfo.controller + ' "Without action" ' + actioninfo.action + ' "')        }    }Else{        //If the route does not match, it is treated as a static filestaticfileserver (req, res); }};
The Viewengine.forward code is as follows:
varStaticfileserver =function(req, res, filePath) {if(!FilePath) {FilePath=Path.join (__dirname, Config.staticfiledir, Url.parse (req.url). Pathname); } fs.exists (FilePath,function(exists) {if(!exists) {              //a situation where the directory does not existhandler404 (req, res); return; }            varRaw =Fs.createreadstream (FilePath); varext =Path.extname (FilePath); Ext= ext? Ext.slice (1): ' HTML '; varacceptencoding = req.headers[' accept-encoding ']; varHead = {' Content-type ': Contenttypes[ext] | | ' Text/html '}; if(!acceptencoding) {acceptencoding= ' '; }        //returns the corresponding data according to the request header information       if(Acceptencoding.match (/\bgzip\b/) ) {head["content-encoding"] = "gzip"; Res.writehead (200, head);        Raw.pipe (Zlib.creategzip ()). pipe (RES); }Else if(Acceptencoding.match (/\bdeflate\b/) ) {head["content-encoding"] = "deflate"; Res.writehead (200, head);        Raw.pipe (Zlib.createdeflate ()). pipe (RES); } Else{Res.writehead (200, head);        Raw.pipe (RES); }       });};
The context of CT is as follows:
// the controller's context object var function (req, res) {    this. req = req;      this. res = res;     this. Dbpool = dbpool;     this. ContextPath = __dirname;     this. handler404 = handler404;     this. handler500 = handler500;};

2.controller

Through the above forwarding can be the URL and module in the method map, we write the method can follow the module to write, such as mailcategory in the Getmailcategory method is as follows:

In the mailcategory.js of the action module in the SRC module:

/*Mailcategory.js, available with two action getmaillist and Getmailcategory*/exports.getmaillist=function(args) {varContext = This; varresult = {errcode:0, msg: ' Success ', Categoryid:categoryid, data:[]}; //parameter Check    varCategoryId =Args.categoryid; if(!categoryId) {Emitter.emit ("Invalidcategoryid", result, context); return false; }  /** * To get mail column information * @param islist 1 is only returned column list 0 return column and module information * @returns {errcode:0, msg: ' Success ', Data:[{id: ', Name: ', Alia S: '},...]} * @returns {errcode:0, msg: ' Success ', data: [{ID: ', ', ' name: ', alias: ', Modules:[{id: ', ' Name: '}, ...]}}*/exports.getmailcategory=function(args) {}

3.module

Provide data for the controller layer, connect directly to the database, or add a cache in the middle, such as Redis. Just seen in the process of mapping, passing the members of an object

   This.dbpool = Dbpool;
It is defined as follows:
DbManager = require ('./src/utilities/dbmanager '); // Database Link Pool var dbpool = Dbmanager.getpool ();

Dbmanager.js encapsulates an object that connects to a database, or a connection pool

//Create a MySQL database linkvarMySQL = require (' MySQL ');//Connection PoolvarDbconfig ={host:' 180.150.189.25 ', Port:' 3306 ', User:' Iyy ', Password:' [Email protected] ', Database:' Anthony ', Connectionlimit:20//Connection Pool Maximum number of connections    //Waitforconnections:false}//get a link from the databaseExports.getconnection =function(){    returnmysql.createconnection (dbconfig); }exports.getpool=function(){    varPool =Mysql.createpool (dbconfig); returnPool;}
This allows you to manipulate the database directly in the controller module as follows:
Context.dbPool.getConnection (function(err,connection) {if(Err) {Emitter.emit ("Connectfailed", result, context); return false; }        //can be further split into the module. Connection.query ("Delete from MailModule where id=" +intdeleteid,function(err,res) {if(Err) {Emitter.emit ("Queryfailed", result, context); return false; }            /*Emitter.on ("Success", function (result, context) {Result.errcode = 0;                Result.msg = "Success";                var str= ' Updateuserinfo_callback ({"ret": 2, "errmsg": "Asdas"}) ';            Context.renderjson (str);             }); */Emitter.emit ("Success", result, context);        }); //Release LinkConnection.end (); });

A kind of nodejs MVC framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.