Browse Source

Fix something

HonorLee 6 years ago
parent
commit
a29d97dd1a
10 changed files with 184 additions and 52 deletions
  1. 43 0
      CHANGELOG.md
  2. 2 1
      README.md
  3. 40 18
      config.js
  4. 1 0
      package.json
  5. 3 4
      server.js
  6. 28 10
      system/core.js
  7. 18 0
      system/lib/core/hook.js
  8. 36 18
      system/lib/core/router.js
  9. 9 1
      system/lib/core/session.js
  10. 4 0
      system/lib/core/system.js

+ 43 - 0
CHANGELOG.md

@@ -0,0 +1,43 @@
+# CHANGELOG
+
+## [Unreleased]
+
+## [0.5] - 2018-05-01
+## Added
+-
+
+## Changed
+- `Router`路由器由原来加载控制器全局静态Handler类改为加载新的控制器Handler实例来处理单个业务请求;在调用控制器方法时由显示传入Request和Reponse两个对象的改为将两个对象赋值为控制器Handler实例属性
+- `Router`路由器加入路径缓存,与上一调整同时进行路由优化,整体运行性能提升300%
+
+## [0.4] - 2018-?-?
+### Added
+- 静态扩展库Helper支持
+
+### Changed
+- 重写Mysql数据库连接池,直接采用官方提供的Mysql-Pool
+- 日志处理程序扩展,加入`Log`,`Debug`,`Info`,`Error`四个不同类型以及对应输出表现
+
+## [0.3] - 2017-?-?
+### Added
+- 加入POST表单(文件)上传的文件预处理
+- 加入基础Session功能并以文件方式进行存储
+- 控制器构造函数`__construct`支持,调用控制器方法时会优先调用该方法
+
+###Fixed
+- 修正Mysql连接池自动断开问题
+
+## [0.2] - 2017-?-?
+### Added
+- Mysql数据库支持,采用NPM的Mysql基础库,实现简单的连接池
+- MongoDB数据库支持,采用NPM的MongoDB基础库
+- 调试日志的输出及存储
+- 自动创建项目目录结构
+
+## [0.1] - 2017-?-?
+### Added
+- 基础的MVC架构实现
+- 参考了PHP的MVC框架-Codeigniter建立了的灵活路由器,无需手动设置路由规则即可自行快速查找请求的文件或控制器
+- GET,POST请求预处理并形成字段
+- 基本的静态文件(图片,样式等)支持;可实现基本的MVC开发工作
+

+ 2 - 1
README.md

@@ -1 +1,2 @@
-Report!
+基于NodeJS的MVC快速开发框架
+

+ 40 - 18
config.js

@@ -1,17 +1,32 @@
 global.Config = {
-    ServerName:'',
-    ServerPort:8080,
-    //Session ExpireTime min.
+
+//Server Setting | 服务器基本信息设置
+Server:{
+    Name:'',
+    Host:'',
+    Port:8080
+},
+
+//Session Setting | Session配置
+Session:{
+    //Session Expire Time min.
     SessionExpire : 30,
-    RenewSessionOnRead:true,
+    //No expire while surfing
+    AutoRefresh:true,
+    //Session store type && Support 'File' or 'Memcache'
+    //If using memcache,Memcache setting must be modified
+    StoreType:'File'
+},
+//Asset setting
+Asset:{
     //Asset path
     asset_path  : 'asset',
     upload_path : 'asset/upload',
-    //WhiteList
-    BlackList : {},
-    //Mysql config
-    mysql_on : false,
-    mysql_cfg : {
+},
+
+Database:{
+    Mysql:{
+        on:false,
         host:'localhost',
         port:3306,
         user:'root',
@@ -20,20 +35,27 @@ global.Config = {
         prefix:'',
         connectionLimit:10
     },
-    //Mongodb config
-    mongodb_on : false,
-    mongodb_cfg : {
+    Mongodb:{
+        on:false,
         host:'localhost',
         port:27017,
         user:null,
         password:'',
         database:'',
         prefix:''
-
     },
-    //If Debug on,log && info logs will output in console;except Error!
-    debug:true,
-    //if write file on,logs will write in log files
-    write_log_file:true,
-    write_error_file:true
+    Memcache:{
+        on:true,
+        host:'localhost',
+        port:11211
+    }
+
+},
+    
+//If Debug on,log && info logs will output in console;except Error!
+debug:true,
+//if write file on,logs will write in log files
+write_log_file:false,
+write_error_file:true,
+
 };

+ 1 - 0
package.json

@@ -17,6 +17,7 @@
     "fs-extra": "^0.30.0",
     "js-base64": "^2.1.9",
     "md5": "^2.2.1",
+    "memcached": "^2.2.2",
     "mime-types": "^2.1.11",
     "mongodb": "^2.2.25",
     "mysql": "^2.11.1",

+ 3 - 4
server.js

@@ -16,12 +16,11 @@ global.serverUID = (Math.ceil(Math.random()*61439+4096)).toString(16).toUpperCas
 require('./config.js');
 require('./system/core.js');
 
-let serverPort = Config.ServerPort;
 try{
-    require('http').createServer(serverHandler).listen(serverPort);
-    LOGGER.info('Child Server ['+serverUID+'] start at port [' + serverPort + '] | ' + DateFormat('yyyy/MM/dd hh:mm:ss', new Date()));
+    require('http').createServer(serverHandler).listen(Config.Server.Port);
+    LOGGER.info('Child Server ['+serverUID+'] start at port [' + Config.Server.Port + '] | ' + DateFormat('yyyy/MM/dd hh:mm:ss', new Date()));
 }catch(e){
-    LOGGER.error('Child Server ['+serverUID+'] failed start at port [' + serverPort + '] | ' + DateFormat('yyyy/MM/dd hh:mm:ss', new Date()));
+    LOGGER.error('Child Server ['+serverUID+'] failed start at port [' + Config.Server.Port + '] | ' + DateFormat('yyyy/MM/dd hh:mm:ss', new Date()));
 }
 
 

+ 28 - 10
system/core.js

@@ -1,5 +1,6 @@
 'use strict';
-global.Core = {};
+global.Core  = {};
+global.CACHE = {};
 
 //Global Path
 global.Core.Path = {
@@ -14,8 +15,8 @@ global.Core.Path = {
     Temp        : ROOTPATH + '/temp',
     Session     : ROOTPATH + '/temp/session',
     Log         : ROOTPATH + '/log',
-    Asset       : ROOTPATH + '/' + Config.asset_path,
-    Upload      : ROOTPATH + '/' + Config.upload_path
+    Asset       : ROOTPATH + '/' + Config.Asset.asset_path,
+    Upload      : ROOTPATH + '/' + Config.Asset.upload_path
 };
 
 //Global Extension Require
@@ -46,6 +47,7 @@ CoreLibFiles.forEach(function(filename){
         Tracer.error('[Core] Core library file ['+filename+'] load error!');
     }
 });
+CoreLibFiles = null;
 //System Library load end
 
 
@@ -53,8 +55,8 @@ CoreLibFiles.forEach(function(filename){
 global.Core.Setting = {};
 
 //If Mysql on,load Mysql Extension
-if(Config && Config.mysql_on && Config.mysql_cfg){
-    let MysqlPool    = require(Core.Path.ExtraLib + '/mysql-pool.js').instance(Config.mysql_cfg);
+if(Config && Config.Database.Mysql.on){
+    let MysqlPool    = require(Core.Path.ExtraLib + '/mysql-pool.js').instance(Config.Database.Mysql);
     let testMysqlCon = MysqlPool.getConnection(function(err,connection){
         connection.release();
         if(!err){
@@ -64,7 +66,7 @@ if(Config && Config.mysql_on && Config.mysql_cfg){
                     LOGGER.error(err);
                 }else{
                     LOGGER.info('Mysql Connect success');
-                    LOGGER.info('Mysql Version: ' + result[0]['version'] + ' | User: ' + Config.mysql_cfg.user + ' | Database: ' + Config.mysql_cfg.database);
+                    LOGGER.info('Mysql Version: ' + result[0]['version'] + ' | User: ' + Config.Database.Mysql.user + ' | Database: ' + Config.Database.Mysql.database);
                     global.MysqlPool = MysqlPool;
                     global.MysqlDB   = require(Core.Path.Helper + '/mysqldb.js');
                 }
@@ -75,9 +77,9 @@ if(Config && Config.mysql_on && Config.mysql_cfg){
 }
 
 //If Mongodb on,load Mongodb Extension
-if(Config && Config.mongodb_on && Config.mongodb_cfg && Config.mongodb_cfg.database){
-    let verify = Config.mongodb_cfg.user?Config.mongodb_cfg.user+':'+Config.mongodb_cfg.password+'@':'';
-    let mongoConnect = 'mongodb://' + verify + Config.mongodb_cfg.host+':'+Config.mongodb_cfg.port+'/'+Config.mongodb_cfg.database;
+if(Config && Config.Database.Mongodb.on && Config.Database.Mongodb.database){
+    let verify = Config.Database.Mongodb.user?Config.Database.Mongodb.user+':'+Config.Database.Mongodb.password+'@':'';
+    let mongoConnect = 'mongodb://' + verify + Config.Database.Mongodb.host+':'+Config.Database.Mongodb.port+'/'+Config.Database.Mongodb.database;
     require('mongodb').MongoClient.connect(mongoConnect,function(err,db){
         if(err) {
             LOGGER.error('MongoDB connect error!',true);
@@ -89,11 +91,27 @@ if(Config && Config.mongodb_on && Config.mongodb_cfg && Config.mongodb_cfg.datab
         global.MongoDB = {db:db};
         global.MG = function(collection){
             if(!collection) return null;
-            return MongoDB.db.collection(Config.mongodb_cfg.prefix+collection);
+            return MongoDB.db.collection(Config.Database.Mongodb.prefix+collection);
         };
     });
 }
 
+//If Memcache on,load Memcache Extension
+if(Config && Config.Database.Memcache.on){
+    let Memclass  = require('memcached');
+    let Memcache  = new Memclass(Config.Database.Memcache.host+':'+Config.Database.Memcache.port);
+    Memcache.version(function(err,data){
+        if(err){
+            LOGGER.error('Memcache Connect error,please recheck your config');
+            LOGGER.error(err);
+        }else{
+            LOGGER.info('Memcache Connect success');
+            LOGGER.info('Memcache Version: ' + data[0]['version']);
+            global.Memcache = Memcache;
+        }
+    });
+}
+
 //Check File Paths
 for(let path in global.Core.Path){
     try{

+ 18 - 0
system/lib/core/hook.js

@@ -0,0 +1,18 @@
+'use strict'
+let HookList = {};
+
+module.exports = {
+    Event:{
+        Router:1
+    },
+    registerHook:function(hookName,callback){
+
+    },
+    triggerHook:function(hookName,callback){
+        if(!HookList.hasOwnProperty(hookName) || HookList[hookName].length==0){
+            callback();
+            return;
+        }
+        
+    }
+}

+ 36 - 18
system/lib/core/router.js

@@ -1,4 +1,6 @@
 'use strict'
+CACHE.router = {};
+
 var Router ={
     goAsset:function(path,req,res){
         let assetFile = Core.Path.Asset+path;
@@ -12,41 +14,57 @@ var Router ={
     },
     goHandler:function(path,req,res){
         let handlerFile = Core.Path.Handler + path + '.js';
-        let method = 'index';
         let pathArr = path.split('/');
-        let Res = res;
-        let Req = req;
+        let method = pathArr.pop();
+
+        if(!method) method = 'index';
 
+        if(CACHE.router[handlerFile]){
+            Router.runHandler(handlerFile,method,req,res);
+            return;
+        }
         FILE.stat(handlerFile,function(err,status){
             if(err || !status.isFile()){
-                method = pathArr.pop();
-                if(pathArr.length<=1) return Router._error('No such handler ['+handlerFile+']',Res);
+                if(pathArr.length<=1) return Router._error('No such handler ['+handlerFile+']',res);
                 handlerFile = Core.Path.Handler + pathArr.join('/') + '.js';
                 FILE.stat(handlerFile,function(err,status){
                     if(err || !status.isFile()){
-                        Router._error('No such handler ['+handlerFile+']',Res);
+                        Router._error('No such handler ['+handlerFile+']',res);
                     }else{
-                        Router.runHandler(handlerFile,method,Req,Res);
+                        Router.runHandler(handlerFile,method,req,res);
                     }
                 });
             }else{
-                Router.runHandler(handlerFile,method,Req,Res);
+                Router.runHandler(handlerFile,method,req,res);
             }
         });
     },
     runHandler:function(handlerFile,method,req,res){
+        let handler;
         try {
-            let handler = require(handlerFile);
-            if(typeof handler[method]==='function'){
-                let noBypass = true;
-                if(typeof handler['__construct']==='function') noBypass = handler['__construct'](req,res);
-                if(noBypass || noBypass===undefined) handler[method](req,res);
-            }else{
-                Router._error('Handler ['+handlerFile+'] no such method "'+method+'"',res);
-            }
+            handler = require(handlerFile);
         }catch(e){
             Router._error(e.stack,res);
         }
+
+        let newHandlerClass = Object.assign({
+            'Request'  : req,
+            'Response' : res,
+            'COOKIE'   : req._Cookie,
+            'GET'      : req._GET,
+            'POST'     : req._POST,
+            'UPLOAD'   : req._UPLOAD
+        },handler);
+        
+        if(!CACHE.router[handlerFile]){ CACHE.router[handlerFile] = true;}
+
+        if(newHandlerClass.hasOwnProperty(method) && typeof newHandlerClass[method]==='function'){
+            let noBypass = true;
+            if(newHandlerClass.hasOwnProperty('__construct') && typeof newHandlerClass['__construct']==='function') noBypass = newHandlerClass['__construct']();
+            if(noBypass || noBypass===undefined) newHandlerClass[method]();
+        }else{
+            Router._error('Handler ['+handlerFile+'] no such method "'+method+'"',res);
+        }
     },
     _error:function(log,res){
         LOGGER.error(log);
@@ -60,11 +78,11 @@ module.exports = function(req,res){
     let URLParse  = URL.parse(URI,true);
     let URLArr    = URLParse.pathname.split('/');
     let enterURI  = String(URLArr[1])==''?'index':String(URLArr[1]);
-    let isAsset   = enterURI == Config.asset_path;
+    let isAsset   = enterURI == Config.Asset.asset_path;
 
     req._GET = URLParse.query;
     if(isAsset){
-        let assetPath = URLArr.join('/').replace('/'+Config.asset_path,'');
+        let assetPath = URLArr.join('/').replace('/'+Config.Asset.asset_path,'');
         Router.goAsset(assetPath,req,res);
         return;
     }

+ 9 - 1
system/lib/core/session.js

@@ -48,4 +48,12 @@ var Session = {
         }catch(e){}
     }
 };
-module.exports = Session;
+module.exports = Session;
+
+var FileManager = {
+
+}
+
+var Session = {
+    
+}

+ 4 - 0
system/lib/core/system.js

@@ -0,0 +1,4 @@
+'use stict'
+module.exports = {
+
+}